Functions and Objects
Inheritance in C++
Inheritance is used to inherit another class' members, including fields and methods. A derived class inherits a base class' members.
Syntax
class derivedClass : modifier baseClass {
};
Notes
A child class inherits all members from the parent class without direct implementation within the child class.
If a function is written in the child class with the same name and parameters as one in the parent class, the parent class' method is overwritten with a direct call. To access the base class' method, prefix the method with 'baseClassName::'.
Example
using namespace std;
#include <string>
class Cat {
public:
string name;
Cat() {
this->name = "Garfield";
}
string sound(){ //implemented sound method from the interface
return "Meow!";
}
};
class Tiger : public Cat { //the variable 'name' and the method 'sound()' are inherited
public:
Tiger() : Cat(){
//calling the constructor in the base class, Cat
}
string sound(){ //overwriting the sound() method in Cat
return "Roar!";
}
string catSound() : Cat{
return Cat::sound(); //calling the sound method from Cat, non-overwritten
}
};