0% found this document useful (0 votes)
35 views29 pages

Week4 Miscellaneous

This document discusses miscellaneous C++ topics including inline functions, default arguments, function overloading, and function templates. Inline functions allow a function body to be substituted for a function call to reduce overhead. Default arguments specify parameter values if none are provided. Function overloading defines multiple functions with the same name but different parameters to handle different data types. Function templates provide a compact way to define identical logic for different data types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views29 pages

Week4 Miscellaneous

This document discusses miscellaneous C++ topics including inline functions, default arguments, function overloading, and function templates. Inline functions allow a function body to be substituted for a function call to reduce overhead. Default arguments specify parameter values if none are provided. Function overloading defines multiple functions with the same name but different parameters to handle different data types. Function templates provide a compact way to define identical logic for different data types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 29

Miscellaneous C++ Topics

CS-2303
System Programming Concepts
(Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie and
from C: How to Program, 5th and 6th editions, by Deitel and Deitel)

CS-2303, C-Term 2010 Miscellaneous C++ Topi 1


cs
Outline – More topics from Ch 18

• Inline functions

• Default Arguments

• Function Overloading

• Function Templates

CS-2303, C-Term 2010 Miscellaneous C++ Topi 2


cs
Inline Functions

• Advice to compiler that the body of the function


may be substituted for a call to that function

• Insert the qualifier inline before return type of


function

• Example:–
inline int max(int a, int b) {
return (a>b) ? a : b;
}

CS-2303, C-Term 2010 Miscellaneous C++ Topi 3


cs
Inline Functions (continued)

• Reasons:–
• Reduce function call overhead—especially for small
functions in inner loops
• Takes advantage of compiler’s local optimizations
• Trade-off of inline functions
• Multiple copies of the function code are inserted in
the program (possibly making the program larger)
• The compiler may ignore the inline
qualifier
• Typically does so for all but the smallest functions

CS-2303, C-Term 2010 Miscellaneous C++ Topi 4


