Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How virtual is this?

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.

like image 989
Etam Avatar asked Nov 27 '22 06:11

Etam


1 Answers

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"
like image 105
Konrad Rudolph Avatar answered Dec 05 '22 10:12

Konrad Rudolph