3

I fear that this is a very basic question, however, I was not able to solve it yet.

I have a class A

// classA.h
...

class ClassA {
    public:
        ClassA();
        ClassA(int foo);
    private:
        int _foo;

    ...

}

// classA.cpp

ClassA::ClassA() {
    _foo = 0;
}

ClassA::ClassA(int foo) {
    _foo = foo;
}

...

A second class B uses an instance of class A in the constructor:

// classB.h
...

#include "classA.h"

#define bar 5

class ClassB {
    public:
        ClassB();
    private:
        ClassA _objectA;

    ...

}

// classB.cpp

ClassB::ClassB() {
    _objectA = ClassA(bar);
}

...

Note that the default constructor of class A is never used. In fact in my real world use case it would not even make sense to use any kind of a default constructor as _foo has to be dynamically assigned.

However, if I remove the default constructor, the compiler returns an error:

no matching function for call to 'ClassA::ClassA()'

Is there a way to use an instance of class A as an object in class B without defining a default constructor for class A? How would this be done?

1
  • 1
    Note that the default constructor of class A is never used -- With your current code, it is being used here: ClassA _objectA; even if you didn't mean to do so. Commented Nov 17, 2016 at 21:35

2 Answers 2

3

The default constructor of ClassA is used. ClassB's _objectA is initialized with it and then you assign ClassA(bar) to it.

You can solve your problem by using constructor initializer lists:

ClassB::ClassB() : _objectA(bar)
{}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! Your answer leads to a follow-up question, but it is a step further :)
3

Just write

ClassB::ClassB() :  _objectA(bar)
{
}

The problem is that when the body of the constructor of the ClassB is executed the data member _objectA is already constructed and inside the body there is used the copy assignment operator

ClassB::ClassB() {
    _objectA = ClassA(bar);
   ^^^^^^^^^^^^^^^^^^^^^^^^
}

Thus you can remove the default constructor of the ClassA.

1 Comment

thank you! Your answer leads to a follow-up question, but it is a step further :)

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.