简体   繁体   中英

C++ a default constructor of a class calling another default constructor of another class

I have 2 classes Class A and B. I am trying to use Class B's default constructor to call class A's default constructor to intialize the values of class A in class B.

class A
{
    A();    
    int x;
}

A::A()
{
    //initialized x
    x=10;
}

class B
{
    B();
    A aobj;
}

B::B()
{
    //Calling class A's  default constructor to initialize B's aobj.
    aobj();
}

I received a no match call to '(aobj)'. Please help me to resolve.

Actually, you don't need to explicitly default construct members as that happens automatically unless you explicitly construct the member otherwise. In case you want to really construct a member explicitly, whether it is default construction or something else, you'll need to put your initialization into the member initializer list:

B::B()
    : aobj() {
}

The expression aobj() in the body of a function tries to use the function call operator on the member aobj . Doing so may be reasonable, eg, when aobj is of type std::function<void()> .

In the context of a statement, aobj() does not try to construct the aobj variable, rather it attempts to call it using the operator() operator overload.

Instead, try doing the construction in B::B() 's initializer list:

B::B() : aobj()
{
}

But note that this is redundant, since the default constructor for member objects will be called implicitly if omitted from the initializer list. That is, this constructor would do the exact same thing:

B::B() { }

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