Rules for calling base class constructor in C++
Hello everyone! I started learning C++ and ran into a problem with inheritance and constructors. I have a base class `Animal` and a derived class `Dog`. I want the `Animal` constructor that takes a name to be automatically called when creating a `Dog` object. But I can't get it to work.
Here's my code:
```cpp
#include
#include
class Animal {
public:
Animal(const std::string& name) : name_(name) {
std::cout << "Animal constructor called for " << name_ << std::endl;
}
private:
std::string name_;
};
class Dog : public Animal {
public:
Dog(const std::string& breed) : breed_(breed) {
std::cout << "Dog constructor called for breed " << breed_ << std::endl;
}
private:
std::string breed_;
};
int main() {
No answers yet.
Log in to leave an answer