Here is some C++ code:
#include <iostream>
using namespace std;
class m
{
public:
m() { cout << "mother" << endl; }
};
class n : m
{
public:
n() { cout << "daughter" << endl; }
};
int main()
{
m M;
n N;
}
Here is the output:
mother
mother
daughter
My problem is that I don't want the m's constructor to be called when I create N. What should I do ?
It does not have a return type and its name is same as the class name. But, a constructor cannot be overridden. If you try to write a super class's constructor in the sub class compiler treats it as a method and expects a return type and generates a compile time error.
Constructors can be overloaded in a similar way as function overloading. Overloaded constructors have the same name (name of the class) but the different number of arguments.
A child class can override any public parent's method that is not defined with the final modifier. Also, classes with final modifier cannot be extended. The Java's String and StringBuffer classes are examples of such classes.
A pure virtual destructor can be declared in C++. After a destructor has been created as a pure virtual object(instance of a class), where the destructor body is provided. This is due to the fact that destructors will not be overridden in derived classes, but will instead be called in reverse order.
AFAIK, you cannot remove inherited constructor.
The problem in your example comes from incorrect class design. Constructor is normally used for allocating class resources, setting default values, and so on. It is not exactly suitable to be used for outputting something.
You should put
n() { cout << "daughter" << endl; }
Into virtual function.
In general - if you have a need to remove inherited constructor, then you probably need to rethink/redesign your class hierarchy.
class m
{
public:
m(bool init = true) { if (init) cout << "mother" << endl; }
};
class n : m
{
public:
n() : m(false) { cout << "daughter" << endl; }
};
or if you don't want it to be public
class m
{
protected:
m(bool init) { if(init) Init(); }
Init() { cout << "mother" << endl; }
public:
m() { Init(); }
};
class n : m
{
public:
n() : m(false) { cout << "daughter" << endl; }
};
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