focusHard
focusHard

Reputation: 271

c++ copying constructor for a composition class

I'm learning a c++ tutorial and having a hard time understanding part of the following code(see the commented part):

#include<iostream>
using namespace std;

class A
{
public:
    A(A&src)
    {
        cout<<"copying A..."<<endl;
    }
    A(void){}
    void Do(void)
    {
        cout<<"A is doing something"<<endl;
    }
};

class B
{
public:
    B(B&src)
    {
        cout<<"copying B..."<<endl;
    }
    B(void){}
    void Do(void)
    {
        cout<<"B is doing something"<<endl;
    }
};

class Compo
{
public:
    Compo(Compo &src):f1(f1),f2(f2)//???

    {
        cout<<"Copying Compo..."<<endl;
    }
    Compo(void){}
    A f1;
    B f2;

};

int main(void)
{
    Compo co1;
    Compo co2=co1;
    co2.f1.Do();
    co2.f2.Do();
}

So how does the compiler know which f1/f2 belongs to which Compo? Is there a way to make it more explicit?

thanks for the help

Upvotes: 1

Views: 365

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258618

It doesn't, you're initializing f1 with itself, which can't lead to anything good. You want:

Compo(const Compo &src):f1(src.f1),f2(src.f2)//???
{
    cout<<"Copying Compo..."<<endl;
}

Another good example to turn on warnings. If you already have them on, pay attention to them.

Upvotes: 5

Related Questions