Hi,
I have studied protected variable and planning to use sample below program.I was expecting the error because as per my understanding protected variable only visible into derive class.
Could anyone point me where am I doing mistake
#include<iostream>
using namespace std;
class base
{
public:
int i;
protected:
int j;
private :
int k;
};
class der : protected base
{
};
class der1 : public der
{
};
class der2 : public der1
{
public:
void fun()
{
cout<<i<<" "<<j<<" "<<" ";
}
};
Protected variables are indeed only accessible within an inheritance hierarchy but since you made the method fun public you are allowed to call it, even though it uses a protected variable.
Any method you make public can be called anywhere that has access to the class instance. If you did not want that method to be called in that place you should make the method itself protected.
What is the use of making the variables protected?
You would make variables protected if you want access to them in a class that inherits it but you do not want your client to have access to them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Base
{
protected:
int x;
};
class Derived : public Base
{
public:
Derived( ) { Base::x = 3; } // can access x since it's protected
};
Base b;
b.x = 3; // error! x is protected, not public!