0% found this document useful (0 votes)
236 views20 pages

Polymorphism

C++ polymorphism allows defining functions in a base class and redefining them in derived classes. There are two types of polymorphism in C++ - compile time polymorphism using function overloading and operator overloading, and runtime polymorphism using virtual functions. Virtual functions allow calling the correct version of a function based on the actual object type at runtime.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
236 views20 pages

Polymorphism

C++ polymorphism allows defining functions in a base class and redefining them in derived classes. There are two types of polymorphism in C++ - compile time polymorphism using function overloading and operator overloading, and runtime polymorphism using virtual functions. Virtual functions allow calling the correct version of a function based on the actual object type at runtime.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

C++ Polymorphism

The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is a
greek word. In object-oriented programming, we use 3 main concepts: inheritance, encapsulation,
and polymorphism.

There are two types of polymorphism in C++:


•Compile time polymorphism:

The overloaded functions are invoked by matching the type and number of
arguments. This information is available at the compile time and, therefore,
compiler selects the appropriate function at the compile time. It is achieved by
function overloading and operator overloading which is also known as static
binding or early binding. Now, let's consider the case where function name and
prototype is same.
Types of overloading in C++ are:
C++ Function Overloading

Function Overloading is defined as the process of having two or more function with the same name,
but different in parameters is known as function overloading in C++. In function overloading, the
function is redefined by using either different types of arguments or a different number of arguments.
It is only through these differences compiler can differentiate between the functions.
The advantage of Function overloading is that it increases the readability of the program because
you don't need to use different names for the same action.
1.#include <iostream>
2.using namespace std;
3.class Cal {
4. public:
5.static int add(int a,int b){
6. return a + b;
7. } C++ Function Overloading Example
8.static int add(int a, int b, int c)
9. {
10. return a + b + c;
11. }
12.};
13.int main(void) {
14. Cal C; // class object declaration.

15. cout<<C.add(10, 20)<<endl;


16. cout<<C.add(12, 20, 23);
17. return 0;
18.}
1.#include<iostream>
2.using namespace std;
3.int mul(int,int);
4.float mul(float,int);
5.
6.
7.int mul(int a,int b)
8.{
9. return a*b;
10.} Program of function overloading
11.float mul(double x, int y) with different types of arguments.
12.{
13. return x*y;
14.}
15.int main()
16.{
17. int r1 = mul(6,7);
18. float r2 = mul(0.2,3);
19. std::cout << "r1 is : " <<r1<< std::endl;
20. std::cout <<"r2 is : " <<r2<< std::endl;
21. return 0;
22.}
Function Overloading and Ambiguity

#include<iostream> #include<iostream>
using namespace std; using namespace std;
void test(float s,float t) void test(float s,float t)
{ {
cout << "Function with float called "; cout << "Function with float called ";
} }
void test(int s, int t) void test(int s, int t)
{ {
cout << "Function with int called "; cout << "Function with int called ";
} }
int main() int main()
{ {
test(3.5, 5.6); ERROR test(3.5f, 5.6f);
return 0; return 0;
} }
Function with Default Arguments

1.#include<iostream>
2.using namespace std; 1.#include<iostream>
3.void fun(int); 2.using namespace std;
4.void fun(int,int); 3.void fun(int,int);
5.void fun(int i) 4.void fun(int a,int b=9)
6.{ 5.{
7. std::cout << "Value of i is : " <<i<< std::endl; 6. std::cout << "Value of a is : " <<a<< std::endl;
8.}
9.void fun(int a,int b=9) 7. std::cout << "Value of b is : " <<b<< std::endl;
10.{
11. std::cout << "Value of a is : " <<a<< std::endl; 8.}
12. std::cout << "Value of b is : " <<b<< std::endl; 9.int main()
13.} 10.{
14.int main() 11. fun(12);
15.{ 12.
16. fun(12); ERROR 13. return 0;
17. 14.}
18. return 0;
19.}
C++ Operators Overloading

Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide


the special meaning to the user-defined data type. Operator overloading is used to overload or
redefines most of the operators available in C++. It is used to perform the operation on the user-
defined data type. For example, C++ provides the ability to add the variables of the user-defined data
type that is applied to the built-in data types.

Operator that cannot be overloaded are as follows:


•Scope operator (::)
•Sizeof
•member selector(.)
•member pointer selector(*)
•ternary operator(?:)
Rules for Operator Overloading

•Existing operators can only be overloaded, but the new operators cannot be
overloaded.
•The overloaded operator contains atleast one operand of the user-defined
data type.
•We cannot use friend function to overload certain operators. However, the
member function can be used to overload those operators.
•When unary operators are overloaded through a member function take no
explicit arguments, but, if they are overloaded by a friend function, takes one
argument.
•When binary operators are overloaded through a member function takes one
explicit argument, and if they are overloaded through a friend function takes
two explicit arguments.
1.#include <iostream>
2.using namespace std;
3.class Test
4.{
5. private:
6. int num;
7. public:
C++ Operators Overloading Example
8. Test(): num(8){}
9. void operator ++() {
10. num = num+2;
11. }
12. void Print() {
13. cout<<"The Count is: "<<num;
14. }
15.};
16.int main()
17.{
18. Test tt;
19. ++tt; // calling of a function "void operator ++()"
20. tt.Print();
21. return 0;
22.}
#include<iostream> C++ Operators Overloading Example
using namespace std;

