+ 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;
3 ответов
+ 2
You may find your answer here :
https://stackoverflow.com/questions/45857883/why-cant-a-base-class-object-assigned-to-a-derived-class-object
+ 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.
+ 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.