M
M
mlwrm2016-03-15 23:24:26
C++ / C#
mlwrm, 2016-03-15 23:24:26

Where and how to correctly use the virtual specifier in C++?

Hello, please explain how and where to use the virtual specifier in C++ correctly?
As far as I understand, function virtualization in C++ is no different from their overloading in child classes, then why create virtual functions at all, especially considering that they can have a body and cannot be considered abstract and used in the same way as in Java.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2016-03-16
@malworm

This is called "dynamic polymorphism".
Virtual methods are useful in that when you call a method through a reference or pointer to the base class, you are actually calling a method on the child class:

class B {
public:
    virtual void f() {}
    ...
}

class D: public B{
public:
    void f(){}
    ...
}
...
doF(D());
...
void doF(const B& b){
    b.f();// вызовется D::f() 
}

If you write "=0;" instead of the body of a virtual function, you get a purely virtual class. This is already a full-fledged analogue of an abstract class in Java. And if you make all methods purely virtual and do not make data fields, you get an analogue of the interface.
The destructor of the class that is created for inheritance must be virtual. Otherwise, doing this:
B *d = new D();
delete d;
you will only call the destructor of the base class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question