简体   繁体   中英

How to initialize a class member data with other member data of this class ?

I have class A and B. B is a member of A. I need to initialize B with other data members of A.

class A;
class B
{
 public:
    B(A& a){cout << "B constr is run \n";}
};

class A
{
 public:
    A(){}

    void initB(A& a){b(a); cout << "A call init B \n"; }
 private:
    // other members ...

    B b;
};

int main()
{
    A a;
    a.initB(a);

}

I got compile error:

classIns.cpp: In constructor âA::A()â:
classIns.cpp:14: error: no matching function for call to âB::B()â
classIns.cpp:8: note: candidates are: B::B(A&)
classIns.cpp:6: note:                 B::B(const B&)
classIns.cpp: In member function âvoid A::initB(A&)â:
classIns.cpp:16: error: no match for call to â(B) (A&)â

Why A(){} needs to call B::B() ?

How to initialize B with other data members of A ?

thanks

B has no default constructor, which means you have to initialise it in A 's ctor.

struct A {
    A() : b(*this) {}
private:
    B b;
};

Any time you think of using init -like members, you're probably doing it wrong. Object should always be valid after the constructor is done.

Like this :

void initB(A& a){
  b = B(a); 
  cout << "A call init B \n"; 
}

Off course, the class B needs a default constructor, and a copy constructor that takes reference to the object of type A.

You can use initialization chain in A constructor:

class B
{
    public:
        B(Type1 x, Type2 y)
        {

        }
        void init(Type1 x, Type2 y) { ........} 
};
class A
{
    public:
        A() : Amember1(), Amember2(), b(Amember1, Amember2) {}
    private:
        Type1 Amember1;
        .....
        B b;
};

But you can't invoke B constructor inside initB method because b is already constructed. You can use a B::init() method with A data, like:

void A::initB(A& a){ b.init(a.Amember1, a.Amember2); cout << "A call init B \n"; }

Why A(){} needs to call B::B() ?

Because A has a data member B which needs to be initialized when you create an instance of the A class. In your case b is initialized with the default B c'tor.

Since you are specifying a constructor for B

public:
    B(A& a){cout << "B constr is run \n";}

The default constructor :

    B(){}

is not automatically generated by the compiler. So it complains.

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