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?
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.
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()".
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.
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.
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.
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