Tutorial :does assignment operator work with different types of objects?



Question:

class A {  public:  void operator=(const B &in);  private:   int a;  };    class B {  private:   int c;    }  

sorry. there happened an error. is assignment operator valid ? or is there any way to achieve this? [There is no relation between A and B class.]

void A::operator=(const B& in)   {   a = in.c;    }   

Thanks a lot.


Solution:1

Yes you can do so.

#include <iostream>  using namespace std;    class B {    public:      B() : y(1) {}      int getY() const { return y; }    private:       int y;  };      class A {    public:      A() : x(0) {}      void operator=(const B &in) {         x = in.getY();      }      void display() { cout << x << endl; }    private:       int x;  };      int main() {     A a;     B b;     a = b;     a.display();  }  


Solution:2

Both assignment operator and parameterized constructors can have parameters of any type and use these parameters' values any way they want to initialize the object.


Solution:3

This isn't an answer, but one should be aware that the typical idiom for the assignment operator is to have it return a reference to the object type (rather than void) and to return (*this) at the end. This way, you can chain the assignent, as in a = b = c:

A& operator=(const A& other)   {      // manage any deep copy issues here      return *this;  }  


Solution:4

Others have clued in on this, but I'll actually state it. Yes you can use different types, but note that unless you use friend, your class cannot access the private members of the class it's being passed in with the operator.

Meaning A wouldn't be able to access B::c because it's private.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »