12.2 Override
12.2 Override
classroom.udacity.com/nanodegrees/nd213/parts/f9fffe8e-1984-4045-92b6-
64854de4df2b/modules/70db33ed-8e7e-45e9-ab1d-3d0b257fc196/lessons/15cd39a7-3fda-495d-af24-
c5ccd45826a8/concepts/c8984e2f-241d-492f-8a81-31bee196143c
class Animal {
public:
virtual std::string Talk() const = 0;
};
class Cat {
public:
std::string Talk() const { return std::string("Meow"); }
};
In this example, Animal exposes a virtual function: Talk() , but does not define it.
Because Animal::Talk() is undefined, it is called a pure virtual function, as opposed to an
ordinary (impure? ) virtual function.
Furthermore, because Animal contains a pure virtual function, the user cannot
instantiate an object of type Animal . This makes Animal an abstract class.
1/2
Cat , however, inherits from Animal and overrides Animal::Talk() with Cat::Talk() ,
which is defined. Therefore, it is possible to instantiate an object of type Cat .
Instructions
1. Create a class Dog to inherit from Animal .
2. Define Dog::Talk() to override the virtual function Animal::Talk() .
3. Confirm that the tests pass.
Menu
full screen
Expand
Function Hiding
Function hiding is closely related, but distinct from, overriding.
A derived class hides a base class function, as opposed to overriding it, if the base class
function is not specified to be virtual .
class Cat {
public:
std::string Talk() const { return std::string("Meow"); }
};
In this example, Cat is the base class and Lion is the derived class. Both Cat and
Lion have Talk() member functions.
When an object of type Lion calls Talk() , the object will run Lion::Talk() , not
Cat::Talk() .
The distinction between overriding and hiding is subtle and not terribly significant, but in
certain situations hiding can lead to bizarre errors, particularly when the two functions
have slightly different function signatures.
2/2