Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

C++ Inheritance

What is Inheritance?

Inheritance allows a derived class (child) to acquire the properties and methods of a base class (parent). It promotes code reuse and establishes an "is-a" relationship.

Syntax: class Derived : accessSpecifier Base { ... };

Inheritance Typepublic members becomeprotected members become
publicpublic in derivedprotected in derived
protectedprotected in derivedprotected in derived
privateprivate in derivedprivate in derived
Single Inheritance
#include <iostream>
#include <string>
using namespace std;

// Base class
class Animal {
protected:
    string name;
    int age;

public:
    Animal(string name, int age) : name(name), age(age) {}

    void eat()   { cout << name << " is eating" << endl; }
    void sleep() { cout << name << " is sleeping" << endl; }

    void info() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

// Derived class — inherits from Animal
class Dog : public Animal {
private:
    string breed;

public:
    // Call base constructor via initializer list
    Dog(string name, int age, string breed)
        : Animal(name, age), breed(breed) {}

    void bark() { cout << name << " says: Woof!" << endl; }

    void info() {  // override base info()
        Animal::info();  // call base version
        cout << "Breed: " << breed << endl;
    }
};

int main() {
    Dog d("Rex", 3, "German Shepherd");
    d.eat();    // inherited from Animal
    d.sleep();  // inherited from Animal
    d.bark();   // Dog's own method
    d.info();   // Dog's overridden info()

    return 0;
}

Multilevel and Multiple Inheritance

Multilevel and Multiple Inheritance
#include <iostream>
using namespace std;

class Vehicle {
public:
    void start() { cout << "Vehicle started" << endl; }
};

class Car : public Vehicle {
public:
    void drive() { cout << "Car driving" << endl; }
};

// Multilevel: ElectricCar → Car → Vehicle
class ElectricCar : public Car {
public:
    void charge() { cout << "Charging battery" << endl; }
};

int main() {
    ElectricCar ec;
    ec.start();   // from Vehicle
    ec.drive();   // from Car
    ec.charge();  // own method
    return 0;
}
#include <iostream>
using namespace std;

class Flyable {
public:
    void fly() { cout << "Flying" << endl; }
};

class Swimmable {
public:
    void swim() { cout << "Swimming" << endl; }
};

// Multiple inheritance: Duck inherits from both
class Duck : public Flyable, public Swimmable {
public:
    void quack() { cout << "Quack!" << endl; }
};

int main() {
    Duck d;
    d.fly();    // from Flyable
    d.swim();   // from Swimmable
    d.quack();  // own method
    return 0;
}

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.