-3

In the following code, if the base class is derived as protected then the code doesn't work. Why? When exactly are protected and private access specifiers used when inheriting base class having virtual functions? Also, since a child class have an access to parent class, why can't a pointer of base class point to it's parent class? Go through the following code to make sense of these questions.

#include<iostream>
using namespace std;

class A
{
public:
    virtual void show()
    {
    cout<<"In A"<<endl;
    }
};
class B:public A//--QUESTION-----Making A protected is giving an error. Why?
{
public:
//protected: works..
    void show()
    {
        cout<<"In B"<<endl;
    }
};
class C : public B//Making B protected is giving an error. Why?
{
public:
     void show()
    {
        cout<<"In C"<<endl;
    }
};
int main()
{
    A obj1;
    B obj2;
    C obj3;
    A *obj;
    B *objp;
    C *objp3;
    obj=&obj2;
    obj->show();

    /*The following 4 lines also do not work. Since a child class has access to parent class, why can't a pointer of base class point to its parent class?*/
    //objp3=&obj2;
    //objp3->show();
    objp=&obj1;
    objp->show();
}

Edit: But we can over-ride the access level of variables, then why can't of functions? Also is making void show()as virtual making any impact here?

Sahil Dhawan
  • 91
  • 2
  • 14
  • 1
    What is unclear about the following question and answers? [Difference between private, public, and protected inheritance](http://stackoverflow.com/questions/860339/difference-between-private-public-and-protected-inheritance) – James Adkison Oct 25 '15 at 15:04

1 Answers1

0

If you derive of A through protected you're setting everything class A has public to protected.

class B:protected A
{
public:
//protected: works..
    void show()
    {
        cout<<"In B"<<endl;
    }
};

So, class B now inherited void show(), and even though show() was public in A, because you derived through protected the inherited void show() will be protected now too. In your inheriting class B you're now trying to override the access level of void show() which is illegal. Same goes for C.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122