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?