Function Overloading
Contents
• Overloading Constructor Functions
• Creating and Using A Copy Constructor
• Using Default Arguments
• Overloading and Ambiguity
• Exercises
Overloading Constructor Functions
• It is possible and common to overload a class’s constructor function.
However, it is not possible to overload a destructor.
• The main reasons for overloading a constructor function:
• To gain flexibility
• To support arrays
• To create copy constructors
• If a program attempts to create an object for which no matching constructor
is found, a compile-time error occurs.
Creating and Using A Copy Constructor
• By defining a copy constructor, you can fully specify exactly what occurs when a copy of an
object is made.
• The copy constructor only applies to initializations.
• It is possible to specify precisely how one object will initialize another by defining a copy
constructor.
• Once defined, the copy constructor is called whenever an object is used to initialize another.
• The most common form of copy constructor is shown here.
classname(classname &obj){
//body of constructor
}
Using Default Arguments
• This is a feature of C++ that is related to function overloading.
• This feature is called the default argument, and it allows you to give a
parameter a default value when no corresponding argument is specified
when the function is called.
• Once you begin to define default parameters, you cannot specify any
parameters that have no defaults.
Overloading and Ambiguity
• Overloading-caused ambiguity can be introduced through type conversions,
reference parameters, and default arguments.
• Ambiguity must be removed before your program will compile without
error.
Exercises
• Create a Person class with multiple constructors. Some constructors should
take different parameters like name, age, and address.
• Extend the Person class from exercise 1 with a copy constructor that creates
a new object by copying the attributes of an existing object.
• Create a Calculator class with methods for addition, subtraction,
multiplication, and division. Implement default arguments for one or more
operands.