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

C++ Single Inheritance

Basic Single Inheritance

Single inheritance is the simplest inheritance relationship in C++: exactly one derived class inherits from exactly one base class, forming a straightforward parent-child pair rather than a more complex hierarchy.

Example: Basic Single Inheritance

cpp
#include <iostream>

class Vehicle {
public:
	void drive() { std::cout << "Driving" << std::endl; }
};

class Car : public Vehicle {};

int main() {
	Car c;
	c.drive();
	return 0;
}

Accessing Base Class Members

A single derived class can freely read and write any base class member that was declared public or protected, since inheritance carries that accessibility down into the child — private base members remain off-limits even here.

Example: Accessing Base Class Members

cpp
#include <iostream>

class Vehicle {
public:
	int wheels = 4;
};

class Car : public Vehicle {};

int main() {
	Car c;
	std::cout << c.wheels << std::endl;
	return 0;
}

Constructor Order of Execution

Base class constructors always execute first to establish the inherited portion of the object, and only afterward does the derived class's own constructor run to finish initializing the properties it introduces itself.

Example: Constructor Order of Execution

cpp
#include <iostream>

class Vehicle {
public:
	Vehicle() { std::cout << "Vehicle first" << std::endl; }
};

class Car : public Vehicle {
public:
	Car() { std::cout << "Car second" << std::endl; }
};

int main() {
	Car c;
	return 0;
}

Private Inheritance

Private inheritance converts every public and protected member of the base class into a private member inside the derived class, meaning outside code loses all access to those inherited members through a derived object — even though the derived class itself can still use them internally.

Example: Private Inheritance

cpp
#include <iostream>

class Vehicle {
public:
	int wheels = 4;
};

class Car : private Vehicle {
public:
	void showWheels() { std::cout << wheels << std::endl; }
};

int main() {
	Car c;
	// c.wheels would fail to compile: private inheritance
	c.showWheels();
	return 0;
}

Protected Inheritance

Protected inheritance is a middle ground: it converts all inherited public and protected base members into protected members in the derived class, keeping them hidden from main() or outside code while still letting any further subclasses of the derived class access them.

Example: Protected Inheritance

cpp
#include <iostream>

class Vehicle {
public:
	int wheels = 4;
};

class Car : protected Vehicle {
public:
	void showWheels() { std::cout << wheels << std::endl; }
};

int main() {
	Car c;
	c.showWheels();
	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.