Inheritance in C++ - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Inheritance is one of the cornerstones of OOP because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits common to a set of related items. This class may then be inherited by other, more specific classes, each adding only those things that are unique to the inheriting class.


When a class inherits another, the members of the base class become members of the derived class.


The access status of the base-class members inside the derived class is determined by access. The base-class access specifier must be either public, private, or protected. If no access specifier is present, the access specifier is private by default if the derived class is a class. If the derived class is a struct, then public is the default in the absence of an explicit access specifier. Let's examine the ramifications of using public or private access.


When the access specifier for a base class is public, all public members of the base become public members of the derived class, and all protected members of the base become protected members of the derived class. In all cases, the base's private elements remain private to the base and are not accessible by members of the derived class.


When the base class is inherited by using the private access specifier, all public and protected members of the base class become private members of the derived class.


It is possible to inherit a base class as protected. When this is done, all public and protected members of the base class become protected members of the derived class.


#include <iostream> using namespace std; class base { int i, j; public: void set(int a, int b) { i=a; j=b; } void show() { cout << i << " " << j << "\n"; } }; class derived : public base { int k; public: derived(int x) { k=x; } void showk() { cout << k << "\n"; } }; int main() { derived ob(3); ob.set(1, 2); ob.show(); ob.showk(); return 0; }


#include <iostream> using namespace std; class base { protected: int i, j; public: void set(int a, int b) { i=a; j=b; } void show() { cout << i << " " << j << "\n"; } }; class derived : public base { int k; public: void setk() { k=i*j; } void showk() { cout << k << "\n"; } }; int main() { derived ob; ob.set(2, 3); ob.show(); ob.setk(); ob.showk(); return 0; }


Happy Exploring!

No comments:

Post a Comment