milesma
milesma

Reputation: 1591

copy constructor VS constructor with a class pointer as parameter

Q1: Does the "self class typed pointer constructor" have a decent/official name?

Q2: Why is copy constructor much more famous than "self class typed pointer constructor"?

Or what are the cases that we must use copy constructor rather then "self class typed pointer constructor"?

class MyClass 
{
public:  
    int i;
    MyClass()
    {
        i = 20;
    }

    //Copy constructor
    MyClass(MyClass const & arg) 
    {
        i = arg.i;
    }

    //What kind of Constructor is this one? 
    MyClass(MyClass* pArg)
    {
        i = pArg->i;
    }
};

int main() {
    MyClass obj;
    MyClass* p = new MyClass();

    //call copy constructor
    MyClass newObj(obj);                //call copy constructor directly
    MyClass newObj2(*p);                //dereference pointer and then call copy constructor
    MyClass* pNew = new MyClass(*p);    //dereference pointer and then call copy constructor

    //Call THE constructor
    MyClass theObj(&obj);               //get the address, call THE constructor
    MyClass theObj2(p);                 //call pointer constructor directly
    MyClass* ptheNew = new MyClass(p);  //call pointer constructor directly
}

Upvotes: 1

Views: 1786

Answers (2)

Kill Console
Kill Console

Reputation: 2023

To an object in C++, we usually use reference rather than pointer. We can use reference to get the address of the object, and than you can use '.' to access its method or data, it is more simple and direct than '->'. I think there is no need to use 'THE constructor'.

Upvotes: 0

Benjamin Lindley
Benjamin Lindley

Reputation: 103741

It has no special name, because there is nothing special about it.

The copy constructor is "more famous", because it is special. It is special because it is a fundamental part of the way the language works. If you don't declare a copy constructor, in most classes, one will be implicitly defined for you. It is involved in many basic operations, such as these:

void foo(MyClass obj) // the copy ctor is (potentially) called to create this parameter
{
    ...
}

MyClass bar() // the copy ctor is (potentially) called when this function returns, and when it result is used
{
    ...
}

MyClass a;
MyClass b(a); // This calls the copy constructor
MyClass c = b; // So does this

Note that, in many cases, the copy is optimized away. See Copy Elision. Also, in C++11, the move constructor is called in many places where the copy constructor used to be called. But the move constructor too can be optimized away in the same places that copy elision could happen.

I can't think of many reasons you would ever use "THE constructor", as you call it.

On a side note, a copy constructor should almost always have this signature:

MyClass(MyClass const &)

Not this one:

MyClass(MyClass &)

Upvotes: 4

Related Questions