What is inheritance?
- Inheritance is a mechanism of reusing existing classes thereby allowing rapid development.
- A new class is created as a type of an existing class using the syntax "class <new-class> : public <existing-class1>, public <existing-class2>..." where "public" is an access specifier.
- The reused class is refered as base class and the new class is refered as derived class.
- A classes immediate base class is called "direct base class" and thier base classes are called "indirect base class".
- The order of object creation starts from the root to the most derived class.
- The order of object destruction is in reverse of object creation. Starts from the most derived class towards the root.
- 3 types of access specifiers are possible during inheritance.
-
public: The public and protected members of the base class remain public and protected members of the derived class.
-
protected: The public and protected members of the base class become protected members of the derived class.
-
private: The public and protected members of the base class become private members of the derived class.
EXAMPLE: Demonstrate the basic functionality of inheritance
#include <iostream> using namespace std; // Base class class Base { private: int data1; protected: int data2; public: Base(int d1, int d2) { data1 = d1; data2 = d2; cout << "Base constructor ..." << endl; } ~Base() { cout << "Base destructor ..." << endl; } }; // Derived class1 class Derived1 : public Base { public: // Constructor Initialization Derived1(int d1, int d2) : Base(d1, d2) { cout << "Derived1 constructor ..." << endl; } void Print() { // cout << "data1=" << data1 << endl; ERROR: SINCE PRIVATE MEMBER cout << "data2=" << data2 << endl; } ~Derived1() { cout << "Derived1 destructor ..." << endl; } }; // Derived class2 class Derived2 : private Base { public: // Constructor Initialization Derived2(int d1, int d2) : Base(d1, d2) { cout << "Derived2 constructor ..." << endl; } void Print() { // cout << "data1=" << data1 << endl; ERROR: SINCE PRIVATE MEMBER cout << "data2=" << data2 << endl; } ~Derived2() { cout << "Derived2 destructor ..." << endl; } }; int main () { Derived1* d1 = new Derived1(10, 20); d1->Print(); delete d1; Derived1* d2 = new Derived1(10, 30); d2->Print(); delete d2; }OUTPUT:
Base constructor ... Derived1 constructor ... data2=20 Derived1 destructor ... Base destructor ... Base constructor ... Derived1 constructor ... data2=30 Derived1 destructor ... Base destructor ...
0 comments:
Post a Comment