I've reduced my problem down to the following example code:
class pokemon{
public:
pokemon(int n);
};
class MewTwo : public pokemon {
public:
MewTwo(int n);
};
MewTwo::MewTwo(int n) {}
Which produces an error:
no matching function for call to ‘pokemon::pokemon()’
What I think is happening is that a default constructor for pokemon is called when I try to write the MewTwo constructor, which doesn't exist. I'm relatively new to C++ so I'm just guessing here. Any ideas?
Restraint: Fixes cannot modify or add public members to the classes.
A parent class constructor is not inherited in child class and this is why super() is added automatically in child class constructor if there is no explicit call to super or this.
This is one reason constructors aren't inherited. Inheritance means a derived object can use a base-class method, but, in the case of constructors, the object doesn't exist until after the constructor has done its work. I understand the constructor is called before object construction is completed.
When classes are inherited, the constructors are called in the same order as the classes are inherited. If we have a base class and one derived class that inherits this base class, then the base class constructor (whether default or parameterized) will be called first followed by the derived class constructor.
In case of inheritance if we create an object of child class then the parent class constructor will be called before child class constructor. i.e. The constructor calling order will be top to bottom. So as we can see in the output, the constructor of Animal class(Base class) is called before Dog class(Child).
Actually what you are looking for is the member initialization list. Change your inherited class constructor to the following:
class MewTwo : public pokemon {
public:
MewTwo(int n) : pokemon(n) {}
};
You were correct in identifying what was going on. Basically when you create the inherited class you first create the base class and you can't do that because there is no default constructor defined. Member initialization lists help you get around that :)
Check out : http://www.cprogramming.com/tutorial/initialization-lists-c++.html for more examples!
Try this :
class pokemon{
public:
pokemon(int n);
};
class MewTwo : public pokemon {
public:
MewTwo(int n) :pokemon(n){}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With