Inheritance in C++
Inheritance in C++
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
class fourWheeler: public Vehicle
{ public:
fourWheeler()
{
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};
// sub class derived from two base classes
class Car: public fourWheeler{
public:
car()
{
cout<<"Car has 4 Wheels"<<endl;
}
};
// main function
int main()
{
//creating object of sub class will
//invoke the constructor of base classes
Car obj;
return 0;
}
Visibilty modes
public
• Derived class can access the public and
protected members of the base class but not
the private members
• this type does not change the access specifiers
of the inherited members of derived class
Private
• Derived class can access public and protected
members of the base class privately
• public and protected members of the base
class become private member to derived class
• This derived class cannot be inherited further
protected
• Derived class can access public and protected
members of the base class as protected
• This derived class is now not available to
outside world and can be accessed only
through member functions of derived and
classes that inherit this derived class
Access Specifier Accessible from Accessible from Accessible from
own class derived class/ objects outside the
Inheritable class
Public Yes Yes Yes
Protected Yes Yes No
Private yes No No
Significance of Visibility modes