Base Class and Derived Class in C++: A Comprehensive Guide with Examples
In object-oriented programming, a core concept is inheritance, which allows you to create new classes (derived classes) based on existing ones (base classes). This promotes code reusability and modularity. In C++, inheritance is implemented using the colon (:) operator.
Understanding the Concept:
- Base Class: A base class, also known as a parent class or superclass, provides fundamental properties and behaviors.
- Derived Class: A derived class, also known as a child class or subclass, inherits characteristics from the base class and can add its own unique features.
Key Advantages of Inheritance:
- Code Reusability: Derived classes inherit attributes and methods from the base class, reducing the need to write redundant code.
- Code Organization: Inheritance helps structure your code logically by grouping related functionalities into classes.
- Polymorphism: Inheritance enables polymorphism, allowing objects of different classes to be treated as objects of a common type.
Illustrative Example:
Let's consider a scenario involving animals:
#include
#include
// Base class: Animal
class Animal {
protected:
std::string name;
int age;
public:
Animal(std::string n, int a) : name(n), age(a) {}
void displayInfo() {
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
}
};
// Derived class: Dog (inherits from Animal)
class Dog : public Animal {
public:
Dog(std::string n, int a) : Animal(n, a) {}
void bark() {
std::cout << "Woof! Woof!" << std::endl;
}
};
// Derived class: Cat (inherits from Animal)
class Cat : public Animal {
public:
Cat(std::string n, int a) : Animal(n, a) {}
void meow() {
std::cout << "Meow!" << std::endl;
}
};
int main() {
Dog myDog("Buddy", 3);
Cat myCat("Whiskers", 2);
myDog.displayInfo();
myDog.bark();
std::cout << std::endl;
myCat.displayInfo();
myCat.meow();
return 0;
}
Explanation:
- Base class Animal: Defines common properties for all animals (name and age).
- Derived classes Dog and Cat: Inherit from the Animal class.
- Constructor: Each derived class initializes its base class using the
Animal(n, a)
constructor. - Methods: Both derived classes have specific methods (
bark()
andmeow()
) that define their unique behaviors.
Running the code will produce the following output:
Name: Buddy
Age: 3
Woof! Woof!
Name: Whiskers
Age: 2
Meow!
Key Points to Remember:
- Use the
public
keyword to indicate inheritance. - Derived classes can add new members (attributes and methods) that are not present in the base class.
- Use the
protected
access specifier in the base class to make members accessible to derived classes. - Inheritance promotes code reusability and facilitates code organization.
- Understanding inheritance is crucial for building complex and scalable object-oriented applications.