Reputation: 100
I have searched for it and this seems to be the only way of calling a superclass constructor in C++:
class SuperClass
{
public:
SuperClass(int foo)
{
// do something with foo
}
};
class SubClass : public SuperClass
{
public:
SubClass(int foo, int bar)
: SuperClass(foo) // Call the superclass constructor in the subclass' initialization list.
{
// do something with bar
}
};
But I'd like to know, how can I call the superclass constructor in the constructor body instead of initialization list?
I have to process inputs of my child's constructor and pass complex processed parameters to superclass constructor, how do I achieve that?
Upvotes: 3
Views: 14838
Reputation: 33932
A base class constructor must be run to initialize the base before you can enter the body of the derived class constructor. The Member Initializer List is the only way to initialize the base class. If you have complex requirements for the parameters, use helper functions to compute the parameters.
Example:
class SuperClass
{
public:
SuperClass(int foo)
{
// do something with foo
}
};
class SubClass : public SuperClass
{
private:
static int basehelper(int foo)
{
// do complicated things to foo
return result_of_complicated_things;
}
public:
SubClass(int foo, int bar)
: SuperClass(basehelper(foo)) // Call the superclass constructor in the subclass' initialization list.
{
// do something with bar
}
};
If the base class parameters require knowledge known only as the derived class is constructed, you must either
Upvotes: 7
Reputation: 9058
You can't.
The parent portion of your class must be initialized before your child can start. So you have to do it at the front of your initializer list.
However, you could have Superclass::initialize() that does what you need to do, and your Superclass constructor can call it.
Upvotes: 2