We already learn about Encapsulation and the two important access specifiers, which are public and private.
Let me recap,
Public: May be accessed from anywhere outside the class.
Private: Accessed within their class and the outsiders can have used the friend function.
But the third access specifier is still left and we need to learn that now.
That one is protected which is similar to private member except one thing-it can be accessed from the derived class.
Example:
// Output: Bolero have 4 Wheels
Types of Inheritance:
Public Inheritance:
Private Inheritance:
Protected Inheritance:
Let me recap,
Public: May be accessed from anywhere outside the class.
Private: Accessed within their class and the outsiders can have used the friend function.
But the third access specifier is still left and we need to learn that now.
That one is protected which is similar to private member except one thing-it can be accessed from the derived class.
Example:
#include <iostream>
using namespace std;
// Base class
class Cars{
public:
void carwheels(int w) //function is declared with one parameter
{
wheels= w; //wheels is accessed from protected access specifier and assigned to w variable
}
protected:
int wheels; //protected member variable
};
// Derived class
class Bolero: public Cars //Bolero is Derived Class and Cars is the Base class
{
public:
int ShowWheels() //Function with integer return type
{
return (wheels); //it return the value provided from the main function
}
};
int main() //main function
{
Bolero whe; //whe object is created
whe.carwheels(4); //4 is the value which is passed to carwheels function's parameter
cout <<"Bolero have "<<whe.ShowWheels()<<" Wheels"<<endl; //ShowWheels() function is called to get the reurn which is provided and diplay that valu
return 0; //return void
}
// Output: Bolero have 4 Wheels
· Hope you understand the program shown above from the comments.
· The most important thing which we need to see is that Bolero is the derived class of Cars and thus as per the rules it accesses the protected variable members.
Types of Inheritance:
Public Inheritance:
· Public members of the base class can be accessible from the derived class without any restrictions.
· Base class’s private members are only accessible through calls to the public and protected member of the base class.
Private Inheritance:
· The public and protected members of the private base class are only accessed by the derived class privately.
Protected Inheritance:
· The public and protected members of the protected base class are only accessed by the derived class as protected members.