Not calling base class constructor from derived class

15,098

Solution 1

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) { };

};

Solution 2

A base class instance is an integral part of any derived class instance. If you successfully construct a derived class instance you must - by definition - construct all base class and member objects otherwise the construction of the derived object would have failed. Constructing a base class instance involves calling one of its constructors.

This is fundamental to how inheritance works in C++.

Solution 3

Sample working program

#include <iostream>

using namespace std;
class A
{
    public:
    A()
    {
        cout<<"a\n";
    }
    A(int a)
    {}
};
class B:public A
{
    public:
    B() : A(10)
    {
        cout<<"b\n";
    }
   
};
int main()
{
    
    new A;
    cout<<"----------\n";
    new B;
    
    return 0;
}

output

a                                                                                                        
----------                                                                                               
b   
Share:
15,098
Brad
Author by

Brad

Updated on June 16, 2022

Comments

  • Brad
    Brad about 2 years

    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?