class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0) {real = r; imag = i;}
int main()
// This is automatically called when '+' is used with {
// between two Complex objects Complex c1(10, 5), c2(2, 4);
Complex operator + (Complex const &obj) { Complex c3 = c1 + c2;
Complex res; c3.print();
res.real = real + obj.real; }
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << '\n'; }
};
#include <iostream>
using namespace std; C++ Operators Overloading Example

class ComplexNumber{
private:
int real;
int imaginary;
public: int main() {
ComplexNumber(int real, int imaginary){ ComplexNumber c1(3,5);
this->real = real; ComplexNumber c2(2,4);
this->imaginary = imaginary; ComplexNumber c3 = c1 + c2;
} c3.print();
void print(){ return 0;
cout<<real<<" + i"<<imaginary; }
}
ComplexNumber operator+ (ComplexNumber c2){
ComplexNumber c3(0,0);
c3.real = this->real+c2.real;
c3.imaginary = this->imaginary + c2.imaginary;
return c3;
}
};
https://www.mygreatlearning.com/blog/operator-overloading-in-cpp/

https://www.programiz.com/cpp-programming/operator-overloading

https://www.geeksforgeeks.org/operator-overloading-c/
C++ virtual function

•A C++ virtual function is a member function in the base class that you redefine
in a derived class. It is declared using the virtual keyword.
•It is used to tell the compiler to perform dynamic linkage or late binding on the
function.
•There is a necessity to use the single pointer to refer to all the objects of the
different classes. So, we create the pointer to the base class that refers to all the
derived objects. But, when base class pointer contains the address of the
derived class object, always executes the base class function. This issue can
only be resolved by using the 'virtual' function.
•A 'virtual' is a keyword preceding the normal declaration of a function.
•When the function is made virtual, C++ determines which function is to be
invoked at the runtime based on the type of the object pointed by the base class
pointer.
Rules of Virtual Function

•Virtual functions must be members of some class.


•Virtual functions cannot be static members.
•They are accessed through object pointers.
•They can be a friend of another class.
•A virtual function must be defined in the base class, even though it is not used.
•The prototypes of a virtual function of the base class and all the derived
classes must be identical. If the two functions with the same name but different
prototypes, C++ will consider them as the overloaded functions.
•We cannot have a virtual constructor, but we can have a virtual destructor
•Consider the situation when we don't use the virtual keyword.
1.#include <iostream>
2.using namespace std; 1.int main()
3.class A 2.{
4.{ 3. A *a;
5. int x=5; 4. B b;
6. public:
5. a = &b;
7. void display()
8. { 6. a->display();
9. std::cout << "Value of x is : " << x<<std::endl; 7. return 0;
10. } 8.}
11.};
12.class B: public A
C++ virtual function Example
13.{ Value of x is : 5
14. int y = 10;
15. public:
In the above example, * a is the base class pointer.
16. void display()
The pointer can only access the base class
17. {
members but not the members of the derived
18. std::cout << "Value of y is : " <<y<< std::endl;
class. Although C++ permits the base pointer to
19. }
point to any object derived from the base class, it
20.};
cannot directly access the members of the derived
class. Therefore, there is a need for virtual function
which allows the base pointer to access the
members of the derived class.
1.#include <iostream>
2.{
3. public:
4. virtual void display()
5. { 1.int main()
6. cout << "Base class is invoked"<<endl; 2.{
7. } 3. A* a; //pointer of base class
8.}; 4. B b; //object of derived class
9.class B:public A
5. a = &b;
10.{
11. public: 6. a->display(); //Late Binding occurs
12. void display() 7.}
13. {
14. cout << "Derived Class is invoked"<<endl;
15. }
16.};
Pure Virtual Function

•A virtual function is not used for performing any task. It only serves as a
placeholder.
•When the function has no definition, such function is known as "do-nothing"
function.
•The "do-nothing" function is known as a pure virtual function. A pure virtual
function is a function declared in the base class that has no definition relative to
the base class.
•A class containing the pure virtual function cannot be used to declare the
objects of its own, such classes are known as abstract base classes.
•The main objective of the base class is to provide the traits to the derived
classes and to create the base pointer used for achieving the runtime
polymorphism.
1.#include <iostream> 1.int main()
2.using namespace std; 2.{
3.class Base 3. Base *bptr;
4.{ 4. //Base b;
5. public: 5. Derived d;
6. virtual void show() = 0; 6. bptr = &d;
7.}; 7. bptr->show();
8.class Derived : public Base 8. return 0;
9.{ 9.}
10. public:
11. void show() Derived class is derived from the base class.
12. {
13. std::cout << "Derived class is deriv In the above example, the base class
contains the pure virtual function.
ed from the base class." << std::endl; Therefore, the base class is an abstract base
14. } class. We cannot create the object of the
15.}; base class.
Interfaces in C++ (Abstract Classes)
1.#include <iostream>
2.using namespace std;
3. class Shape
4.{ 1.int main( ) {
5. public: 2. Rectangle rec;
6. virtual void draw()=0; 3. Circle cir;
7.}; 4. rec.draw();
8. class Rectangle : Shape 5. cir.draw();
9.{ 6. return 0;
10. public: 7.}
11. void draw()
12. {
13. cout < <"drawing rectangle..." < <endl;
14. }
15.}; Abstract classes are the way to achieve abstraction in
16.class Circle : Shape C++. Abstraction in C++ is the process to hide the internal
17.{ details and showing functionality only.
18. public:
19. void draw()
20. {
21. cout <<"drawing circle..." < <endl;
22. }
23.};

You might also like