Object Oriented Programming 7 + 8
Object Oriented Programming 7 + 8
ORIENTED
PROGRAMMING
Lecture: 9 + 10
Instructor: Tayyba Khalid
Content:
• Compile-time Polymorphism
• Runtime Polymorphism
Compile-Time Polymorphism
■ Function Overloading
Function overloading is a feature of object-oriented programming where two
or more functions can have the same name but behave differently for
different parameters.
Explanation already discussed
Operator Overloading
■ C++ has the ability to provide the operators with a special meaning for
particular data type, this ability is known as operator overloading.
Two ways:
■ Prefix Unary Operator Overloading
■ Postfix Unary Operator Overloading
Prefix Unary Operator
Overloading
■ class Count {
■ int value;
■ public:
■ Count(){
■ Value = 0;
■ }
■ void operator++() { // Prefix
■ ++value;
■ }
■ void display() {
■ cout << "Value: " << value << endl;
■ }
■ };
Postfix Unary Operator
Overloading
■ class Count {
■ int value;
■ public:
■ Count() {
■ Value = 10;
■ }
■ void operator++(int) { // Postfix
■ value++;
■ }
■ void display() {
■ cout << "Value: " << value << endl;
■ }
■ };
Binary Operator Overloading
Binary operators are operators that work on two operands, like:
•+, -, *, /, ==, !=, etc.
•In the binary operator overloading function, there should be one argument to
be passed.
• It is the overloading of an operator operating on two operands.
■ // C++ Program to
Demonstrate
// This is automatically called when '+' is used with
■ // Operator Overloading // between two Complex objects
■ #include <iostream> Complex operator+(Complex const& obj)
{
■ using namespace std; Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
■ class Complex {
return res;
■ private: }
void print() { cout << real << " + i" << imag << '\n'; }
■ int real, imag;
};