Reputation: 10660
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
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
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
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
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