Answer: Function overloading and function virtual functions in C allow developers to create functions with the same name but different parameter lists or behaviors. Detailed description: Function overloading: Create functions with the same name but different parameter lists to use functions with similar functionality in different situations. Function virtual function: Override the function of the base class in the derived class, used for polymorphism, allowing the derived class to provide a different implementation than the base class.
Function overloading and function virtual functions in C
Function overloading
Function overloading allows you to create multiple functions with the same name but different parameter lists. This is useful if you need to use functions with similar functionality in different situations.
Syntax:
ret_type function_name(parameter_list_1); ret_type function_name(parameter_list_2); ...
Example:
void printInfo(int x) { cout << "int: " << x << endl; } void printInfo(double x) { cout << "double: " << x << endl; } int main() { int a = 10; double b = 3.14; printInfo(a); // calls printInfo(int) printInfo(b); // calls printInfo(double) return 0; }
Function virtual function
Function Virtual functions allow you to override functions of a base class in a derived class. This is useful for polymorphism and object-oriented programming because it allows you to provide a derived class with a different implementation than the base class.
Syntax:
Use the keyword virtual
when declaring a function in a base class.
virtual ret_type function_name(parameter_list) const = 0;
Use the keyword override
when overriding a function in a derived class.
override ret_type function_name(parameter_list) const { /* implementation */ }
##Example:
class Shape { public: virtual double area() const = 0; // pure virtual function }; class Circle : public Shape { public: double radius; Circle(double radius) : radius(radius) {} override double area() const { return 3.14 * radius * radius; } }; class Square : public Shape { public: double side; Square(double side) : side(side) {} override double area() const { return side * side; } }; int main() { Shape* s1 = new Circle(5); Shape* s2 = new Square(10); cout << "Area of circle: " << s1->area() << endl; cout << "Area of square: " << s2->area() << endl; return 0; }
Note:
in the base class.
and
= 0 in the base class) must be overridden in the derived class, otherwise the derived class will become an abstract class.
The above is the detailed content of C++ function overloading and function virtual functions. For more information, please follow other related articles on the PHP Chinese website!