2

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.

3
  • 2
    The first solution is the correct one (using the ternary operator). If you have a more complex initialization to compute the value of the Base parameter, you can use a (free or not) function call (Derived::Derived(int _x, int _y, bool _z) : Base( compute_value() ) {}) Commented Feb 13, 2013 at 10:44
  • class Base() is wrong, remove the parens. The 1st proposal you've made is fine, the evaluation will be made before the Base() constructor is called. Commented Feb 13, 2013 at 10:47
  • 1
    The second one, in each branch of the if, creates a temporary object of type Base and immediately destroys it. Commented Feb 13, 2013 at 13:33

3 Answers 3

3
 Derived::Derived(int _x, int _y, bool _z) : Base(_z?_x:_y) {}

Is the correct way. You could only call base constructor with parameter in member initializers list

Sign up to request clarification or add additional context in comments.

Comments

2

Your first alternative is the correct one: use the initialisation list.

The second alternative doesn’t work.

Comments

2

The first alternative is the only one of your alternatives that will work. The constructor of the derived class will be called after the constructor of the base-class, so your second option is invalid.

Now, of course, the question is whether this is the "right" thing to do. Since it may be that you should have two derived classes, rather than one. I'm not saying what you are doing is wrong as such, it's just something to bear in mind.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.