In this lesson, we will see how we can start to implement inheritance in C++.
Lets imagine we have an Actor class, defined as follows:
class Actor {
// Actor class code
};
We want to create a new class, Character
, that will inherit from the Actor
class.
We can do that in the following way:
class Character : Actor {
// Character class code
};
After the name of the class we are creating, we can choose which class it inherits from. We do that using a :
followed by the name of the class we want to be the parent.
How can we create a Dog
class that inherits from an Animal
class?
In the previous lesson, we had this diagram for an inheritance tree we wanted to create:
Lets set it up in code:
class Actor {
public:
void Render() {};
};
class Character : Actor {
public:
void Move() {};
void Attack() {};
void DropLoot() {};
};
class Goblin : Character {
public:
void Enrage() {};
};
class Dragon : Character {
public:
void Fly() {};
};
Our code, at this point, might not work entirely as we expect. Lets try this:
Character PlayerOne;
PlayerOne.Render();
We will get an error claiming that Render
is private. This may be surprising, as we have declared it as public within the Actor
class.
However, just like functions and variables, inheritance itself can be public
or private
. By default, class inheritance is private
.
We can change this to be public
within our class heading:
class Character : public Actor {};
Now, anything that is public
in Actor
will be public
in Monster
Setting the inheritance to public
will not overrule access restrictions within the base class. If something was private
in Actor
, it will still be private in Monster
.
In practice, public inheritance is by far the most useful and most commonly used, so it will be what we focus on in this course.
What would be the effect of compiling and running the following code?
class Animal {
public:
void Move() {};
};
class Dog : Animal {};
int main() {
Dog MyDog;
MyDog.Move();
}
How could we update the Dog
class to fix this problem?
class Animal {
public:
void Move() {};
}
class Dog : Animal {};
int main() {
Dog MyDog;
MyDog.Move();
}
final
- Preventing InheritanceSometimes, we create a class that is not designed to ever have a child class. To clarify that intent, and have the compiler to enforce it, we can add the final
specifier to the class heading:
class Actor final {};
class Monster : Actor {};
Should anyone try to inherit from our class, as done on line 3 in the above example, their code will not compile. This will yield an error similar to the following:
Cannot inherit from 'Actor' as it has been declared as 'final'
— Fixed grammar issue in one of the quiz questions
— First Published
Become a software engineer with C++. Starting from the basics, we guide you step by step along the way