cs
Inline Function Example
1 // Fig. 18.3: fig18_03.cpp
2 // Using an inline function to calculate the volume of a cube.
3 #include <iostream>
4 using std::cout; using avoids repeating std::
5 using std::cin;
6 using std::endl;
7
inline qualifier
8 // Definition of inline function cube. Definition of function appears
9 // before function is called, so a function prototype is not required.
10 // First line of function definition acts as the prototype.
11 inline double cube( const double side )
12 {
13 return side * side * side; // calculate the cube of side Complete function definition so the
14 } // end function cube compiler knows how to expand a
15 cube function call into its inlined
16 int main() code.
17 {
18 double sideValue; // stores value entered by user
19

CS-2303, C-Term 2010 Miscellaneous C++ Topi 5


cs
Inline Functions (continued)

• Typical usage:– Member function of a class


• Very simple, short, fast operations
• Especially in inner loops
• Especially set and get functions
• Saves the (non-trivial) overhead of invoking a
method, creating activation record, etc.
• Encourages cleaner, more readable code
Widely used whenever you ask yourself
about efficiency of a calling a function vs.
• inline qualifier is strictly advisory
accessing a class member directly

CS-2303, C-Term 2010 Miscellaneous C++ Topi 6


cs
Questions?

CS-2303, C-Term 2010 Miscellaneous C++ Topi 7


cs
Default Argument

• Definition:– A default value to be passed to a


parameter
• When the function/method call does not specify an argument
for that parameter

• Example
void prnt(int value, int base = 10);

prnt(100); //prints in base 10
prnt(100,16); //prints in base 16
prnt(100,8); //prints in base 8
prnt(100,3); //prints in base 3
CS-2303, C-Term 2010 Miscellaneous C++ Topi 8
cs
Default Arguments (continued)

• Must be rightmost parameter(s) in


parameter list of function

• Default value specified in function


prototype
• Usually in class header file
• So compiler knows how to compile calls
• If one argument is defaulted, all arguments
to right of it must be defaulted also
CS-2303, C-Term 2010 Miscellaneous C++ Topi 9
cs
Default Argument Example
void f(int a, double b, int c = 10,
bool d = false);

• f(100, 3.14) // okay


• f(100, 3.14, 15) // okay
• f(100, 3.14, 15, true) // okay
• f(100, 3.14, , true) // no good
• f(100, 3.14, 10, true) // okay

See also Fig 18.8 of D&D


CS-2303, C-Term 2010 Miscellaneous C++ Topi 10
cs
Summary – Default Arguments

• Simplest form of function overloading

• Default values specified in header/prototype

• Defaults applied from right to left

CS-2303, C-Term 2010 Miscellaneous C++ Topi 11


cs
Questions?

CS-2303, C-Term 2010 Miscellaneous C++ Topi 12


cs
Function Overloading

• Multiple functions or methods with same name,


but different types of parameters and/or results

• Compiler selects proper function to execute based


on number, types, and order of arguments in the
function call.

• Commonly used to create several functions of the


same name that perform similar tasks, but on
different data types. Widely used for readable code
CS-2303, C-Term 2010 Miscellaneous C++ Topi 13
cs
Function Overloading Example
1 // Fig. 18.10: fig18_10.cpp
2 // Overloaded functions.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 // function square for int values Defining a square function
8 int square( int x )
9 {
for ints
10 cout << "square of integer " << x << " is ";
11 return x * x;
12 } // end function square with int argument
13
14 // function square for double values
Defining a square function for
15 double square( double y )
16 { doubles
17 cout << "square of double " << y << " is ";
18 return y * y;
19 } // end function square with double argument
20
21 int main()
22 {
23 cout << square( 7 ); // calls int version
24 cout << endl;
25 cout << square( 7.5 ); // calls double version
Output confirms that the proper
26 cout << endl; function was called in each case
27 return 0; // indicates successful termination
28 } // end main

square of integer 7 is 49
square of double 7.5 is 56.25
CS-2303, C-Term 2010 Miscellaneous C++ Topi 14
cs
Compiling Overloaded Functions

• Compiler mangles function names to create


unique names for linker – e.g.,
– _square$qi
– _square$qd

• These become visible to programmer during


linking, loading, and (sometimes)
debugging!

CS-2303, C-Term 2010 Miscellaneous C++ Topi 15


cs
Another Function Overloading Example
double sqrt(double x){
/* invoke hardware square root
function of a double >= 0 */
}

complex sqrt(complex x){


/* algorithm to take square root
of a complex number */
}

CS-2303, C-Term 2010 Miscellaneous C++ Topi 16


cs
Overloaded Constructors

• Constructors are like functions or methods

• May be overloaded

• Useful for initializing a class object from


various kinds of input

CS-2303, C-Term 2010 Miscellaneous C++ Topi 17


cs
Questions?

CS-2303, C-Term 2010 Miscellaneous C++ Topi 18


cs
Problem

• What about the case when all of the


overloaded functions have essentially the
same code, but for different types

• Not good style to write a bunch of nearly


identical code
• Inefficient of programmer time
• Various instances can get out of sync with each
other
• Some cases might be missed

CS-2303, C-Term 2010 Miscellaneous C++ Topi 19


cs
Solution – Function Templates

• A more compact and convenient form of


overloading.
– Identical program logic and operations for each
data type.

CS-2303, C-Term 2010 Miscellaneous C++ Topi 20


cs
Function Template
• Written by programmer once
• Essentially defines a whole family of overloaded
functions
• Begins with the template keyword
• Contains a template parameter list of formal type
and the parameters for the function template are
enclosed in angle brackets (<>)
• Formal type parameters
– Preceded by keyword typename or keyword class
– Placeholders for fundamental types or user-defined
types
CS-2303, C-Term 2010 Miscellaneous C++ Topi 21
cs
Function Template Example
1 // Fig. 18.12: maximum.h
2 // Definition of function template maximum.
3
4 template < class T > // or template< typename T >
5 T maximum( T value1, T value2, T value3 )
6 { Using formal type parameter T in place of data type
7 T maximumValue = value1; // assume value1 is maximum
8
9 // determine whether value2 is greater than maximumValue
10 if ( value2 > maximumValue )
11 maximumValue = value2;
12
13 // determine whether value3 is greater than maximumValue
14 if ( value3 > maximumValue )
15 maximumValue = value3;
16
17 return maximumValue;
18 } // end function template maximum

CS-2303, C-Term 2010 Miscellaneous C++ Topi 22


cs
Result

• Whole Family of Overloaded Functions


– All with the “same” source code
– All doing the same thing, but with different
data types
– Defined in one place

• Common Programming Errors


• Not placing keyword class or keyword typename before
every formal type parameter of a function template
• Writing < class S, T > instead of
< class S, class T > ) is a syntax error

