C++ Class Inheritance Syntax
Inheritance is a fundamental concept in object-oriented programming (OOP). It allows us to create new classes (derived classes) that inherit properties and behaviors from existing classes (base classes). This promotes code reusability and modularity.
In C++, the inheritance syntax is straightforward. Here's a breakdown:
1. Base Class Declaration:
class BaseClass {
public:
// Public members: accessible from anywhere
void function1();
protected:
// Protected members: accessible from derived classes and within the class
int protectedValue;
private:
// Private members: accessible only within the class
int privateValue;
};
2. Derived Class Declaration:
class DerivedClass : accessSpecifier BaseClass {
public:
// New members and overridden methods
void function2();
};
3. Access Specifiers:
public
: Members of the base class become public members in the derived class.protected
: Members of the base class become protected members in the derived class.private
: Members of the base class remain private and cannot be accessed directly from the derived class.
4. Inheritance Types:
- Single Inheritance: A derived class inherits from only one base class.
- Multiple Inheritance: A derived class inherits from multiple base classes.
- Multilevel Inheritance: A derived class inherits from another derived class, which itself inherits from a base class.
- Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
Example:
#include
class Animal {
public:
void speak() { std::cout << "Animal sound\n"; }
};
class Dog : public Animal {
public:
void bark() { std::cout << "Woof!\n"; }
};
int main() {
Dog myDog;
myDog.speak(); // Inherited from Animal
myDog.bark(); // Specific to Dog
return 0;
}
Output:
Animal sound
Woof!
Key Points:
- The
:
symbol indicates inheritance. - The access specifier determines the visibility of base class members in the derived class.
- Derived classes can override methods inherited from the base class.
- Inheritance is a powerful mechanism for code reusability and modularity.
Understanding inheritance syntax is crucial for effective object-oriented programming in C++. By utilizing inheritance, you can create more complex and organized programs that are easier to maintain and extend.