2023-01-21

What’s overloading in OOP anyway? An example with C++.

In object-oriented programming (OOP), overloading refers to the ability of a class or its member functions to have multiple implementations with different parameters. An example of overloading in C++ would be a class called “Calculator” that has several different versions of a function called “add”:

class Calculator {

public:

    int add(int a, int b);

    double add(double a, double b);

    float add(float a, float b);

};

 

In this example, the class “Calculator” has three different versions of the “add” function, each with a different set of parameters (int, int; double, double; and float, float). When an object of the “Calculator” class is created, all three versions of the “add” function will be available, and the appropriate version will be called based on the types of the arguments passed in.

 

Calculator calc;

int result1 = calc.add(3, 4);

double result2 = calc.add(3.5, 4.2);

float result3 = calc.add(3.5f, 4.2f);

 

In this example, the first call to “add” will call the version of the function that takes two ints, the second call will call the version that takes two doubles and the third call will call the version that takes two floats.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *