Making an object equal to another object

I know that you can make two objects equal to each other when one of them is declared. I've tested this in my program. but when i went to use the assignment expression it got scared. Can you make two objects equal to each other using the assignment operator, or can you only do this when you declare one object?

+2


source to share


5 answers


You provide operator = to the class to copy the content of another object. For example:



class A
{
  public:

   //Default constructor
   A();

   //Copy constructor
   A(const A&);

   //Assignment operator
    A& operator=(const A& a);
};

int main()
{
  A a; //Invokes default constructor
  A b(a); //Invokes copy constructor;
  A c;
  c = a; //Invokes assignment operator
}

      

+7


source


Overloading the assignment operator for this object can help you. (I hope you are talking about objects of the same class :))



+2


source


For the assignment operator, just an overload operator according to your class implementation.

0


source


An object may be required to be initialized or created or equated to another object when the object depends on other objects.

In this case, the copy constructor gives a better solution .. because it does not copy an object to another object bit by bit. A bitwise copy creates a problem if memory is dynamically allocated to an object. so the solutions are defining the copy_constructor instance in the class. The copy constant refers to an existing object of the same type as its argument and is used to create a new object from an existing one. Here is an example to equate objects to other objects using the copy constructor.

#include "stdafx.h"
#include "iostream"
using namespace std;
class array
{
int *ptr;
int size;
public:
array (int sz) {
ptr = new int [sz];
size =sz;
for(int index=0;index<size;index++)
ptr[index]=size;
}
~array(){
delete[] ptr;
}
array(array &a) {
int index;
ptr=new int[a.size];
for(index=0;index<a.size;index++)
ptr[index]=a.ptr[index];
cout<<"copy_constructor invoked"<<endl;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
array num(10);
array x(num); //invokes copy_constructor
array y=num; //invokes copy consturctor

return 0;
}

      

0


source


This answer is specific to C #.

Along with the Overloading = operator, you must also override the method. You should also check the Best Practices for overloading equals () and operator ==

public struct Complex 
{
   double re, im;
   public override bool Equals(Object obj) 
   {
      return obj is Complex && this == (Complex)obj;
   }
   public override int GetHashCode() 
   {
      return re.GetHashCode() ^ im.GetHashCode();
   }
   public static bool operator ==(Complex x, Complex y) 
   {
      return x.re == y.re && x.im == y.im;
   }
   public static bool operator !=(Complex x, Complex y) 
   {
      return !(x == y);
   }
}

      

-1


source







All Articles