Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default constructor for an inherited class

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.

like image 451
Coltin Avatar asked Dec 04 '10 05:12

Coltin


People also ask

Is default constructor inherited in Java?

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.

Are default constructors inherited C++?

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.

How constructors are implemented when the classes are inherited?

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.

How do you call a constructor from an inheritance?

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).


2 Answers

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!

like image 133
Victor Parmar Avatar answered Oct 31 '22 07:10

Victor Parmar


Try this :

class pokemon{
    public:
        pokemon(int n);
};

class MewTwo : public pokemon {
    public:
        MewTwo(int n) :pokemon(n){}
};
like image 29
Prasoon Saurav Avatar answered Oct 31 '22 07:10

Prasoon Saurav