Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

OOP Part 3: Inheritance and Code Reuse

Lesson 35 of 53 in the free Foundation of C & C++ notes on Siksha Sarovar, written by Rohit Jangra.

Don't Repeat Yourself (DRY)

Inheritance allows you to create a new class (the Child or Derived class) that inherits all the properties and functions of an existing class (the Parent or Base class).

The Logic of Inheritance

Think of a Vehicle class. It has a brand and a start() function. A Car is a type of Vehicle. So instead of rewriting the brand and start() code for Car, Truck, and Motorcycle, we just inherit from Vehicle!

Syntax

class Car : public Vehicle {
    // Car inherits everything from Vehicle
};

Types of Inheritance

  1. Single: One parent, one child.
  2. Multilevel: Grandparent -> Parent -> Child.
  3. Multiple: One child can have TWO parents. (Unique to C++).
  4. Hierarchical: One parent, many children.

The protected Keyword

A child can see its parent's public and protected members, but never the private ones. Private means "Private to THIS class only."

Function Overriding

A child can provide its own "special" version of a parent's function.

class Animal { public: void speak() { cout << "Sound"; } };
class Dog : public Animal { public: void speak() { cout << "Woof!"; } };
Multiple inheritance is powerful but dangerous. It can lead to the "Diamond Problem" where a child doesn't know which version of a function to use. C++ solves this using Virtual Inheritance.