Sobes.tech
Junior — Middle

Is a virtual method a valid template in C++?

sobes.tech AI

Answer from AI

Yes, a virtual method is a valid and widely used pattern in C++. Virtual methods allow implementing polymorphism — the ability to call derived class methods through pointers or references to the base class.

Example:

class Base {
public:
    virtual void show() {
        std::cout << "Base show" << std::endl;
    }
    virtual ~Base() = default; // Virtual destructor
};

class Derived : public Base {
public:
    void show() override {
        std::cout << "Derived show" << std::endl;
    }
};

int main() {
    Base* obj = new Derived();
    obj->show(); // Calls Derived::show thanks to the virtual method
    delete obj;
}

Using virtual methods is the standard way to implement dynamic polymorphism in C++.