1

Feel free to edit the title I'm not sure how to phrase this.

I'm trying to figure out how to call a class's constructor other than the default when it is instantiated in another class. What I mean is this...

class A
{
public:
    A(){cout << "i get this default constructor when I create a B" << endl;}
    A(int i){cout << "this is the constructor i want when I create a B" << endl;}
};

class B
{
    A a;
};

int main()
{
    B *ptr = new B;
    return 0;
}

I've done some searching but I don't see a way to do what I want. I thought maybe in B's declaration I could do A a(5) but that doesn't work.

Thanks

2
  • Just a note: that B *ptr = new B; can be replaced by the safer B obj;. You won't have to free any memory. If you still need a pointer, consider std::unique_ptr. Commented Aug 30, 2012 at 23:14
  • possible duplicate of c++ calling non-default constructor as member Commented Aug 31, 2012 at 0:54

1 Answer 1

10

You can do that with a constructor initialization list (you might also want to look at this question and others similar to it).

This means that you will have to manually write a constructor for B:

class B
{
    A a;

    public: B() : a(5) {}
};

See it in action.

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

1 Comment

Thanks that worked. I like your example tool it's pretty cool.

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.