Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the private copy constructor doesn't work?

In MAIN:

Text *p1 = new Text("alfa");
Text *p2 = new Text("delta");
p1 = p2;

In Text.h

private:
Text (const Text& t);
Text&  operator=(const Text& t);

However, I think that the compiler should give an error like "The operator = is unaccessible", instead the code work like the copy constructor and the operator = are no private. Indeed, at the end p1=p2="delta". why? Some advice? Thanks to all.

like image 482
MM92x Avatar asked Feb 23 '26 04:02

MM92x


2 Answers

p1 and p2 are pointers. You may assign one pointer to another pointer of the same type. In your code snippet, neither your copy constructor nor your copy assignment operator are being used.

Text *p1 = new Text("alfa");
Text *p2 = new Text("delta");
p1 = p2;

The copy constructor would be used if you wrote this, for example:

Text *p3 = new Text( *p1 );

And the copy assignment operator would be used if you wrote this:

*p1 = *p2;

In that case, you would be assigning one object of type Text to another object of type Text.

like image 142
Vlad from Moscow Avatar answered Feb 25 '26 18:02

Vlad from Moscow


Your example code is assigning a pointer to another pointer. This will not invoke the assignment operator since you are doing a simple pointer assignment. If you want to attempt to invoke the assignment operator you should try:

*p1 = *p2;

Otherwise, your current code is almost equivalent to assigning one integer to another.

like image 35
Kevin Avatar answered Feb 25 '26 19:02

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!