-
“Inheritance in C++ takes place between classes. Inheritance allows us to reuse classes by having other classes inherit their members. Inheritance involves creating new objects by directly acquiring the attributes and behaviours of other objects and then extending or specializing them.”
-
Bicycles could be a set of real world objects that could be modelled using C++.
-
“In an inheritance relationship, the class being inherited from is called the parent class , base class , or superclass , and the class doing the inheriting is called the child class , derived class , or subclass.”
#include <iostream>
using namespace std;
class Bicycle{
private:
string domain;
string ageRange;
public:
Bicycle(string d,string a){
domain=d;
ageRange=a;
}
void printInfo(){
cout<<"Bicycle's domain is "<<domain<<endl;
cout<<"Bicycle's age range is "<<ageRange<<endl;
}
};
class Specification: public Bicycle{
private:
int wheelSize;
string colour;
public:
Specification(string d,string a,int w,string c):Bicycle(d,a){
wheelSize=w;
colour=c;
}
void printSpec(){
cout<<"Bicycle's wheel size is "<<wheelSize<<" inch"<<endl;
cout<<"Bicycle's colour is "<<colour<<endl;
}
};
int main()
{
Specification x=Specification("offroad","adult",29,"green");
x.printInfo();
x.printSpec();
return 0;
}
- “Inheriting from a base class means we don’t have to redefine the information from the base class in our derived classes. We automatically receive the member functions and member variables of the base class through inheritance, and then simply add the additional functions or member variables we want. This not only saves work, but also means that if we ever update or modify the base class (e.g. add new functions, or fix a bug), all of our derived classes will automatically inherit the changes!”