L5 Overloading, Constructor and Destructor
L5 Overloading, Constructor and Destructor
• The C++ language allows the programmer to specify more than one
definition for a function name or operator.
• It is one of the many useful features that object-oriented languages provide,
which increases the power and flexibility of C++.
• Overloading is a technique of using a single identifier to define different
methods of a class that differs in their input and output parameters.
• Overloading is generally used when a program block executes the same task
but is slightly distinct in a set of parameters.
• Overloading is a concept used to avoid redundant code where the
same method name or operator is used multiple times but with a
different set of parameters or number of operands.
Operator Overloading
Function Overloading
Operator Overloading
Operator overloading is a type of polymorphism in which a
single operator is overloaded to give a user-defined meaning.
Operator overloading provides a flexible option for creating
new definitions of C++ operators.
There are some C++ operators which cannot be overloaded
class classname
{
---
public
returntype operator symbol (arguments) {
... .. ...
}
... .. ...
};
Operator Overloading in Unary Operators
public:
// Constructor to initialize count to 100
Count() : value(100)
{}
// Overload ++ when used as prefix
void operator ++ ( )
{
++value;
}
void display() {
cout << "Count: " << value << endl;
}
};
int main() {
Count count1;
• (Basic programs)
CONSTRUCTOR DESTRUCTOR
Declared as Declared as
classname( arguments if any ) ~ classname( no arguments )
{Constructor’s Body }. { }.
Constructor can either accept arguments or
While it can’t have any arguments.
not.
The constructor’s name is same as the Here, its name is also same as the class
class name. name preceded by the tiled (~) operator.
In a class, there can be multiple
There is always a single destructor.
constructors.
• There is a concept of copy constructor which is used to initialize
an object from another object.
• Conversely, there is no copy destructor concept.