+ 5

Operator= in class objects. (C++)

What happens when we assign an object of the inherited class to a base class object? class A{}; class B: public A{}; A a; B b; a=b;

22nd Dec 2017, 5:08 AM
Alexander Sadomov
Alexander Sadomov - avatar
3 Answers
23rd Dec 2017, 10:54 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 4
When you use the default assignment operator provided to assign a base class object with a derived class object, all the data present in the inherited members of the derived class is copied to the base class. Eg - : #include<iostream> using namespace std; class A { public: int a; A(int v):a(v){} }; class B : public A { public: int b; B(int v):b(v),A(v){} }; int main() { A o1(2); B o2(4); o1 = o2; cout<<o1.a<<endl; } Note that o1 = o2 is possible, but o2 = o1 is not. You need to define a new assignment operator in the derived class to use the object of the base class and copy just the useful data.
22nd Dec 2017, 6:30 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 4
I know that it will work like this, but I can not understand why to equate an object in which only the variable a to the object in which both a and b is possible, and vice versa is impossible.
22nd Dec 2017, 4:56 PM
Alexander Sadomov
Alexander Sadomov - avatar