Noa Regev
Noa Regev

Reputation: 5

how do I init a base constructor within curly braces of derived constructor? c++

I'm trying to initialize a base-class member item through a derived class. The problem I have is that the value I'm passing is dependant of "x". so here's what I'm doing:

Derived:: Derived()
{
    uint8 number = getNumber();
    P p;

    if (number == 3)
    {
         p = P1;
    }
    else
    {
    p = P2;
    }

    Base(p);
}

I get the error "no default constructor exists for class "Base". What am I doing wrong?

Upvotes: 0

Views: 347

Answers (1)

You can only initialize a base class in the member initializer list sequence of a constructor. If that requires calling some other code, you can delegate that to a helper function:

P calculate_p() {
  uint8 number = getNumber();
  if (number == 3)
    return P1;

  return P2; 
}

Derived::Derived() : Base(calculate_p())
{
}

Upvotes: 3

Related Questions