Junior
What is overloading and overriding methods in C++?
sobes.tech AI
Answer from AI
Method Overloading:
- Allows having multiple methods with the same name in one class.
- Differ by signature (number and/or types of parameters).
- The return type does not participate in the signature for overloading.
- The specific method is chosen by the compiler based on argument types at call time (static binding).
class MyClass {
public:
void print(int a) {
// Print integer
}
void print(double d) {
// Print floating-point number
}
void print(int a, int b) {
// Print two integers
}
};
Method Overriding:
- Allows a derived class to provide a specific implementation of a method already defined in the base class.
- The method in the derived class must have the same signature (name, number, and types of parameters) and the same return type (or covariant return type).
- Used with virtual functions (
virtual) to implement polymorphism. - The specific implementation is determined at runtime (dynamic binding), depending on the actual object type.
class Base {
public:
virtual void display() {
// Implementation in base class
}
};
class Derived : public Base {
public:
void display() override { // The override keyword (since C++11) helps avoid errors
// Specific implementation in derived class
}
};
Main differences:
| Characteristic | Method Overloading | Method Overriding |
|---|---|---|
| Usage location | In one class | In base and derived classes |
| Method name | Same | Same |
| Method signature | Different | Same |
| Mechanism of choice | Static binding (compile-time) | Dynamic binding (runtime) |
| Used with | Regular functions | Virtual functions |
| Goal | Different actions for different types | Specific implementation in the inheritor |