+ 23
Is it possible to assign a base class object to a derived class object?
8 Respuestas
+ 18
Kremik congrats on 500 challenge victories amazing
+ 17
So, which answer true or false should be correct for the following question in quiz: It is possible to assign a base class object to a derived class object.
+ 9
Do you mean like this?:
class A{...};
class B : public A{...};
A ao;
B bo = ao;
This is not possible by default in C++ (because A "is not a" B) but you can do the inverse (because B "is a" A), like this:
B bo;
A ao = bo;
In this case B is "sliced" and only the A part of B is copied to A.
But of course you can "cheat" and overload B's assignment operator to achieve this! For example:
class A
{
protected:
int a;
public:
A(int x){a=x;}
int getA() const{return a;}
};
class B : public A
{
int b;
public:
B(int x, int y) : A(x) {b=y;}
void operator=(const A& ar) {a=ar.getA();}
};
int main() {
A ao(4);
B bo(2, 3);
bo = ao; //bo is now 4, 3
return 0;
}
+ 5
If you have to answer yes/no the answer would be No.
+ 4
yes ypu can, but you have to use explicit conversion like:
B bo;
A ao;
bo=(bo)ao;
which is unsafe really often, because ao could have no members which are in B class
+ 3
accept my challenge
+ 1
No.we can't use base class object for derived class.
+ 1
Yes , but only we assign base class pointer to derived class obj