Thursday 24 November 2016

Virtual function inside private access specifier.

There will not be any error, see the below mentioned program and output.


#include<iostream>
using namespace std;

class Base
{
    public:
        virtual void displayClassName()
        {
            cout<<"base class"<<endl;
        }
};

class Derived : public Base
{
    private: // notice displayClassName function is private in derived class.
        virtual void displayClassName()
        {
            cout<<"Derived class"<<endl;
        }
};
int main(int argc, char **argv)
{
    Base *ptr;
    Derived obj;
    ptr = &obj;
    ptr->displayClassName();
    return 0;
}

/*
------------------------------------------------------output
$ ./a.exe
Derived class
*/

Thanks for reading it, for more questions please click on this link.

No comments:

Post a Comment