views:

132

answers:

4
class member
{
public:
    member()
    {
       cout<<"Calling member constr"<<'\n';
    }
    member(const member&)
    {
        cout<<"Calling member copy constr"<<'\n';
    }
};

class fred
{
public:
    fred()
    {
        cout<<"calling fred constr"<<'\n';
    }
    fred(const fred &)
    {
        cout<<"Calling fred copy constr"<<'\n';
    }
protected:
    member member_;
};

int main()
{
    fred a;
    fred b=a;
}

Output:
Calling member constr
calling fred constr
**Calling member constr**
Calling fred copy constr
+16  A: 

Because you did not call member's copy constructor. You need to copy the members explicitly if you override the default copy constructor of fred.

fred(const fred& other) : member_(other.member_) {
    cout<<"Calling fred copy constr"<<'\n';
}
KennyTM
+6  A: 

It isn't called because you explicitly asked the compiler not to call it. When you defined your own copy constructor for class fred, you essentially told the compiler that you wanted to take matters into your hands and do the copying yourself. Since you do nothing to copy the member_ in the fred's copy constructor, it isn't copied.

If you get rid of the explicit definition of fred's copy constructor, the compiler will provide an implicit one for you, which will call the member's copy constructor to copy member_.

If you insist on defining fred's copy constructor yourself, you have to copy member_ yourself, as KennyTM suggested.

AndreyT
A: 

If class A has a class B member and you explicitly implement the copy ctor for class A, then you must explicitly copy the members there, in this case call the B copy ctor, otherwise the B member will be default constructed, not copy constructed.

Johann Gerell
A: 

You have to explicitly call it in this case. Because, you have overloaded constructors.

Btw, When I see "Fred", it reminds me this useful resource, please have look for further understanding of C++ constructors: http://www.parashift.com/c++-faq-lite/ctors.html

baris_a