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

loop
  • 3,460
  • 5
  • 34
  • 57
  • 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`. – chris Aug 30 '12 at 23:14
  • possible duplicate of [c++ calling non-default constructor as member](http://stackoverflow.com/questions/3643548/c-calling-non-default-constructor-as-member) – jogojapan Aug 31 '12 at 00:54

1 Answers1

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.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806