Luke
Luke

Reputation: 5971

What is the difference from overwriting a nonvirtual function and a virtual?

In C++: What is the difference from overwriting a nonvirtual function and overwriting a virtual one?

Upvotes: 3

Views: 156

Answers (2)

Alexander Gessler
Alexander Gessler

Reputation: 46607

With 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 out the 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 virtual, there is no true runtime polymorphism: which function is called is decided by the compiler depending on the current type of the pointer/reference through which it is called.

With virtual, the objects maintains a list of virtual functions (vtable) in which it looks up the actual address of the function to call - at runtime, every time you call a virtual member of it. In this sample, the entry for Foo is implicitly modified by the Derived constructor to point to the overridden function so it doesn't matter that Foo is called through an Base-pointer.

Upvotes: 8

Pepe
Pepe

Reputation: 6480

Overwriting a virtual function will ensure that the type of the object is assessed at runtime and the appropriate method is called.

Example:

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"
}

Upvotes: 0

Related Questions