Example for access specifier of the base
class is private:
#include<iostream.h>
#include<conio.h>
class
Base
{
private:
int a;
public:
void setA(int x)
{
a=x;
}
void showA()
{
cout<<”\nA=”<<a;
}
};
class
Derived: private Base
{
private:
int b;
public:
void setB(int y)
{
b=y;
}
void showB()
{
cout<<”\nB=”<<b;
}
};
void
main()
{
Derived obj;
clrscr();
cout<<”\n Derived class members”;
obj.setA(10);
// Error. Since setA() will become private member function of B.
obj.showA();// Error. Since showA() will become
private member function of B.
obj.setB(20);
obj.showB();
}
Output:
Derived
class members
B=20
Example 10:
Example for access specifier is of the
base class is protected:
#include<iostream.h>
#include<conio.h>
class
Base
{
protected:
int a;
public:
void setA(int x)
{
a=x;
}
void showA()
{
cout<<”\nA=”<<a;
}
};
class
Derived: protected Base
{
int b;
public:
void setB(int y)
{
setA(10);
b=y+a;
}
void showAB()
{
cout<<”\nA=”<<a<<”\nB=”<<b;
}
};
void
main()
{
Derived obj;
clrscr();
cout<<”\nDerived class members ”;
obj.setA(10);
//Error because of set A is protected member of derivede class
obj.showA()
//Error because of set A is protected member of derivede class
obj.setB(20);
obj.showB();
}
Output:
Derived
class members
A=10
B=30
No comments:
Post a Comment