Feb 27, 2008

Private data members of the class in C++

private member of the class can be accessed in class itself but can not be accessed in its derived class and outside of the class. This example shows the same.
This program will raise an error

#include<iostream.h>
#include<conio.h>
class demo1
{
private :
int a,b,c;
public:
void add()
{
a=10; // private 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; // private members of the class can not 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; // private 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

Infolinks In Text Ads

Total Pageviews

Powered by Blogger.

Dont Forget To Follow Us

Blog Archive