Brad
Brad

Reputation: 10660

Not calling base class constructor from derived class

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?

Upvotes: 18

Views: 20500

Answers (4)

Alexey Malistov
Alexey Malistov

Reputation: 26975

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

};

Upvotes: 22

Jindra Helcl
Jindra Helcl

Reputation: 3736

You might want to create a protected (possibly empty) default constructor which would be used by the derived class:

class Base {
protected:
  Base() {}

public:
  int a;
  
  Base(int x) {a = 12;}
};

class Derived : Base {
public:
  Derived(int x) {a = 42;}
};

This will block any external code from using default Base constructor (and thus not initializing a properly). You just need to make sure you initialize all the Base fields in the Derived constructor as well.

Upvotes: 0

Sathvik
Sathvik

Reputation: 654

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   

Upvotes: 2

CB Bailey
CB Bailey

Reputation: 791581

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++.

Upvotes: 9

Related Questions