#include <iostream>
struct Junk
{
int x;
Junk& operator=(const Junk& rhs)
{
x = rhs.x;
std::cout << "Copying\n";
return *this;
}
};
int main()
{
Junk* a = new Junk;
Junk* b = new Junk;
a->x = 5;
*b = *a; // This will call the assignment op
std::cout << b->x << '\n';
std::cin.ignore();
}
The whole point of the assignment operator is to assign the values of one
object to another.
using it on pointers to objects the way you doing is meaningless (and won't work) - pointers are all about addreses.
In your example above - what you would do is:
1 2 3 4 5 6 7 8 9
void main(){
Junk *a = new Junk, *b;
a->x = 5;
b = new Junk (a); //Create a new object using an existing one - You need a Copy Constructor
cin.ignore();
return;
}
To assign an existing object to an already existing one - You use an assignment operator of the form - Note the use of the reference operator (NOT pointer operator)
1 2 3 4 5 6 7 8 9
struct Junk{
int x;
Junk & operator= (const Junk& inc){
//But remember to guard against self-assignment
this->x = inc->x;
cout << "Copying\n";
return *this;
}
};
So you can now say:
1 2 3
Junk a, b; //Create some objects
.....//manipulate the objects
a = b; //assign one existing object to another
So we can't use overloaded operators on objects referred to by pointers?
You just need to dereference the pointer first using *: *ptr1 = *ptr2. That tells the compiler that it is the contents of the pointer that need assigning rather than the pointer itself.
Chemical Engineer wrote:
I was really fond of the abstraction that pointers afforded. It'd be a great shame if they have that limitation.
I avoid pointers like the plague. Sometimes they are necessary. But I would always go for a non-pointer solution given the choice.
You have to manage the pointers yourself. That increases the possibility of errors. There is often no guarantee that they actually point to anything in a given piece of code.