C++ Review Road Fourteen - Function Overloading and Rewriting

In C++, we introduced overloading and rewriting of functions, but many times we tend to confuse these two concepts.

Today, let’s talk about the difference between these two concepts.

function overloading

In the same scope , functions with the same name but different parameter lists are called overloaded functions.

[Note]: The parameter list here is different, which refers to the type and number of parameters .

We can't tell if functions are overloaded by their return types .

Let's look at an example of function overloading:

int func(int a, int b)
{
	int c = a + b;
	return c;
}

float func(float a, float b)
{
	float c = a + b;
	return c;
}

The above two examples are function overloading, and the data types of their parameter lists are different.

function rewrite

Function overriding is mainly used between different scopes (between base and derived classes).

If the function is rewritten: the prototype of the function is the same , the parameter list, name, and return type are the same , but the specific operations in the function body can be different.

Function rewriting is mainly used to reflect a major feature of C++ - polymorphism. Therefore , the functions of the base class must be modified with the virtual keyword, and cannot be modified with the static keyword .

Here's an example of function rewriting:

Class A
{
public:
	virtual void print()
	{
		cout << m_a << endl;
	}
	
private:
	int m_a;
};


Class B : public A
{
public:
	virtual void print()
	{
		cout << m_b << endl;
	}
private:
	int m_b;
};

In class B, the print() function is rewritten, and it must have the same prototype as the print() function in the base class!

in conclusion:

The scope of the function overloads must be the same, and the parameter lists must be different

The scope of the function override is different, the function prototype must be the same.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325948797&siteId=291194637