← Back to C++ Course | Chapter 9: Inheritance | Lesson 1 of 8

C++ Inheritance Introduction

What is Inheritance?

Inheritance lets a new class, called the derived class, automatically acquire the properties and methods of an existing class, called the base class. This promotes code reuse by letting related classes share common behavior instead of each reimplementing it independently.

Example: What is Inheritance?

cpp
#include <iostream>

class Animal {
public:
	void eat() { std::cout << "Eating" << std::endl; }
};

class Dog : public Animal {
public:
	void bark() { std::cout << "Barking" << std::endl; }
};

int main() {
	Dog d;
	d.eat();
	d.bark();
	return 0;
}

Base and Derived Class Constructors

When you create an object of a derived class, the base class's constructor always runs first to set up the inherited portion of the object, and only after that finishes does the derived class's own constructor run to initialize the parts it added.

Example: Base and Derived Class Constructors

cpp
#include <iostream>

class Animal {
public:
	Animal() { std::cout << "Animal constructed" << std::endl; }
};

class Dog : public Animal {
public:
	Dog() { std::cout << "Dog constructed" << std::endl; }
};

int main() {
	Dog d;
	return 0;
}

Public Inheritance Access

With public inheritance, any member that was public in the base class remains public in the derived class, meaning external code can access it through a derived object exactly as freely as it could through a base object.

Example: Public Inheritance Access

cpp
#include <iostream>

class Animal {
public:
	int legs = 4;
};

class Dog : public Animal {};

int main() {
	Dog d;
	std::cout << d.legs << std::endl;
	return 0;
}

Protected Access Specifier

Protected members can never be accessed from outside the class hierarchy entirely, but unlike private members, they remain freely accessible inside any class that derives from the one that declared them — useful for internal state a subclass legitimately needs to build on.

Example: Protected Access Specifier

cpp
#include <iostream>

class Animal {
protected:
	int age = 2;
};

class Dog : public Animal {
public:
	void showAge() { std::cout << age << std::endl; }
};

int main() {
	Dog d;
	d.showAge();
	return 0;
}

Overriding Base Class Methods

Method overriding lets a derived class supply its own specific implementation of a function that the base class already defines, replacing the inherited behavior with logic tailored to that particular subclass.

Example: Overriding Base Class Methods

cpp
#include <iostream>

class Animal {
public:
	void speak() { std::cout << "..." << std::endl; }
};

class Dog : public Animal {
public:
	void speak() { std::cout << "Woof" << std::endl; }
};

int main() {
	Dog d;
	d.speak();
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.