0

I am new to OOPS and was learning about virtual function that it is useful to achieve run-time polymorphism.

But I have some doubt.

#include<bits/stdc++.h>
using namespace std;
class A
{
    public: 
        virtual void print()
        {
            cout<<"Inside base class private"<<endl;    
        }   
        
};
class B: public A
{
    private:
        void print()
        {
            cout<<"Inside derived class private"<<endl;
        }
};
int main()
{
    A *ptr = new B();
    ptr->print();
    //ptr->show();
    return 0;
}

Since in derived class our print function is private and then also it is giving output as Inside derived class private. Why it is so? It is in private section so it should have given compiler error but it is giving correct output?

  • @RetiredNinja That's too bookish language. I just want to learn this with vptr concept. – Hash include Aug 21 '21 at 05:03
  • You have an `A*`, the function is public in `A`, you can call it. – Retired Ninja Aug 21 '21 at 05:05
  • @RetiredNinja But print is in private section inside B? – Hash include Aug 21 '21 at 05:08
  • That does not matter. It is public in `A` and can be called with an instance, reference, or pointer of `A`. Here are some more explanations, if you're going to learn C++ you're going to need to get used to "bookish language". https://stackoverflow.com/questions/34486508/virtual-function-overridden-and-private-public-specifier https://stackoverflow.com/questions/55475852/why-private-method-overwrites-base-class-public-virtual-methodwith-public-inher – Retired Ninja Aug 21 '21 at 05:11
  • @RetiredNinja So basically access specifier of overridden virtual function inside derived class doesn't affect them. It only affect that who can access them outside the class but doesn't affect their overridden functionality to override base class virtual function. And we can access them using base class pointer which points to derived class object. Correct me if I am wrong? – Hash include Aug 21 '21 at 05:28
  • @Hashinclude Think of it this way: the code that tries to invoke `print()` need not know that `B` exists. In a separate source file, make the definition of `A` but not `B` available. Define the function `void fun(A * ptr) { ptr-print(); }`. Next, in your main function, replace `ptr->print();` with `fun(ptr);`. Where should the compiler throw an error, and why? (Keep in mind that when compiling `fun()`, the compiler has no knowledge of `B`.) If no error in this case, why should your version have an error? – JaMiT Aug 21 '21 at 05:48
  • Mandatory remark. See [Why should I not #include ?](https://stackoverflow.com/q/31816095) and [Why using namespace std is bad practice](https://stackoverflow.com/questions/1452721). – prapin Aug 21 '21 at 07:09

0 Answers0