0
votes

My codes:

#include <iostream>
using namespace std;
class Base
{
public:
    void print() { doPrint();}
private:
    virtual void doPrint() {cout << "Base::doPrint" << endl;}
};

class Derived : public Base
{
private:
    virtual void doPrint() {cout << "Derived::doPrint" << endl;}
};

int main()
{
    Derived *d = new Derived();
    Base* p = dynamic_cast<Base*>(d);
    p->print();
    delete d;
    return 0;
}

The output is Derived::doPrint, I don't know the answer well. Why not Base::doPrint? In public inheritance, why Base class can call Derived class's private virtual function?

3
Find a good book and read about polymorphism.Some programmer dude
Perhaps answer to this question will help you. stackoverflow.com/questions/4548145/…Arunmu

3 Answers

0
votes

Virtual will tell it to check what function to call. It still knows that it is a Derived. If you haven't put virtual this would not work. Read more about polymorphism.

1
votes

In C++, access checks are done on the static (compile time) type of an expression, but virtual calls use the dynamic (run time) type.

In your example, *p has static type Base and dynamic type Derived.

0
votes

Even after you've written Base* p = dynamic_cast<Base*>(d);, p is still a pointer to an instance of Derived.

So p->print(); will call the function on the Derived class.

That's how polymorphism works in C++.