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);
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With