Lecture
The mechanism of virtual functions is addressed in cases where each derived class requires its own version of some component function. Classes that include such functions are called polymorphic and play a special role in OOP.
Consider how non-virtual component functions with the same names, types, and parameter signatures behave when inheriting.
Example 2.3.1
Example 2.3.1
class base
{
public:
void print () {cout << “\ nbase”;}
};
class dir : public base
{
public:
void print () {cout << “\ ndir”;}
};
void main ()
{
base B, * bp = & B;
dir D, * dp = & D;
base * p = & D;
bp -> print (); // base
dp -> print (); // dir
p -> print (); // base
}
In the latter case, the print function of the base class is called, although the pointer p is set to an object of the derived class. The fact is that the choice of the necessary function is performed when the program is compiled and is determined by the type of the pointer, and not by its value. This mode is called early or static binding . Greater flexibility provides later ( delayed ) or dynamic binding , which is provided by the mechanism of virtual functions . Any non-static base class function can be made virtual by using the virtual keyword .
Example
class base
{
public:
virtual void print () {cout << “\ nbase”;}
. . .
};
// and so on - see the previous example.
In this case, will be printed
base
dir
dir
Comments
To leave a comment
C ++ (C plus plus)
Terms: C ++ (C plus plus)