views:

55

answers:

2

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?

+2  A: 

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

Charles Bailey
+1  A: 

Make additional empty ctor.

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

};
Alexey Malistov