Say I have a base class:
class baseClass
{
public:
baseClass() { };
};
And a derived class:
class derClass : public baseClass
{
public:
derClass() { };
};
When I create an instance of derClass
the constructor of baseClass
is called. How can I prevent this?
How to call the parameterized constructor of base class in derived class constructor? To call the parameterized constructor of base class when derived class's parameterized constructor is called, you have to explicitly specify the base class's parameterized constructor in derived class as shown in below program: C++
In Inheritance, the child class acquires the properties of the base class or parent class. You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class. Example: Javascript.
In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.
Use super(). __init__() to call the immediate parent class constructor. Call super(). __init__(args) within the child class to call the constructor of the immediate parent class with the arguments args .
Make an additional empty constructor.
struct noprapere_tag {};
class baseClass
{
public:
baseClass() : x (5), y(6) { };
baseClass(noprapere_tag) { }; // nothing to do
protected:
int x;
int y;
};
class derClass : public baseClass
{
public:
derClass() : baseClass (noprapere_tag) { };
};
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