The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Lecture/Lab #10
Function overloading, overload resolution, member functions
What will be the output of the following program?
int main() {
auto const n = 17;
n = -3;
std::cout << n;
}
struct point {
int x;
int y;
};
void move_by( point& p, point const& offset ) {
p.x += offset.x;
p.y += offset.y;
}
int main() {
point const p = { 5, 5 };
move_by( p, point{ -1, 1 } );
std::cout << p.x << ", " << p.y << std::endl;
}
How about this one?
void print( int ); // prints an integer
void print( double ); // prints a floating-point number
void print( std::string ); // prints a string
int main()
{
print( 42 ); // calls print( int )
print( 9.65 ); // calls print( double )
print( "Barcelona" ); // calls print( std::string )
}
One of the characteristic features of C++ is function overloading: the ability to define more than one function with the same name in the same scope:
If two functions are defined with the same name, but with different argument types, the compiler will choose the most appropriate function to invoke for each call.
Define overloaded function `divide` that mimics the behavior of the built-in operator `/`
Open the exercise template
Write your code, press Run to test
When you're done, grab your Repl's link and send it as a direct message to me (agurtovoy)
Click on the corresponding option in the "Lab10 exercises" poll in #general
A member function is a function that is defined as part of a class.
Member functions are sometimes referred to as methods.
Member functions are accessed the same way as class' data members:
obj.mem_func()
Member functions that do not modify the object's state should be marked as const.
Member function's definition can be provided outside of the class.
Member functions are in the class scope and have implicit access to other class members.
class point():
def __init__( self, x, y ):
self.x = x
self.y = y
def move_by( self, offset ):
self.x += offset.x
self.y += offset.y
def main():
p = point( 1, -1 )
p.move_by( point( -1, 1 ) )
main()
struct point {
point( int x, int y )
: x( x ), y( y ) {}
void move_by( point const& offset )
{
x += offset.x;
y += offset.y;
}
int x;
int y;
};
int main() {
point p( 1, -1 );
p.move_by( point( -1, 1 ) );
}
Implement member function `print` that takes a standard output stream and prints point's coordinates
Open the exercise template
Write your code, press Run to test
When you're done, grab your Repl's link and send it as a direct message to me (agurtovoy)
Click on the corresponding option in the "Lab10 exercises" poll in #general