0

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)
{
    ....
}

3 Answers 3

3

Yes. Use

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

and same for C.

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

Comments

0

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);

1 Comment

Brilliant - thank you. For anyone looking at this answer You should not include type names in function calls... it confuses the compiler. Something I had to work out :-)
0

You can use following syntax:

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

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.