I have the following situation (the below is just for illustration):
class Base()
{
public:
Base(int);
};
class Derived : public Base
{
public:
Derived(int, int, bool);
};
I want to initialise the base class depending on the boolean flag in the derived constructor. What (if any) is the correct way of doing so ..
I could do (but is the evaluation done before Base is initialised?):
Derived::Derived(int _x, int _y, bool _z) : Base(_z?_x:_y) {}
or (but this probably doesn't work properly)
Derived::Derived(int _x, int _y, bool _z)
{
if(_z)
::Base(_x);
else
::Base(_y);
}
If there is no correct way of doing this then I could possibly get away with adding additional constructors to Derived.
Derived::Derived(int _x, int _y, bool _z) : Base( compute_value() ) {})class Base()is wrong, remove the parens. The 1st proposal you've made is fine, the evaluation will be made before theBase()constructor is called.if, creates a temporary object of typeBaseand immediately destroys it.