What is the difference from overwriting a non-virtual function and a virtual one?

In C ++: What is the difference from rewriting a non-virtual function and rewriting a virtual?

+3
source share
2 answers

C virtual:

class Base {
    virtual void Foo() { std::cout << "Foo in Base" << std::endl;}
};

class Derived : public Base {
    virtual void Foo() { std::cout << "Foo in Derived" << std::endl;}
};

// in main()
Derived* d = new Derived();
d->Foo(); // prints "Foo in Derived"

Base* b = new Derived();
b->Foo(); // prints "Foo in Derived"

and without (same code, but leave it virtual):

// in main() 
Derived* d = new Derived();
d->Foo(); // prints "Foo in Derived"

Base* b = new Derived();
b->Foo(); // prints "Foo in Base"

so the difference is that without virtualthere is no true polymorphism at runtime: which function is called is determined by the compiler depending on the current type of pointer / link through which it is called.

virtual (vtable), - , , . Foo Derived, , , Foo Base -.

+8

, .

:

class Vehicle
{
public:
   void PrintType(); // Prints "Vehicle"
};

class Car: public Vehicle
{
 // overwrite PrintType to print "Car"
};


// In main
void main()
{
Vehicle *s = new Car();
s->PrintType();  // Prints "Vehicle"

// If PrintType was virtual then the type of s will be evaluated at runtime and the inherited function will be called printing "Car"
}
0

All Articles