VISIBILITY
MODES
An
important feature of Inheritance is to know which member of the base class will
be acquired by the derived class. This is done by using visibility modes.
The
accessibility of base class by the derived class is controlled by visibility
modes. The three visibility modes are private, protected and public. The
default visibility mode is private. Though visibility modes and access
specifiers look similar, the main difference between them is Access specifiers
control the accessibility of the members with in the class where as visibility
modes control the access of inherited members with in the class.
When
a base class is inherited with private visibility mode the public and protected
members of the base class become ‘private’ members of the derived class
When
a base class is inherited with protected visibility mode the protected and
public members of the base class become ‘protected members ‘ of the derived
class
When
a base class is inherited with public visibility mode , the protected members
of the base class will be inherited as protected members of the derived class
and the public members of the base class will be inherited as public members of
the derived class.
//Implementation of Single Inheritance using public visibility
mode
#include <iostream>
using namespace std;
class Shape
{
private:
int count;
protected:
int width;
int height;
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
};
class Rectangle: publicShape
{
public:
int getArea()
{
return (width * height);
}
};
int main()
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of theobject.
cout<< "Total area: "<<Rect.getArea()
<<endl;
return 0;
}
Total area: 35
Suppose
the class rectangle is derived with
protected visibility then the properties of class rectangle will change as
follows
In
case the class rectangle is derived with private visibility mode from its base
class shape then the property of class rectangle will change as follows
When you derive the class from an existing base class,it may
inherit the properties of the base class based on its visibility mode.So one
must give appropriate visibility mode depends up on the need.
Private
inheritance should be used when you want the features of the base class to be
available to the derived class but not to the classes that are derived from the
derived class.
Protected
inheritance should be used when features of base class to be available only to
the derived class members but not to the outside world.
Public
inheritance can be used when features of base class to be available the derived
class members and also to the outside world.
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.