Sign in to follow this  
Winegums

Inherited class constructors

Recommended Posts

Winegums    286
Hi, in C++ if i inherit class B from class A, in class B's constructor when is class A's constructor called? Is it called before class B's constructor? I think it is, since it's almost called in the function definition itself, but just not 100%. thanks.

Share this post


Link to post
Share on other sites
Agony    3452
Only the base class's default constructor is called (and it isn't called directly, but from the derived class's constructor). If you want to call any non-default constructor, you'll have to do that manually.

Given these two class declarations:
class Base
{
public:
Base();
Base(int n);
Base(const std::string& s);
};

class Derived : public Base
{
public:
};

then the only constructor available for the Derived class is the default, parameter-less version. This will automatically call Base(). If we modify Derived to be:
class Derived : public Base
{
public:
Derived();
Derived(int n);
Derived(const std::string& s);
};

then all three versions will automatically call Base(). Base(int) and Base(const std::string&) will not get used. If you want to use them, then when writing the definitions for Derived's functions, do the following:
Derived::Derived() : Base()
{
}

Derived::Derived(int n) : Base(n)
{
}

Derived::Derived(const std::string& s) : Base(s)
{
}

Additionally, if Base takes completely different parameters from Derived, but Derived's parameters can be mapped to Base's parameters in some way or another, then this can be performed too:
class Base
{
public:
Base(int a, int b, double c);
};

class Derived : public Base
{
public:
Derived(int d, const std::string& s, bool e);
};

Derived::Derived(int d, const std::string& s, bool e)
: Base((d + 14) * 3, s.length(), 3.7)
{
//Base doesn't need information from e, but
// Derived can use it here
}

This syntax for initializing a base is essentially the same for initializing any members:
class SomeClass
{
public:
SomeClass();
SomeClass(int a, int b, const std::string& c);

private:
int mA;
double mB;
std::string mC;
};

SomeClass::SomeClass() : mA(0), mB(0), mC("") //std::string default constructor
//will do the same thing, so this
//last one isn't really needed.
{
}

SomeClass::SomeClass(int a, int b, const std::string& c) : mA(a), mB(b), mC(c)
{
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this