简体   繁体   中英

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?

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
}

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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM