Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy constructor calling using "new"

I'm quite new to C++.

I have read that the copy constructor is called when passing an object as an arguement to a function or when returning an object from a function and in initiallization of variables with assignment. Can it be called also in this case, suppose D has copy constructor?

D* pd1 = new D;
D* pd2 = new D(*pd1);
like image 905
Day_Dreamer Avatar asked Sep 08 '25 08:09

Day_Dreamer


2 Answers

Yes.

Copy constructors can be called either implicitly or explicitly.

In this case it is explicitly called:

D* pd2 = new D(*pd1); //pd1 points to D object

In this case it is implicitly called:

D pd2 = *pd1; //pd1 points to D object

A copy constructor can not be called implicitly if it uses the explicit specifier.

http://en.cppreference.com/w/cpp/language/explicit

like image 86
Gábor Angyal Avatar answered Sep 10 '25 04:09

Gábor Angyal


You can try it like this:

class copy {
public:
    copy(int a = 1) :i(a) {}
    copy(copy &c) :i(c.i) { std::cout << "I'm copied!"; }
private:
    int i;
};

int main() {
    copy c;
    // here the copy constructor is called
    // the string literal will be printed 
    auto p = new copy(c);
}

It's clear to see that "new copy(c)" calls the copy constructor.

like image 33
Dardai Avatar answered Sep 10 '25 04:09

Dardai