CS-2303, C-Term 2010 Miscellaneous C++ Topi 23


cs
Definition:–

Function Template Specialization


• Specialization:– the automatic generation of a new
“overloaded function” from the template as needed
• I.e., whenever a function template is called with a particular type

• Example for function template max with type


parameter T called with int arguments
– Compiler detects a max invocation in the program
code.
– int is substituted for T throughout the template
definition.
– This produces function-template specialization
max<int>
CS-2303, C-Term 2010 Miscellaneous C++ Topi 24
cs
Function Template
Specialization Example
Example
1 // Fig. 18.13: fig18_13.cpp
2 // Function template maximum test program.
3 #include <iostream>
4 using std::cout;
5 using std::cin;
6 using std::endl;
7
8
Compiler:–
#include "maximum.h" // include definition of function template maximum
9 1. Suspends what it was doing
10 int main() 2. Generates a new overloaded
11 {
12 // demonstrate maximum with int values function from template maximum
13 int int1, int2, int3; for parameter type int
14
15 cout << "Input three integer values: ";
3. Compiles this new function
16 cin >> int1 >> int2 >> int3; 4. Returns to this program and
17 compiles a call to new function.
18 // invoke int version of maximum
19 cout << "The maximum integer value is: "
20 << maximum( int1, int2, int3 );
21
22 // demonstrate maximum with double values Invoking maximum with int arguments
23 double double1, double2, double3;
24
25 cout << "\n\nInput three double values: ";
26 cin >> double1 >> double2 >> double3;
27
CS-2303, C-Term 2010 Miscellaneous C++ Topi 25
cs
Function Template
Specialization Example
Example (continued)
28 // invoke double version of maximum
29 cout << "The maximum double value is: "
30 << maximum( double1, double2, double3 );
31
32 // demonstrate maximum with char values
Invoking maximum with double
33 char char1, char2, char3;
arguments
34
35 cout << "\n\nInput three characters: "; Compiler does same again, but for
36 cin >> char1 >> char2 >> char3;
parameter type double
37
38 // invoke char version of maximum
39 cout << "The maximum character value is: "
40 << maximum( char1, char2, char3 ) << endl;
41 return 0; // indicates successful termination
Invoking maximum with char
42 } // end main
arguments
Input three integer values: 1 2 3
The maximum integer value is: 3 And again, but for
Input three double values: 3.3 2.2 1.1 parameter type char
The maximum double value is: 3.3

Input three characters: A C B


The maximum character value is: C

CS-2303, C-Term 2010 Miscellaneous C++ Topi 26


cs
Specialization (continued)

• Each time that the compiler encounters a use of


maximum with a type that it has not seen before
– … it creates a new instance of the function
maximum with new parameter types
– With new mangled name!

CS-2303, C-Term 2010 Miscellaneous C++ Topi 27


cs
Function Templates Summary

• Very important for


– Code readability
– Code reuse
– Good coding style
– Programmer efficiency

• Foundation of other template features in C+


+
CS-2303, C-Term 2010 Miscellaneous C++ Topi 28
cs
Questions?

CS-2303, C-Term 2010 Miscellaneous C++ Topi 29


cs

You might also like