0

i trying to undestand how overload operator work , i did a test to overload a ptr = ptr operator but it didn t work really well. i try to do it with referent and it work but why ptr don' work ? it is because we can t overload this operator ?

Thanks in advance to everyone.

#include<iostream> 
using namespace std; 

class Test 
{ 
    int *ptr; 
public: 
    Test (int i = 0)      { ptr = new int(i); } 
    void setValue (int i) { *ptr = i; } 
    void print()          { cout << *ptr << endl; } 
    Test * operator = (Test *t); 
}; 

Test *Test::operator = (Test *t) 
{ 
   // Check for self assignment 
   std::cout << "here\n";
   return this; 
} 

int main() 
{ 
    Test *t1 = new Test(5); 
    Test *t2 = new Test(6);
    t2->print(); 
    t2 = t1; 
    t1->setValue(10); 
    t2->print(); 
    return 0; 
} 
pikooli
  • 11
  • 2

2 Answers2

4

i did a test to overload a ptr = ptr operator

No you didnt. The operator you implemented:

Test * operator = (Test *t); 

is a member function, hence you call it on objects. Even if you use a pointer you always have to first dereference the pointer and then call the method:

Test t1,t2;
Test* t_ptr1 = &t1;
Test* t_ptr2 = &t2;
t_ptr->operator=(t_ptr2);
// ^^ same as vv
t1.operator=(t_ptr2);
// ... or ...
t1 = t_ptr2;

ie the lhs is always an object, not a pointer. In fact you cannot overload methods of pointers. Pointers have no member functions. You take a Test* as parameter and return a Test*, but the operator is still a member function that is called on objects.

To assign pointers you write

t_ptr1 = t_ptr2;

and there is no way to overload operator= for pointers.

PS Actually I didn't refer to you code in details. I am not even sure if it compiles as is. Just one thing that should be mentioned: You leak memory. Either make sure you delete everything you newed, or use smart-pointers, or even better, do not use dynamic memory allocation when you do not need to. See here for more on that: Why should C++ programmers minimize use of 'new'?

463035818_is_not_a_number
  • 64,173
  • 8
  • 58
  • 126
0

You assign two pointers to your object, not the object it self. If you use the object directly it will work.

int main() 
{ 
    Test t1(5); 
    Test t2(6);

    t2 = t1; 

    return 0; 
} 

And indeed it is a duplicate as NathanOliver indicated. There this solution is used:

int main() 
{ 
    Test *t1 = new Test(5); 
    Test *t2 = new Test(6);

    (*t2) = (*t1); 

    return 0; 
} 
Bart
  • 842
  • 3
  • 23