Answer the question
In order to leave comments, you need to log in
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
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()
}
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 questionAsk a Question
731 491 924 answers to any question