+ 23

Is it possible to assign a base class object to a derived class object?

22nd Feb 2017, 12:05 PM
8 Answers
+ 18
Kremik congrats on 500 challenge victories amazing
6th May 2017, 8:39 PM
‎‏‎‏‎Joe - avatar
+ 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.
22nd Feb 2017, 3:03 PM
+ 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; }
22nd Feb 2017, 1:20 PM
Ettienne Gilbert
Ettienne Gilbert - avatar
+ 5
If you have to answer yes/no the answer would be No.
22nd Feb 2017, 3:48 PM
Ettienne Gilbert
Ettienne Gilbert - avatar
+ 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
19th May 2017, 6:31 AM
Kamil Machalica
+ 3
accept my challenge
6th Jun 2017, 2:27 PM
Rajyalakshmi Reddy
Rajyalakshmi Reddy - avatar
+ 1
No.we can't use base class object for derived class.
1st Oct 2018, 10:52 AM
khasimbabu shaik
khasimbabu shaik - avatar
+ 1
Yes , but only we assign base class pointer to derived class obj
17th Feb 2019, 10:30 AM
Sachin Ramchandra Rokade
Sachin Ramchandra Rokade - avatar