[ACCEPTED]-does assignment operator work with different types of objects?-virtual-functions

Accepted answer
Score: 11

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();
}

0

Score: 2

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

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

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

Score: 1

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

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

More Related questions