Do not call base class constructor from derived class

Say I have a base class:

class baseClass { public: baseClass() { }; }; 

And the derived class:

 class derClass : public baseClass { public: derClass() { }; }; 

When I create an instance of derClass , the baseClass constructor is baseClass . How can I prevent this?

+6
c ++ class derived-class
source share
2 answers

Make an extra 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) { }; }; 
+11
source share

An instance of a base class is an integral part of any instance of a derived class. If you have successfully created an instance of a derived class, you must - by definition - build all the base classes and member objects, otherwise the construction of the derived object would fail. Building an instance of a base class involves calling one of its constructors.

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

+3
source share

All Articles