can you explain me why:
int main (int argc, char * const argv[]) {
Parent* p = new Child();
p->Method();
return 0;
}
prints "Child::Method()", and this:
int main (int argc, char * const argv[]) {
Parent p = *(new Child());
p.Method();
return 0;
}
prints "Parent::Method()"?
Classes:
class Parent {
public:
void virtual Method() {
std::cout << "Parent::Method()";
}
};
class Child : public Parent {
public:
void Method() {
std::cout << "Child::Method()";
}
};
Thanks, Etam.
Your second code copies a Child
object into a Parent
variable. By a process called slicing it loses all information specific to Child
(i.e. all private fields partial to Child
) and, as a consequence, all virtual method information associated with it.
Also, both your codes leak memory (but I guess you know this).
You can use references, though. E.g.:
Child c;
Parent& p = c;
p.Method(); // Prints "Child::Method"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With