Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call the base class 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?

like image 773
Stefan Avatar asked Aug 03 '11 08:08

Stefan


People also ask

Do you have to call base class constructor?

If a class do not have any constructor then default constructor will be called. But if we have created any parameterized constructor then we have to initialize base class constructor from derived class. We have to call constructor from another constructor. It is also known as constructor chaining.

How do you call a base constructor in C ++?

If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".

Is base class constructor called automatically?

Using your example, the answer is: YES. The base constructor will be called for you and you do not need to add one. You are only REQUIRED to use "base(...)" calls in your derived class if you added a constructor with parameters to your Base Class, and didn't add an explicit default constructor.

Why is base constructor called first?

A technical reason for this construction order is that compilers typically initialize the data needed for polymorphism (vtable pointers) in constructors. So first a base class constructor initializes this for its class, then the derived class constructor overwrites this data for the derived class.


1 Answers

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.

like image 64
Björn Pollex Avatar answered Sep 30 '22 18:09

Björn Pollex