0
#include<iostream> 
using namespace std; 

class Derived; 

class Base { 
private: 
    virtual void fun() { cout << "Base Fun"; }
}; 

class Derived: public Base { 
public: 
    void fun() { cout << "Derived Fun"; } 
}; 

int main() 
{ 
Base *ptr = new Derived; 
ptr->fun(); 
return 0; 
} 

The above function gives the error: virtual void Base::fun()’ is private within this context

But why does it need to check in the base class, while in the declaration we are making it clear that it's pointing to derived class?

llinvokerl
  • 1,029
  • 10
  • 25
Sudo Pehpeh
  • 71
  • 1
  • 8
  • 1
    does this answers your question https://stackoverflow.com/questions/41136606/if-a-private-virtual-function-is-overridden-as-a-public-function-in-the-derived? – Gaurav Dhiman Jan 10 '20 at 10:49
  • Because `ptr` is a pointer to the *base* class. – Some programmer dude Jan 10 '20 at 10:50
  • 1
    What do you think the text `private:` within the class `Base` does???? Your code is using a pointer to `Base`, not a `Derived`. So at the call point `ptr->fun()` knows that `fun()` is a private member of `Base` - and does not look at the *actual* type of the object that `ptr` points at. – Peter Jan 10 '20 at 10:51
  • Now think about what the meaning of your code is supposed to be, aside from how it technically works. A method in a base class says that all children have this kind of method. If it is a private one, it is meant to be used internally. So what would the meaning of making it public be? I don't see one. Also, how would a child know something that is private in the base? Note that it is private, not protected. Third thing, you should really use the `override` keyword. – Aziuth Jan 10 '20 at 11:00
  • `while in the declaration we are making it clear that it's pointing to derived class?` no the declaration is `Base *ptr = …` so you create a pointer to `Base`. The compiler checks if it is valid to assign the pointer returned by `new Derived` to `ptr`, but that does not change the fact that it is still a pointer to `Base`. So all compiler checks for `ptr->…` are done assuming it is a pointer to Base, resolving the correct virtual function is done at runtime. – t.niese Jan 10 '20 at 11:00

0 Answers0