I'm having trouble understanding what the purpose of the virtual
keyword in C++. I know C and Java very well but I'm new to C++
From wikipedia
In object-oriented programming, a virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature.
However I can override a method as seen below without using the virtual
keyword
#include <iostream>
using namespace std;
class A {
public:
int a();
};
int A::a() {
return 1;
}
class B : A {
public:
int a();
};
int B::a() {
return 2;
}
int main() {
B b;
cout << b.a() << endl;
return 0;
}
//output: 2
As you can see below, the function A::a is successfully overridden with B::a without requiring virtual
Compounding my confusion is this statement about virtual destructors, also from wikipedia
as illustrated in the following example, it is important for a C++ base class to have a virtual destructor to ensure that the destructor from the most derived class will always be called.
So virtual
also tells the compiler to call up the parent's destructors? This seems to be very different from my original understanding of virtual
as "make the function overridable"
B obj; A* p = &obj;
orA& ref = obj;
– Regurgitate