C++ Single Inheritance
In this page:
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
#include <iostream>
class Vehicle {
public:
void drive() { std::cout << "Driving" << std::endl; }
};
class Car : public Vehicle {};
int main() {
Car c;
c.drive();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
class Vehicle {
public:
int wheels = 4;
};
class Car : public Vehicle {};
int main() {
Car c;
std::cout << c.wheels << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: