C++ 33: Inheritance
Inheritance Introduction:
- Single Inheritance.
- Multiple Inheritance.
- Hierarchical Inheritance.
- Multilevel Inheritance.
- Hybrid Inheritance (also known as Virtual Inheritance)
is-a relationship
Inheritance is an is-a relationship. We use inheritance only if an is-a relationship is present between the two classes.
Here are some examples:
- A car is a vehicle.
- Orange is a fruit.
- A surgeon is a doctor.
- A dog is an animal.
C++ protected Members
The access modifier protected is especially relevant when it comes to C++ inheritance.
Like private members, protected members are inaccessible outside of the class. However, they can be accessed by derived classes and friend classes/functions.
We need protected members if we want to hide the data of a class, but still want that data to be inherited by its derived classes.
To learn more about protected, refer to our C++ Access Modifiers tutorial.
Access Modes in C++ Inheritance
In our previous tutorials, we have learned about C++ access specifiers such as public, private, and protected.
So far, we have used the public keyword in order to inherit a class from a previously-existing base class. However, we can also use the private and protected keywords to inherit classes. For example,
class Animal {
// code
};
class Dog : private Animal {
// code
};class Cat : protected Animal {
// code
};The various ways we can derive classes are known as access modes. These access modes have the following effect:
- public: If a derived class is declared in
publicmode, then the members of the base class are inherited by the derived class just as they are. - private: In this case, all the members of the base class become
privatemembers in the derived class. - protected: The
publicmembers of the base class becomeprotectedmembers in the derived class.
The private members of the base class are always private in the derived class.
Examples on inheritance:
#include <iostream>using namespace std;class Distance{protected:int Feet, Inches;public:void setdata(int f, int i){Feet = f;Inches = i;}void display(){cout << "Distance is " << Feet << " and " << Inches << " inches" << endl;}};class MyDistance : public Distance{public:void convert(){Inches += Feet * 12;cout << "Distance inches is " << Inches << endl;}};int main(){MyDistance a;a.setdata(2, 7);a.display();a.convert();return 0;}
Distance is 2 and 7 inches
Distance inches is 31#include <iostream>using namespace std;class Cylinder{protected:int radius, height;public:void setdata(int r, int h){radius = r;height = h;}void volume(){cout << "Volume is " << 3.14 * radius * radius * height << endl;}};class MyCylinder : public Cylinder{public:void surfacearea(){cout << "Surface area is " << 2 * (3.14 * radius * radius) + (2 * 3.14 * radius) * height << endl;}};int main(){MyCylinder a;a.setdata(2, 10);a.volume();a.surfacearea();return 0;}
Enter your age: 56
You can vote
Comments
Post a Comment