0
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!

2
  • 6
    For the answer to "how many times?", you can put something like cout << "in A1's ctor" << endl; in the constructors and run the code to see for yourself. Commented Mar 14, 2011 at 4:05
  • @Martinho - If you were even lazier, you could do static int i = 0; std::cout << ++i << "th time in A1" << std::endl; Commented Mar 14, 2011 at 4:16

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.