Reputation: 568
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.
Upvotes: 2
Views: 174
Reputation: 310980
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
.
Upvotes: 7
Reputation: 1526
You aren't copying or assigning an object. You copy a pointer. This means you copy the address of your object from one variable into another.
Upvotes: 2
Reputation: 81
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.
Upvotes: 2