Search code examples
c++constructorinstance-variablesdefault-constructor

use parameterized constructor in other classes constructor


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?


Solution

  • 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)
    {}