2008 Delhi:
2.a. Differentiate between public and private visibility modes in context of Object Oriented Programming using a suitable example illustrating each.
Ans:
public and private visibility modes in context of OOP: The visibility mode (private or public or protected) in the definition of the derived class specifies whether the features of the base class are privately derived or publicly derived or protected derived. The visibility modes basically control the access specifier to be for inheritable members of base class, in the derived class.
Public visibility mode: The public derivation means that the derived class can access the public and protected members of the base class but not the private members of the base class. With publicly derived class, the public members of the base class become the public members of the derived class, and the protected members of the base class become the protected members of the derived class.
Private visibility mode: The private derivation means, the derived class can access the public and private members of the base class privately. With privately derived class, the public and protected members of the base class become private members of the derived class. That means the inherited members can be accessed only through member functions of the derived class.
Visibility | Inheritable | Inheritable | Private |
Mode | public member becomes ( in derived class) | protected member becomes (in derived class) | member of base class are not directly accessible to derived class. |
private | Private private |
public and private access specifiers in context of OOP: public access specifier is used to define any method or a variable which may be accessed by any member function of the same class and also from outside the class. Private access specifier is used to make any variable or a method which has a limited access within the class only.
The concept of data hiding is implemented through the private access specifier only.
Eg: class student
{
private: int rno;
char name[21];
public: int age;
void input( );
void display( );
}
Here, since rno and name are declared in private, they can be accessed only inside the class. Since age,input( ) and display() are declared in public, they can be accessed from outside class also.