C++
- C++ Introduction
- C++ Getting Started
- C++ Syntax
- C++ Output (Print Text)
- C++ Comments
- C++ Variables
- C++ Declare Multiple Variables
- C++ Identifiers
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ Conditions
- C++ Switch
- C++ While Loop
- C++ For Loop
- C++ Break And Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Function Overloading
- C++ OOP
- C++ Classes And Objects
- C++ Class Methods
- C++ Constructors
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Multilevel Inheritance
- C++ Multiple Inheritance
- C++ Inheritance Access
- C++ Polymorphism
- C++ Files
- C++ Exceptions
- C++ How To Add Two Numbers
C++ Inheritance
Inheritance
In C++, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:
- derived class (child) - the class that inherits from another class
- base class (parent) - the class being inherited from
To inherit from a class, use the :
symbol.
In the example below, the Car
class (child) inherits the attributes and methods from the Vehicle
class (parent):
Example
// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};
// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};
int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};
// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};
int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}
Why And When To Use "Inheritance"?
- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.
Practice Excercise Practice now
Products
Partner
Copyright © RVR Innovations LLP 2024 | All rights reserved - Mytat.co is the venture of RVR Innovations LLP