How do you use the non-default constructor for a member?

Jeremy Salwen picture Jeremy Salwen · Jan 18, 2010 · Viewed 14.9k times · Source

I have two classes

class a {
    public:
        a(int i);
};

class b {
    public:
        b(); //Gives me an error here, because it tries to find constructor a::a()
        a aInstance;
}

How can I get it so that aInstance is instantiated with a(int i) instead of trying to search for a default constructor? Basically, I want to control the calling of a's constructor from within b's constructor.

Answer

i_am_jorf picture i_am_jorf · Jan 18, 2010

You need to call a(int) explicitly in the constructor initializer list:

b() : aInstance(3) {} 

Where 3 is the initial value you'd like to use. Though it could be any int. See comments for important notes on order and other caveats.