Jeremy Salwen
Jeremy Salwen

Reputation: 8430

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

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.

Upvotes: 12

Views: 16812

Answers (5)

Clive
Clive

Reputation: 435

The top two answers won't work. You put class declarations in the .h header files, and (member) function definitions in the .cpp files. The braces {} that the respondents have put define the b constructor block. In practice no one would want that empty. Yet you can't define it properly in the .cpp or the compiler will report error of 'redefinition'. (As the linker would anyway if the header file is #included in several translation units) Since the purpose of header files is that they CAN be included in several .cpp's the answers above are unfeasable.

Upvotes: 0

i_am_jorf
i_am_jorf

Reputation: 54600

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.

Upvotes: 24

Maurits Rijk
Maurits Rijk

Reputation: 9985

I think you should use a pointer to 'a' like:

class b {
public:
    b() : aInstance(new a(5)) {}
    a *aInstance;
};

This way you will have defined behaviour. Of course you will need to free *aInstance in the destructor.

Upvotes: -2

Dmitry
Dmitry

Reputation: 6770

Just use a constructor which is defined like this:

class b {
public:
    b()
    : aInstance(5)
    {}
    a aInstance;
};

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490108

Use an initialization list:

b::b() : aInstance(1) {}

Upvotes: 3

Related Questions