Protected variable

Apr 7, 2012 at 2:52am
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<<" "<<" ";
}
};


int main()
{
der2 d;
d.fun();
return 0;
}

Last edited on Apr 7, 2012 at 2:53am
Apr 7, 2012 at 6:17am
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.

Apr 7, 2012 at 8:38am
What is the use of making the variables protected?




Apr 7, 2012 at 1:22pm
Protected variables are accessible from inherited classes.

http://www.cplusplus.com/doc/tutorial/inheritance/
Apr 8, 2012 at 3:37am
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!

Last edited on Apr 8, 2012 at 3:39am
Topic archived. No new replies allowed.