Sobes.tech
Junior — Middle

What is the difference between method overloading and virtual functions in object-oriented programming?

sobes.tech AI

Answer from AI

Method overloading is the ability to have multiple methods with the same name in a class, but with different parameters (types or number). The specific method is chosen at compile time (static polymorphism).

Virtual functions are mechanisms that allow overriding methods in derived classes and ensure that the version of the method corresponding to the actual object type is called during runtime (dynamic polymorphism).

Example:

class Base {
public:
    void func(int x) { /* overload */ }
    virtual void virtFunc() { /* virtual function */ }
};

class Derived : public Base {
public:
    void func(double x) { /* overload */ }
    void virtFunc() override { /* override virtual function */ }
};

Summary:

  • Overloading is choosing a method based on parameters at compile time.
  • Virtual functions are choosing a method based on the object type at runtime.