Feb 27, 2008

Protected member of the class in C++

Protected member of the class can be accessed in class itself and its derived class
but cannot be accessed outside of the class. This example shows the same.
This program will raise an error
#include<iostream.h>
#include<conio.h>
class demo1
{
protected :
int a,b,c;
public:
void add()
{
a=10; // protected members a,b and c are accessed within the class
b=20;
c=a+b;
cout << c <<endl;
}
};

class demo2: public demo1
{
public:
void sub()
{
a=30; // protected members of the class can be accessed in its derived class.
b=20;
c=a-b;
cout << c <<endl;
}
};
main()
{
clrscr();
demo2 d;
d.add();
d.sub();
d.a=50; // protected members can not be accessed outside of the class.
d.b=60;
d.c=d.a+d.b;
cout << d.c <<endl;
getch();
}

No comments:

Post a Comment