Narek
Narek

Reputation: 39881

Does copy constructor call default constructor to create an object

Does copy constructor call default constructor while creating an object in C++? If I hide the default constructor, I should be still able to created the copy, right?

Upvotes: 5

Views: 6940

Answers (2)

Lior
Lior

Reputation: 292

The answer is No.

The creation of the object memory is done via the new instruction. Copy constructor is then in charge of the actual copying (relevant only when it's not a shallow copy, obviously).

You can, if you want, explicitly call a different constructor prior to the copy constructor execution.

You can easily test this by copy/paste this code and running it ...

#include <stdio.h>

class Ctest
{
public:

    Ctest()
    {
        printf("default constructor");
    }

    Ctest(const Ctest& input)
    {
        printf("Copy Constructor");
    }
};


int main()
{    
    Ctest *a = new Ctest();     //<-- This should call the default constructor

    Ctest *b = new Ctest(*a);  //<-- this will NOT call the default constructor
}

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Deleting the default constructor does not prevent you from copying the object. Of course you need a way to produce the object in the first place, i.e. you need to provide a non-default constructor.

struct Demo {
    Demo() = delete;
    Demo(int _x) : x(_x) { cout << "one-arg constructor" << endl; }
    int x;
};

int main() {
    Demo a(5); // Create the original using one-arg constructor
    Demo b(a); // Make a copy using the default copy constructor
    return 0;
}

Demo 1.

When you write your own copy constructor, you should route the call to an appropriate constructor with parameters, like this:

struct Demo {
    Demo() = delete;
    Demo(int _x) : x(_x) { cout << "one-arg constructor" << endl; }
    Demo(const Demo& other) : Demo(other.x) {cout << "copy constructor" << endl; }
    int x;
};

Demo 2.

Upvotes: 2

Related Questions