Welcome to the exciting world of C++ Inheritance! In this lesson, we'll explore how to create a strong foundation for your C++ programming skills by learning about inheritance.
By the end of this lesson, you'll be able to:
Inheritance is a powerful feature of object-oriented programming that allows you to create a new class, called the derived class, based on an existing class, known as the base class. This means that the derived class inherits all properties and methods of the base class.
A derived class inherits characteristics from a base class. Here's a simple example:
// Base class
class Animal {
public:
std::string name;
int age;
void eat() {
std::cout << name << " is eating.\n";
}
};
// Derived class
class Dog : public Animal {
public:
void bark() {
std::cout << name << " is barking.\n";
}
};In this example, Dog is a derived class that inherits from the Animal base class. A Dog object will have access to all properties and methods of the Animal class.
To access base class members in a derived class, simply use the name of the member variable or method.
Dog myDog;
myDog.name = "Fido";
myDog.age = 5;
myDog.eat(); // "Fido is eating."
myDog.bark(); // "Fido is barking."You can override a base class function in a derived class by providing a new implementation for the function in the derived class.
// Base class
class Animal {
public:
std::string name;
int age;
void eat() {
std::cout << name << " is eating.\n";
}
};
// Derived class
class Dog : public Animal {
public:
void eat() {
std::cout << name << " is eating a bone.\n";
}
};In this example, the eat() function in the Dog class overrides the eat() function in the Animal class. When we call the eat() function on a Dog object, the Dog's implementation will be used.
Multiple inheritance allows a class to inherit from more than one base class. Here's an example:
// Base class 1
class Mammal {
public:
std::string habitat;
void live() {
std::cout << name << " lives in " << habitat << ".\n";
}
};
// Base class 2
class Carnivore {
public:
std::string diet;
void hunt() {
std::cout << name << " is hunting for food.\n";
}
};
// Derived class
class Wolf : public Mammal, public Carnivore {
public:
std::string name;
};In this example, the Wolf class inherits from both the Mammal and Carnivore classes. A Wolf object will have access to all properties and methods of both base classes.
What is Inheritance in C++?
This lesson provides a strong foundation for understanding C++ inheritance. By learning about inheritance, you'll be able to create more efficient, organized, and maintainable code. Happy learning, and remember: practice makes perfect! š”