Junior — Middle
Can you explain what the term 'virtual' means in the context of programming and how it is used?
sobes.tech AI
Answer from AI
In programming, especially in C++, the keyword virtual is used to declare virtual functions — methods that can be overridden in derived classes and provide dynamic (polymorphic) calls.
This means that when calling a method through a pointer or reference to the base class, the version of the method corresponding to the actual type of the object will be called, not the type of the pointer.
Example:
#include <iostream>
class Base {
public:
virtual void show() { // virtual function
std::cout << "Base show" << std::endl;
}
};
class Derived : public Base {
public:
void show() override { // override
std::cout << "Derived show" << std::endl;
}
};
int main() {
Base* ptr = new Derived();
ptr->show(); // calls Derived::show thanks to virtual
delete ptr;
return 0;
}
If you remove virtual, then calling ptr->show() will invoke the base class method, even if the object is actually of type Derived.
Thus, virtual enables the implementation of polymorphism — an important principle of object-oriented programming.