C++ Overloading

C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively.

Following is the example where same function print() is being used to print different data types:

#include<iostream>

usingnamespacestd;

classprintData

{

public:

voidprint(inti){

cout<<“Printing int: “<<i<<endl;

}

voidprint(double  f){

cout<<“Printing float: “<< f <<endl;

}

voidprint(char* c){

cout<<“Printing character: “<< c <<endl;

}

};

int main(void)

{

printDatapd;

// Call print to print integer

pd.print(5);

// Call print to print float

pd.print(500.263);

// Call print to print character

pd.print(“Hello C++”);

return0;

}

Related Posts

© 2024 Software Engineering - Theme by WPEnjoy · Powered by WordPress