Override or remove inherited constructor

Here is the 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 result:

mother  
mother  
daughter

My problem is that I do not want the constructor m to be called when creating N. What should I do?

+3
source share
5 answers

AFAIK, you cannot remove the inherited constructor.

The problem in your example comes from the wrong class design. The constructor is usually used to allocate class resources, set default values, etc. This is not quite suitable for outputting anything.

You have to put

n() { cout << "daughter" << endl; }

Into a virtual function.

In general, if you need to remove an inherited constructor, you probably need to rethink / redesign the class hierarchy.

+9
source
class m
{
public:
      m(bool init = true) { if (init) cout << "mother" << endl; }
};


class n : m
{
public:
      n() : m(false) { cout << "daughter" << endl; }
};

,

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; }
};
+1

. , ++ , . , , , , , .

+1

:

  • n m. , ( ) . m* n, m . .

  • , , , m , , . , m, init() , . , .

0

- . . . .

0

Source: https://habr.com/ru/post/1752596/


All Articles