Pages

Thursday, 15 September 2022

Thought on C++ copy constructor

 //
// When a variable contains an object directly,
// copying, assignment and returning becomes complex.
// In C++, "copy constructor" and "assignment operator" are
// necessary for those operations.
//
// In practice, coping objects is rarely needed. So, other OO
// languges usually don't operate on objects directly, but on
// their references(pointers) instead.
//
// For example, in Java/Python, a variable contains a reference(pointer) to
// the actual object. As a result, copying, assignment, and
// returning such a variable are just simple as if it was an
// integer.
//
// In C++, we can use class pointers to mimic references in Java,
// but code full of "*" looks ugly.
//
//

#include <iostream>
using namespace std;
class A
{
        public:
                // constructor
                A()
                {
                        cout << "A::A() being called\n";
                }
                // copy constructor
                A(const A& old_obj)
                {
                        cout << "A::A(const A&) being called.\n";
                }
};
// A's copy constructor will be called
void f1(const A obj)
{
        return;
}
// A's copy constructor will not be called
void f2(const A& obj)
{
        return;
}
A f3(const A& obj)
{
        // A's copy constructor will be called
        return obj;
}
// copy constructor will NOT be called
A& f4(A& obj)
{
        return obj;
}

int main(int argc, char** argv)
{
        A o1;
        A o2 = o1; // call copy constructor
        A o3;
        o3 = o1;  // assignment operator
        cout << "f1\n";
        f1(o1);
        cout << "f2\n";
        f2(o1);
        cout << "f3\n";
        f3(o1);
        cout << "f4\n";
        f4(o1);
}

RESULT:

$ ./a.out
A::A() being called
A::A(const A&) being called.
A::A() being called
f1
A::A(const A&) being called.
f2
f3
A::A(const A&) being called.
f4

No comments:

Post a Comment