How to avoid calling the constructor of parent class?

 

Hi, I have the problem that when an object of the child class is created, the constructor of the parent class is called without notice.

class ClassA {
  public:
  ClassA(){
    Print("ClassA Constructor");
  };
};

class ClassB:public ClassA {
  public:
  ClassB(){
    Print("ClasB");
  }

};


int OnInit()
{
  ClassB* cb = new ClassB();


  return(INIT_SUCCEEDED);
}


Output:


🤔

Files:
 
Eugen Funk:

Hi, I have the problem that when an object of the child class is created, the constructor of the parent class is called without notice.


Output:


🤔

Practically not possible. What you can do is this:

class A
{
    A() = delete;
};

class B : public A
{
    B()
    {};
};

Or this:

class A
{
};

class B : public A
{
    B()
    {};
};

But why???

EDIT:

Try to compile it and see what happens....

 

nah, because the classB has other tasks than classA ... 
Ok, i changed the structure little bit the stuff works as I need it - but strange. C++ and other languages are different.


Thank you!

 
Eugen Funk:

Hi, I have the problem that when an object of the child class is created, the constructor of the parent class is called without notice.


Output:


🤔

What a bad idea !

The constructor of A NEEDS to be called.

 
Alain Verleyen #:

What a bad idea !

The constructor of A NEEDS to be called.

Of course, and omitting it in A will just create an implicit constructor...

EDIT:
I would say, there is a fundamental design flaw, if you need to do something like that.
 
Dominik Egert #:
Of course, and omitting it in A will just create an implicit constructor...
And the "delete" version doesn't compile.
 
Eugen Funk #:

nah, because the classB has other tasks than classA ... 
Ok, i changed the structure little bit the stuff works as I need it - but strange. C++ and other languages are different.


Thank you!

What language allows to create a subclass which doesn't call the parent constructor ?
 
Alain Verleyen #:
And the "delete" version doesn't compile.
Of course not...
 
Alain Verleyen #:
What language allows to create a subclass which doesn't call the parent constructor ?

C++, Python, ... You usually need to call it explicitly via super(),

ClassB(int x):ClassA(x){...}
 
Eugen Funk #:

C++, Python, ... You usually need to call it explicitly via super(),

C++ is similar to MQL in that regards.

Even if C++ allow to somehow to not call the base constructor (as far as I know it's done implicitly if not explicitly), it's really a strange requirement. I can't imagine something else that a bad design.

 
Eugen Funk #:

C++, Python, ... You usually need to call it explicitly via super(),

as reference, take a look here:


It's C++11