0
#include<iostream>
using namespace std;

class base {
public:
    virtual void func()
    {
        cout << "Using base version of func()\n";
    }
};


class derived1 : public base {

    void func()
    {
        cout << "Using derived1's version of func()\n";
    }
};

// Derived2 inherits derived1.
class derived2 : public derived1 {

    void func()
    {
        cout << "Using derived2's version of func()\n";
    }
};


int main()
{
    base *p, ob;
    derived1 d_ob1;
    derived2 d_ob2;

    p = &ob;
    //ob.func();
    p->func(); // use base's func()


    p = &d_ob1;
    p->func(); // use derived1's func()

    p = &d_ob2;
    p->func(); // use derived2's func()

    return 0;
}

The outputs of this code are:

Using base version of func()

Using derived1's version of func()

Using derived2's version of func()

How the pointer is accessing the private methods of the derived classes?

aahmed109
  • 161
  • 1
  • 1
  • 6
  • Not only is this supposed to work this way, this is how the *template method pattern* is usually implemented in C++ . https://en.wikipedia.org/wiki/Template_method_pattern – PaulMcKenzie Jan 18 '16 at 14:54
  • Are you asking why it's allowed to, or how it's done? (It's allowed to because `func` is public in `base`, and `p` is a `base*`.) – molbdnilo Jan 18 '16 at 14:55
  • @TartanLlama, I really don't understand how this question is duplicated – aahmed109 Jan 18 '16 at 15:00
  • @molbdnilo, I have no problem with the base class. The two func methods in two derived classes are private. Are they supposed to be accessed by the pointer? – aahmed109 Jan 18 '16 at 15:03
  • @aahmed109 This is not checked at runtime, only at compile-time. Since `p` is a `base*`, the interface of `base` is the one that applies. (And yes, it's supposed to work that way.) – molbdnilo Jan 18 '16 at 15:10

0 Answers0