Please explain me these 2 codes | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Please explain me these 2 codes

https://code.sololearn.com/cyW4JEJesnTV/?ref=app https://code.sololearn.com/ck5hJ76Onac6/?ref=app I have added my questions in comment there .

2nd May 2021, 8:05 AM
[bool left=True;]
[bool left=True;] - avatar
3 Answers
+ 2
Test 1: To have all destructors being called when deleting a pointer to a base object the destructor has to be declared virtual. That's just how C++ works. Without declaring it virtual C++ has no idea which destructor to call when you delete a pointer to an object of a base class. Therefore it is good practice to always declare destructors of classes which are base classes virtual. Test 2: The problem is that you give the argument per value, effectively copying the object. Just change the declaration to void foo(base& a);
2nd May 2021, 8:20 AM
Hape
Hape - avatar
+ 1
12345 you are copying the object, which means in this case that you are constructing a completely new object of class base, which does not know that it was created from an object of a derived class. I extended your code to hopefully make it a bit clearer. https://code.sololearn.com/cTisoEDgw7uD/?ref=app
2nd May 2021, 10:07 AM
Hape
Hape - avatar
0
Hape i slightly understood 1st test code. But sir can you explain me this part base &a=>calls derived class method base a=>calls base class method
2nd May 2021, 8:25 AM
[bool left=True;]
[bool left=True;] - avatar