C++ Private Inheritance šŸŽÆ

beginner
16 min

C++ Private Inheritance šŸŽÆ

Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of C++ Private Inheritance. Let's get started! šŸ“

Understanding Inheritance šŸ’”

Inheritance is a powerful feature in C++ that allows us to create new classes based on existing ones. The existing class is called the base class or parent class, and the new class is called the derived class or child class.

Base Class šŸ“

The base class is a pre-existing class that provides properties and behaviors to the derived class.

Derived Class šŸ“

The derived class is a new class that inherits properties and behaviors from the base class.

Private Inheritance šŸ’”

Private inheritance is a type of inheritance in C++ where the derived class inherits all members of the base class, but the base class members are private in the derived class.

This means that the derived class cannot access or modify the base class members directly. Instead, it can use them indirectly through public member functions of the base class.

Example of Private Inheritance šŸ“

Let's look at an example to understand private inheritance better:

cpp
#include <iostream> using namespace std; // Base class class Animal { public: void eat() { cout << "Eating" << endl; } void sleep() { cout << "Sleeping" << endl; } private: int age; }; // Derived class (private inheritance) class Dog : private Animal { public: void bark() { cout << "Woof!" << endl; } }; int main() { Dog myDog; myDog.eat(); // Accessing public functions from base class // myDog.age; // Error: age is private in the derived class myDog.bark(); return 0; }

In this example, the Dog class inherits from the Animal class privately. As a result, the Dog class cannot access the age variable directly, but it can still call the eat() function from the Animal class.

Quiz šŸ“

Quick Quiz
Question 1 of 1

What is the difference between public inheritance and private inheritance in C++?

That's all for today! Private inheritance is a powerful tool in C++ that allows us to create derived classes with controlled access to base class members. Stay tuned for more exciting lessons on C++! šŸ’”

Happy coding! šŸŽÆ