You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
C++ allows specification of more than one function of the same name in the same scope. These are called overloaded functions and are described in detail in Overloading. Overloaded functions enable programmers to supply different semantics for a function, depending on the types and number of arguments.
20
+
C++ allows specification of more than one function of the same name in the same scope. These are called *overloaded* functions. Overloaded functions enable you to supply different semantics for a function, depending on the types and number of arguments.
21
21
22
-
For example, a **print** function that takes a string (or **char \***) argument performs very different tasks than one that takes an argument of type **double**. Overloading permits uniform naming and prevents programmers from having to invent names such as `print_sz` or `print_d`. The following table shows what parts of a function declaration C++ uses to differentiate between groups of functions with the same name in the same scope.
22
+
For example, a **print** function that takes a **std::string** argument might perform very different tasks than one that takes an argument of type **double**. Overloading saves you from having to use names such as `print_string` or `print_double`. At compile time, the compiler chooses which overload to use based on the type of arguments passed in by the caller. If you call **print(42.0)** then the **void print(double d)** function will be invoked. If you call **print("hello world")** then the **void print(std::string)** overload will be invoked.
23
+
24
+
You can overload both member functions and non-member functions. The following table shows what parts of a function declaration C++ uses to differentiate between groups of functions with the same name in the same scope.
23
25
24
26
### Overloading Considerations
25
27
@@ -31,11 +33,9 @@ C++ allows specification of more than one function of the same name in the same
31
33
|Presence or absence of ellipsis|Yes|
32
34
|Use of `typedef` names|No|
33
35
|Unspecified array bounds|No|
34
-
|**const** or `volatile` (see below)|Yes|
36
+
|**const** or `volatile`|Yes, when applied to entire function|
35
37
|[ref-qualifier](#ref-qualifier)|Yes|
36
38
37
-
Although functions can be distinguished on the basis of return type, they cannot be overloaded on this basis. `Const` or `volatile` are only used as a basis for overloading if they are used in a class to apply to the **this** pointer for the class, not the function's return type. In other words, overloading applies only if the **const** or `volatile` keyword follows the function's argument list in the declaration.
38
-
39
39
## Example
40
40
The following example illustrates how overloading can be used.
41
41
@@ -44,68 +44,71 @@ C++ allows specification of more than one function of the same name in the same
44
44
// compile with: /EHsc
45
45
#include <iostream>
46
46
#include <math.h>
47
-
47
+
#include <string>
48
+
48
49
// Prototype three print functions.
49
-
int print( char *s ); // Print a string.
50
-
int print(double dvalue); // Print a double.
51
-
int print(double dvalue, int prec); // Print a double with a
52
-
// given precision.
53
-
using namespace std;
54
-
int main(int argc, char *argv[] )
55
-
{
56
-
const double d = 893094.2987;
57
-
if( argc < 2 )
58
-
{
59
-
// These calls to print invoke print( char *s ).
60
-
print("This program requires one argument." );
61
-
print("The argument specifies the number of" );
62
-
print("digits precision for the second number" );
63
-
print("printed." );
64
-
exit(0);
65
-
}
66
-
67
-
// Invoke print( double dvalue ).
68
-
print( d );
69
-
70
-
// Invoke print( double dvalue, int prec ).
71
-
print(d, atoi(argv[1] ) );
72
-
}
73
-
50
+
int print(std::string s); // Print a string.
51
+
int print(double dvalue); // Print a double.
52
+
int print(double dvalue, int prec); // Print a double with a
53
+
// given precision.
54
+
using namespace std;
55
+
int main(int argc, char *argv[])
56
+
{
57
+
const double d = 893094.2987;
58
+
if (argc < 2)
59
+
{
60
+
// These calls to print invoke print( char *s ).
61
+
print("This program requires one argument.");
62
+
print("The argument specifies the number of");
63
+
print("digits precision for the second number");
64
+
print("printed.");
65
+
exit(0);
66
+
}
67
+
68
+
// Invoke print( double dvalue ).
69
+
print(d);
70
+
71
+
// Invoke print( double dvalue, int prec ).
72
+
print(d, atoi(argv[1]));
73
+
}
74
+
74
75
// Print a string.
75
-
int print( char *s )
76
-
{
77
-
cout << s << endl;
78
-
return cout.good();
79
-
}
80
-
76
+
int print(string s)
77
+
{
78
+
cout << s << endl;
79
+
return cout.good();
80
+
}
81
+
81
82
// Print a double in default precision.
82
-
int print(double dvalue )
83
-
{
84
-
cout << dvalue << endl;
85
-
return cout.good();
86
-
}
87
-
88
-
// Print a double in specified precision.
83
+
int print(double dvalue)
84
+
{
85
+
cout << dvalue << endl;
86
+
return cout.good();
87
+
}
88
+
89
+
// Print a double in specified precision.
89
90
// Positive numbers for precision indicate how many digits
90
91
// precision after the decimal point to show. Negative
91
92
// numbers for precision indicate where to round the number
The left operand of the `->*` and `.*` (pointer to member) operators are treated the same way as the `.` and `->` (member-selection) operators with respect to argument matching.
398
+
399
+
## <aname="ref-qualifiers"></a> Ref-qualifiers on member functions
400
+
Ref qualifiers make it possible to overload a member function on the basis of whether the object pointed to by `this` is an rvalue or an lvalue. This feature can be used to avoid unnecessary copy operations in scenarios where you choose not to provide pointer access to the data. For example, assume class **C** initializes some data in its constructor, and returns a copy of that data in member function **get_data()**. If an object of type **C** is an rvalue that is about to be destroyed, then the compiler will choose the **get_data() &&** overload, which moves the data rather than copy it.
401
+
402
+
```cpp
403
+
#include<iostream>
404
+
#include<vector>
405
+
406
+
usingnamespacestd;
407
+
408
+
classC
409
+
{
410
+
411
+
public:
412
+
C() {/*expensive initialization*/}
413
+
vector<unsigned> get_data() &
414
+
{
415
+
cout << "lvalue\n";
416
+
return _data;
417
+
}
418
+
vector<unsigned> get_data() &&
419
+
{
420
+
cout << "rvalue\n";
421
+
return std::move(_data);
422
+
}
423
+
424
+
private:
425
+
vector<unsigned> _data;
426
+
};
427
+
428
+
intmain()
429
+
{
430
+
C c;
431
+
auto v = c.get_data(); // get a copy. prints "lvalue".
432
+
auto v2 = C().get_data(); // get the original. prints "rvalue"
433
+
return 0;
434
+
}
435
+
436
+
```
395
437
396
438
## Restrictions on overloading
397
439
Several restrictions govern an acceptable set of overloaded functions:
@@ -436,10 +478,13 @@ obj.name
436
478
void Print( char szToPrint[][9][42] );
437
479
```
438
480
439
-
## Declaration matching
481
+
## Overloading, overriding, and hiding
482
+
440
483
Any two function declarations of the same name in the same scope can refer to the same function, or to two discrete functions that are overloaded. If the argument lists of the declarations contain arguments of equivalent types (as described in the previous section), the function declarations refer to the same function. Otherwise, they refer to two different functions that are selected using overloading.
441
484
442
-
Class scope is strictly observed; therefore, a function declared in a base class is not in the same scope as a function declared in a derived class. If a function in a derived class is declared with the same name as a function in the base class, the derived-class function hides the base-class function instead of causing overloading.
485
+
Class scope is strictly observed; therefore, a function declared in a base class is not in the same scope as a function declared in a derived class. If a function in a derived class is declared with the same name as a virtual function in the base class, the derived-class function *overrides* the base-class function. For more information, see [Virtual Functions](../cpp/virtual-functions.md).
486
+
487
+
If the base class function is not declared as 'virtual', then the derived class function is said to *hide* it. Both overriding and hiding are distinct from overloading.
443
488
444
489
Block scope is strictly observed; therefore, a function declared in file scope is not in the same scope as a function declared locally. If a locally declared function has the same name as a function declared in file scope, the locally declared function hides the file-scoped function instead of causing overloading. For example:
## <a name="ref-qualifiers"></a> Ref-qualifiers on member functions
525
-
Ref qualifiers make it possible to overload a member function on the basis of whether the object pointed to by `this` is an rvalue or an lvalue. This feature can be used to avoid unnecessary copy operations. For example, assume class C initializes a large data set in its constructor, and returns a copy of that data in member function f(). If an object of C is an rvalue that is about to be destroyed, then it is safe for f() to simply move the data rather than copying it.
Copy file name to clipboardExpand all lines: docs/cpp/functions-cpp.md
+3-1Lines changed: 3 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -40,6 +40,8 @@ int main()
40
40
There is no practical limit to function length, but good design aims for functions that perform a single well-defined task. Complex algorithms should be broken up into easy-to-understand simpler functions whenever possible.
41
41
42
42
Functions that are defined at class scope are called member functions. In C++, unlike other languages, a function can also be defined at namespace scope (including the implicit global namespace). Such functions are called *free functions* or *non-member functions*; they are used extensively in the Standard Library.
43
+
44
+
Functions may be *overloaded*, which means different versions of a function may share the same name if they differ by the number and/or type of formal parameters. For more information, see [Function Overloading](../cpp/function-overloading.md).
43
45
44
46
## Parts of a function declaration
45
47
A minimal function *declaration* consists of the return type, function name, and parameter list (which may be empty), along with optional keywords that provide additional instructions to the compiler. The following example is a function declaration:
@@ -117,7 +119,7 @@ int sum(int a, int b)
117
119
118
120
7. (member functions only) `static` applied to a member function means that the function is not associated with any object instances of the class.
119
121
120
-
8. (Non-static member functions only) The ref-qualifier, which specifies to the compiler which overload of a function to choose when the implicit object parameter (*this) is an rvalue reference vs. an lvalue reference.
122
+
8. (Non-static member functions only) The ref-qualifier, which specifies to the compiler which overload of a function to choose when the implicit object parameter (*this) is an rvalue reference vs. an lvalue reference. For more information, see [Function Overloading](function-overloading.md#ref-qualifiers).
121
123
122
124
The following figure shows the parts of a function definition. The shaded area is the function body.
0 commit comments