views:

228

answers:

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

+4  A: 

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();
}
Shree
You can also make getY() as a const member function and avoid the const_cast.
Naveen
Yes, make getY const, and don't cast constness away.
Dave Van den Eynde
True... was just lazy to go back and change it :)
Shree
Or else make A a friend of B so that it can access private elements.
David Rodríguez - dribeas
+1  A: 

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.

sharptooth