Junior — Middle
Can you explain the difference between the keywords 'virtual' and 'override' in the context of OOP?
sobes.tech AI
Answer from AI
In the context of OOP and C++/C# languages, the keyword virtual is used to declare a method in a base class that can be overridden in derived classes. This allows for polymorphism — calling a method through a pointer or reference to the base class will dynamically invoke the version of the method in the derived class.
The keyword override is used in a derived class to explicitly indicate that a method overrides a virtual method in the base class. This helps the compiler verify that the method indeed overrides an existing virtual method and prevents errors, such as typos in the name or signature mismatch.
Example in C++:
class Base {
public:
virtual void foo() { // virtual - method can be overridden
std::cout << "Base foo" << std::endl;
}
};
class Derived : public Base {
public:
void foo() override { // override - explicitly overriding the base virtual method
std::cout << "Derived foo" << std::endl;
}
};
Thus:
virtualdeclares a method as virtual in the base class.overrideconfirms that the method in the derived class overrides a virtual method of the base class.