Inheritance and Overriding in C++ with simple example
Inheritance
C++ commonly uses inheritance functionality to prevent unnecessary copy which could cause duplication and severe errors. It allows to create many similar classes from a base class and performs them differently. Even though parent class has many child classes, only the class, that we want to change, can be modified without affecting other classes. Less code and errors mean less expense in maintenance and upgrade.
Overriding
In C++, overriding can be used if you want to modify only a function of the derived class ignoring the function of the base class.
Memory Allocation & Deallocation processing in Inheritance. Memory Allocation order in Inheritance
First, allocation of memory space Second, running the Base class constructor Third, running the Derived class constructor Memory Deallocation order in Inheritance
First, calling the Derived class destructor Second, calling the Base class destructor Third, Memory is returned(Deallocation)
Example code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | class Animal { private: int weight; public: void setWeight(int weight) { this->weight = weight; } int getWeight() { return this->weight; } void print() { cout << "hello" << endl; } }; class Dog : public Animal { //Dog class inherit the parent class public: void print() { Animal::print(); //Only modified the function printf() redefined cout << "Print dog class" << endl; } }; int main() { Dog dog; dog.print(); Animal animal; Animal animal1; animal.setWeight(20); animal1.setWeight(30); cout << animal.getWeight() << endl; cout << animal1.getWeight() << endl; return 0; } | cs |
Result