How to Call the Base Class Constructor in C++

c++constructor

Lately, I have done much programming in Java. There, you call the class you inherited from with super(). (You all probably know that.)

Now I have a class in C++, which has a default constructor which takes some arguments. Example:

class BaseClass {
public:
    BaseClass(char *name); .... 

If I inherit the class, it gives me the warning that there is no appropriate default constructor available. So, is there something like super() in C++, or do I have to define a function where I initialize all variables?

Best Answer

You do this in the initializer-list of the constructor of the subclass.

class Foo : public BaseClass {
public:
    Foo() : BaseClass("asdf") {}
};

Base-class constructors that take arguments have to be called there before any members are initialized.

Related Question