Don Lun
Don Lun

Reputation: 2777

copy constructor in c++

class A1{
public:
    A1(){}
    A1(const A1& rhs){}
    void foo() {std::cout<<"Hello";}
};

class A2: public A1{
public:
    A2(){}
    A2(const A2& rhs){}
    void foo1(A1&rhs){rhs.foo();}
    void foo2(A1 a1){a1.foo();}
};

int main()
{
    A2 a2;
    A1 a1(a2);

    a2.foo1(a1);
    a2.foo2(a1);
}

How many times are the A1's copy constructor invoked? How many times are the A2's copy constructor invoked?

Could anybody can teach me this? thanks!

Upvotes: 0

Views: 236

Answers (2)

fbrereto
fbrereto

Reputation: 35925

Modifying your code slightly for more explicit output, I have:

#include <iostream>

class A1{
public:
    A1(){}
    A1(const A1& rhs)
        { std::cout << "A1::copy_ctor\n"; }
    void foo()
        { std::cout << "A1::foo\n"; }
};

class A2: public A1{
public:
    A2(){}
    A2(const A2& rhs){}
    void foo1(A1&rhs)
        {
        std::cout << "A2::foo1\n";
        rhs.foo();
        }
    void foo2(A1 a1)
        {
        std::cout << "A2::foo2\n";
        a1.foo();
        }
};

int main()
{
    A2 a2;
    A1 a1(a2);

    a2.foo1(a1);
    a2.foo2(a1);
}

Which using Xcode 3.2.5 yields:

A1::copy_ctor
A2::foo1
A1::foo
A1::copy_ctor
A2::foo2
A1::foo

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283624

It's much easier to talk about code that doesn't reuse variable names everywhere.

The copy constructor for A1 is called twice, and for A2 not at all.

class A1{
public:
    A1(){}
    A1(const A1& rhs){}
    void foo() {std::cout<<"Hello";}
};

class A2: public A1{
public:
    A2(){}
    A2(const A2& rhs){}
    void foo1(A1& a1byref){a1byref.foo();}
    void foo2(A1 a1byval){a1byval.foo();}
};

int main()
{
    A2 a2;
    A1 a1(a2); // calls A1 copy constructor

    a2.foo1(a1);
    a2.foo2(a1); // calls A1 copy constructor
}

Upvotes: 2

Related Questions