KingJohnno
KingJohnno

Reputation: 602

Using base default constructor (with parameters) for child class

I have a class A which has to have a a class passed to it; From A I have two classes B and C; is it possible for B and C to use the constructor from A, as apposed to the default constructor.

     A
    / \
   B   C 

A::A(randomNumber &rnd)
{
    ....
}

Upvotes: 0

Views: 835

Answers (3)

Azodious
Azodious

Reputation: 13872

You can use following syntax:

B::B() : A(aRandomNum)
{
    ....
}

Upvotes: 0

Andy Prowl
Andy Prowl

Reputation: 126432

Yes, it is possible:

class B
{
public:
    B(randomNumber& rnd) : A(rnd) { }
    // ...
};

If you want to call A's constructor in B's default constructor, you will have to pass a global object: since A's construct accepts an lvalue reference, creating a temporary is not an option.

B() : A(global_random_number);

Upvotes: 0

ForEveR
ForEveR

Reputation: 55887

Yes. Use

class B {
public:
   B() : A(someRndNum) {}
};

and same for C.

Upvotes: 3

Related Questions