0

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?

cwfighter
  • 502
  • 1
  • 5
  • 20
  • 2
    [Find a good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and read about *polymorphism*. – Some programmer dude Jun 08 '16 at 15:05
  • Perhaps answer to this question will help you. http://stackoverflow.com/questions/4548145/low-level-details-of-inheritance-and-polymorphism – Arunmu Jun 08 '16 at 15:06

3 Answers3

1

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.

MSalters
  • 173,980
  • 10
  • 155
  • 350
0

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++.

0

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.

kemis
  • 4,404
  • 6
  • 27
  • 40