简体   繁体   中英

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?

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM