Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override or remove an inherited constructor

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 ?

like image 767
gokoon Avatar asked Jul 01 '10 09:07

gokoon


People also ask

Can we override constructor in Java in inheritance?

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.

Can you override constructor in C++?

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.

Can a child class override the constructor of parent class in Java?

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.

Can we override destructor in C++?

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.


2 Answers

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.

like image 141
SigTerm Avatar answered Oct 18 '22 06:10

SigTerm


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; }
};
like image 5
adf88 Avatar answered Oct 18 '22 05:10

adf88