does assignment operator work with different types of objects?
Asked Answered
E

4

9
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.

Eden answered 8/4, 2009 at 8:10 Comment(1)
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.Eden
S
13

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();
}
Savina answered 8/4, 2009 at 8:17 Comment(5)
You can also make getY() as a const member function and avoid the const_cast.Armpit
Yes, make getY const, and don't cast constness away.Giaimo
True... was just lazy to go back and change it :)Savina
Or else make A a friend of B so that it can access private elements.Patricio
Can this work with builtin types to support, for example, A a=45;Fully
C
2

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;
}
Cabral answered 21/11, 2012 at 15:25 Comment(0)
T
1

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.

Transverse answered 8/4, 2009 at 8:18 Comment(0)
A
1

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.

Alded answered 12/5, 2011 at 21:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.