Method overloading in C++ is a feature that allows a class to have multiple member functions with the same name but with different parameters.
When a function is called, the compiler matches the parameters provided with the appropriate function based on the number, type, and order of the parameters.
#include <iostream>
using namespace std;
class Prim{
public:
void sameName() {
cout << "I am from Prim Cls" << endl;
}
};
class Sec : public Prim{
public:
void sameName() {
cout << "I am from Sec Cls" << endl;
}
};
int main() {
Sec Object;
Object.sameName();
Prim Obj_2;
Obj_2.sameName();
return 0;
}
In this example, we have two classes, Prim
and Sec
, and both have a method with the same name sameName()
. However, the implementation of the method is different in both classes.
In Sec
, the sameName()
method prints "I am from Sec Cls", and in Prim
, the sameName()
method prints "I am from Prim Cls".
When we create an object of Sec
and call the sameName()
method, the implementation in the Sec
class is executed, and "I am from Sec Cls" is printed. When we create an object of Prim
and call the sameName()
method, the implementation in the Prim
class is executed, and "I am from Prim Cls" is printed.
This is because the compiler distinguishes between the two methods based on their signature, which includes the method name and the types and number of parameters. When there are multiple methods with the same name but different signatures, the compiler decides which method to call based on the arguments passed to it. This is called method overloading.
No comments:
Post a Comment