0% found this document useful (0 votes)
2 views40 pages

c++ notes ut 2

The document provides an overview of Object-Oriented Programming (OOP) concepts in C++, including key principles such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It explains the advantages of OOP over procedural programming and details various types of constructors, destructors, and the use of the 'this' pointer in C++. Additionally, it includes examples of C++ classes and methods to illustrate these concepts in practice.

Uploaded by

prabhat.raghav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views40 pages

c++ notes ut 2

The document provides an overview of Object-Oriented Programming (OOP) concepts in C++, including key principles such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It explains the advantages of OOP over procedural programming and details various types of constructors, destructors, and the use of the 'this' pointer in C++. Additionally, it includes examples of C++ classes and methods to illustrate these concepts in practice.

Uploaded by

prabhat.raghav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

C++ OOPs Concepts

The major purpose of C++ programming is to introduce the concept of


object orientation to the C programming language.

Object Oriented Programming is a paradigm that provides many concepts


such as inheritance, data binding, polymorphism etc.

The programming paradigm where everything is represented as an object


is known as truly object-oriented programming language. Smalltalk is
considered as the first truly object-oriented programming language.

OOPs (Object Oriented Programming System)


Object means a real word entity such as pen, chair, table etc. Object-
Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies the software development
and maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object
Any entity that has state and behavior is known as an object. For
example: chair, pen, table, keyboard, bike etc. It can be physical and
logical.

Class
Collection of objects is called class. It is a logical entity.

Inheritance
When one object acquires all the properties and behaviours of
parent object i.e. known as inheritance. It provides code reusability. It is
used to achieve runtime polymorphism.

Polymorphism
When one task is performed by different ways i.e. known as
polymorphism. For example: to convince the customer differently, to draw
something e.g. shape or rectangle etc.

In C++, we use Function overloading and Function overriding to achieve


polymorphism.

Abstraction
Hiding internal details and showing functionality is known as
abstraction. For example: phone call, we don't know the internal
processing.

In C++, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit is
known as encapsulation. For example: capsule, it is wrapped with
different medicines.

Advantage of OOPs over Procedure-oriented


programming language
1. OOPs makes development and maintenance easier where as in
Procedure-oriented programming language it is not easy to manage
if code grows as project size grows.
2. OOPs provide data hiding whereas in Procedure-oriented
programming language a global data can be accessed from
anywhere.
3. OOPs provide ability to simulate real-world event much more
effectively. We can provide the solution of real word problem if we
are using the Object-Oriented Programming language.

C++ Object and Class


Since C++ is an object-oriented language, program is designed using
objects and classes in C++.

C++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile,
laptop etc.

In other words, object is an entity that has state and behavior. Here, state
means data and behavior means functionality.

Object is a runtime entity, it is created at runtime.

Object is an instance of a class. All the members of the class can be


accessed through object.

Let's see an example to create object of student class using s1 as the


reference variable.

1. Student s1; //creating an object of Student

In this example, Student is the type and s1 is the reference variable that
refers to the instance of Student class.

C++ Class
In C++, class is a group of similar objects. It is a template from which
objects are created. It can have fields, methods, constructors etc.

Let's see an example of C++ class that has three fields only.

1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. }

C++ Object and Class Example


Let's see an example of class that has two fields: id and name. It creates
instance of the class, initializes the object and prints the object value.

1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. };
8. int main() {
9. Student s1; //creating an object of Student
10. s1.id = 201;
11. s1.name = "Sonoo Jaiswal";
12. cout<<s1.id<<endl;
13. cout<<s1.name<<endl;
14. return 0;
15. }

Output:

201
Sonoo Jaiswal

C++ Class Example: Initialize and Display data


through method
Let's see another example of C++ class where we are initializing and
displaying object through method.
1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. void insert(int i, string n)
8. {
9. id = i;
10. name = n;
11. }
12. void display()
13. {
14. cout<<id<<" "<<name<<endl;
15. }
16. };
17. int main(void) {
18. Student s1; //creating an object of Student
19. Student s2; //creating an object of Student
20. s1.insert(201, "Sonoo");
21. s2.insert(202, "Nakul");
22. s1.display();
23. s2.display();
24. return 0;
25. }

Output:

201 Sonoo
202 Nakul

C++ Class Example: Store and Display Employee


Information
Let's see another example of C++ class where we are storing and
displaying employee information using method.

1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. float salary;
8. void insert(int i, string n, float s)
9. {
10. id = i;
11. name = n;
12. salary = s;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1; //creating an object of Employee
21. Employee e2; //creating an object of Employee
22. e1.insert(201, "Sonoo",990000);
23. e2.insert(202, "Nakul", 29000);
24. e1.display();
25. e2.display();
26. return 0;
27. }

Output:

201 Sonoo 990000


202 Nakul 29000

C++ Constructor
In C++, constructor is a special method which is invoked automatically at
the time of object creation. It is used to initialize the data members of new
object generally. The constructor in C++ has the same name as class or
structure.
There can be two types of constructors in C++.

o Default constructor
o Parameterized constructor

C++ Default Constructor


A constructor which has no argument is known as default constructor. It is
invoked at the time of creating object.

Let's see the simple example of C++ default Constructor.

1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Default Constructor Invoked"<<endl;
9. }
10. };
11. int main(void)
12. {
13. Employee e1; //creating an object of Employee
14. Employee e2;
15. return 0;
16. }

Output:

Default Constructor Invoked


Default Constructor Invoked

C++ Parameterized Constructor


A constructor which has parameters is called parameterized constructor. It
is used to provide different values to distinct objects.
Let's see the simple example of C++ Parameterized Constructor.

#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of
Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}

Output:

101 Sonoo 890000


102 Nakul 59000

C++ Copy Constructor


A Copy constructor is an overloaded constructor used to declare and
initialize an object from another object.

Syntax Of Copy Constructor:


1. Class_name(const class_name &old_object);

Consider the following situation:

1. class A
2. {
3. A(A &x) // copy constructor.
4. {
5. // copyconstructor.
6. }
7. }

In the above case, copy constructor can be called in the following


ways:

Let's see a simple example of the copy constructor.

// program of the copy constructor.

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. public:
6. int x;
7. A(int a) // parameterized constructor.
8. {
9. x=a;
10. }
11. A(A &i) // copy constructor
12. {
13. x = i.x;
14. }
15. };
16. int main()
17. {
18. A a1(20); // Calling the parameterized constructor.
19. A a2(a1); // Calling the copy constructor.
20. cout<<a2.x;
21. return 0;
22. }

Output:

20
When Copy Constructor is called
Copy Constructor is called in the following scenarios:

o When we initialize the object with another existing object of the


same class type. For example, Student s1 = s2, where Student is
the class.
o When the object of the same class type is passed by value as an
argument.
o When the function returns the object of the same class type by
value.

Dynamic Constructor in C++


When allocation of memory is done dynamically using dynamic memory
allocator new in a constructor, it is known as dynamic constructor. By using
this, we can dynamically initialize the objects.
Example 1:

 CPP14

#include <iostream>
using namespace std;

class geeks {
const char* p;

public:
// default constructor
geeks()
{

// allocating memory at run time


p = new char[6];
p = "geeks";
}

void display()
{
cout << p << endl;
}
};
int main()
{
geeks obj;
obj.display();
}

Output:

geeks
In this we point data member of type char which is allocated memory
dynamically by new operator and when we create dynamic memory within
the constructor of class this is known as dynamic constructor.
Example 2:

 CPP14

#include <iostream>
using namespace std;

class geeks {
int* p;

public:
// default constructor
geeks()
{

// allocating memory at run time


// and initializing
p = new int[3]{ 1, 2, 3 };

for (int i = 0; i < 3; i++) {


cout << p[i] << " ";
}

cout << endl;


}
};

int main()
{

// five objects will be created


// for each object
// default constructor would be called
// and memory will be allocated
// to array dynamically
geeks* ptr = new geeks[5];
}

Output:
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3

dynamically .

In this program we have created array of object dynamically. The first object
is ptr[0], second is ptr[1] and so on . For each object creation default
constructor is called and for each object memory is allocated to pointer type
variable by new operator.
Example 3:

 CPP14

#include <iostream>
using namespace std;

class geeks {
int* p;

public:
// default constructor
geeks()
{

// allocating memory at run time


p = new int;
*p = 0;
}

// parameterized constructor
geeks(int x)
{
p = new int;
*p = x;
}
void display()
{
cout << *p << endl;
}
};

int main()
{

// default constructor would be called


geeks obj1 = geeks();
obj1.display();

// parameterized constructor would be called


geeks obj2 = geeks(7);
obj2.display();
}

Output:
0
7

In this integer type pointer variable is declared in class which is assigned


memory dynamically when the constructor is called. When we create
object obj1, the default constructor is called and memory is assigned
dynamically to pointer type variable and initialized with value 0. And similarly
when obj2 is created parameterized constructor is called and memory is
assigned dynamically.

C++ Destructor
A destructor works opposite to constructor; it destructs the objects of
classes. It can be defined only once in a class. Like constructors, it is
invoked automatically.

A destructor is defined like constructor. It must have same name as class.


But it is prefixed with a tilde sign (~).
Note: C++ destructor cannot have parameters. Moreover, modifiers can't be
applied on destructors.

C++ Constructor and Destructor Example


Let's see an example of constructor and destructor in C++ which is called
automatically.

1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Constructor Invoked"<<endl;
9. }
10. ~Employee()
11. {
12. cout<<"Destructor Invoked"<<endl;
13. }
14.};
15. int main(void)
16.{
17. Employee e1; //creating an object of Employee
18. Employee e2; //creating an object of Employee
19. return 0;
20.}

Output:

Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked

C++ this Pointer


In C++ programming, this is a keyword that refers to the current instance
of the class. There can be 3 main usage of this keyword in C++.
o It can be used to pass current object as a parameter to
another method.
o It can be used to refer current class instance variable.
o It can be used to declare indexers.

C++ this Pointer Example


Let's see the example of this keyword in C++ that refers to the fields of
current class.

1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id; //data member (also instance variable)
6. string name; //data member(also instance variable)
7. float salary;
8. Employee(int id, string name, float salary)
9. {
10. this->id = id;
11. this->name = name;
12. this->salary = salary;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1 =Employee(101, "Sonoo", 890000); //creating
an object of Employee
21. Employee e2=Employee(102, "Nakul", 59000); //creating an
object of Employee
22. e1.display();
23. e2.display();
24. return 0;
25. }

Output:

101 Sonoo 890000


102 Nakul 59000

C++ static
In C++, static is a keyword or modifier that belongs to the type not
instance. So instance is not required to access the static members. In C+
+, static can be field, method, constructor, class, properties, operator and
event.

Advantage of C++ static keyword


Memory efficient: Now we don't need to create instance for accessing
the static members, so it saves memory. Moreover, it belongs to the type,
so it will not get memory each time when instance is created.

C++ Static Field


A field which is declared as static is called static field. Unlike instance field
which gets memory each time whenever you create object, there is only
one copy of static field created in the memory. It is shared to all the
objects.

It is used to refer the common property of all objects such as


rateOfInterest in case of Account, companyName in case of Employee etc.

C++ static field example


Let's see the simple example of static field in C++.

1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. int accno; //data member (also instance variable)
6. string name; //data member(also instance variable)
7. static float rateOfInterest;
8. Account(int accno, string name)
9. {
10. this->accno = accno;
11. this->name = name;
12. }
13. void display()
14. {
15. cout<<accno<< "<<name<< " "<<rateOfInterest<<
endl;
16. }
17. };
18. float Account::rateOfInterest=6.5;
19. int main(void) {
20. Account a1 =Account(201, "Sanjay"); //creating an object of
Employee
21. Account a2=Account(202, "Nakul"); //creating an object of E
mployee
22. a1.display();
23. a2.display();
24. return 0;
25. }

Output:

201 Sanjay 6.5


202 Nakul 6.5

C++ static field example: Counting Objects


Let's see another example of static keyword in C++ which counts the
objects.

1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. int accno; //data member (also instance variable)
6. string name;
7. static int count;
8. Account(int accno, string name)
9. {
10. this->accno = accno;
11. this->name = name;
12. count++;
13. }
14. void display()
15. {
16. cout<<accno<<" "<<name<<endl;
17. }
18. };
19. int Account::count=0;
20. int main(void) {
21. Account a1 =Account(201, "Sanjay"); //creating an object of
Account
22. Account a2=Account(202, "Nakul");
23. Account a3=Account(203, "Ranjana");
24. a1.display();
25. a2.display();
26. a3.display();
27. cout<<"Total Objects are: "<<Account::count;
28. return 0;
29. }

Output:

201 Sanjay
202 Nakul
203 Ranjana
Total Objects are: 3

C++ Structs
In C++, classes and structs are blueprints that are used to create the
instance of a class. Structs are used for lightweight objects such as
Rectangle, color, Point, etc.
Unlike class, structs in C++ are value type than reference type. It is useful
if you have data that is not intended to be modified after creation of
struct.

C++ Structure is a collection of different data types. It is similar to the


class that holds different types of data.

The Syntax Of Structure

1. struct structure_name
2. {
3. // member declarations.
4. }

In the above declaration, a structure is declared by preceding the struct


keyword followed by the identifier(structure name). Inside the curly
braces, we can declare the member variables of different types. Consider
the following situation:

1. struct Student
2. {
3. char name[20];
4. int id;
5. int age;
6. }

In the above case, Student is a structure contains three variables name,


id, and age. When the structure is declared, no memory is allocated.
When the variable of a structure is created, then the memory is allocated.
Let's understand this scenario.

How to create the instance of Structure?


Structure variable can be defined as:

Student s;

Here, s is a structure variable of type Student. When the structure


variable is created, the memory will be allocated. Student structure
contains one char variable and two integer variable. Therefore, the
memory for one char variable is 1 byte and two ints will be 2*4 = 8. The
total memory occupied by the s variable is 9 byte.

How to access the variable of Structure:


The variable of the structure can be accessed by simply using the
instance of the structure followed by the dot (.) operator and then the field
of the structure.

For example:

1. s.id = 4;

In the above statement, we are accessing the id field of the structure


Student by using the dot(.) operator and assigns the value 4 to the id
field.

C++ Struct Example


Let's see a simple example of struct Rectangle which has two data
members width and height.

1. #include <iostream>
2. using namespace std;
3. struct Rectangle
4. {
5. int width, height;
6.
7. };
8. int main(void) {
9. struct Rectangle rec;
10. rec.width=8;
11. rec.height=5;
12. cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<
endl;
13. return 0;
14. }

Output:

Area of Rectangle is: 40

C++ Struct Example: Using Constructor and Method


Let's see another example of struct where we are using the constructor to
initialize data and method to calculate the area of rectangle.

1. #include <iostream>
2. using namespace std;
3. struct Rectangle {
4. int width, height;
5. Rectangle(int w, int h)
6. {
7. width = w;
8. height = h;
9. }
10. void areaOfRectangle() {
11. cout<<"Area of Rectangle is: "<<(width*height); }
12. };
13. int main(void) {
14. struct Rectangle rec=Rectangle(4,6);
15. rec.areaOfRectangle();
16. return 0;
17. }

Output:

Area of Rectangle is: 24

Structure v/s Class

Structure Class

If access specifier is not declared If access specifier is not declared


explicitly, then by default access explicitly, then by default access
specifier will be public. specifier will be private.

Syntax of Structure: Syntax of Class:

struct structure_name class class_name


{ {
// body of the structure. // body of the class.
} }

The instance of the structure is known The instance of the class is known as
as "Structure variable". "Object of the class".

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.

Real Life Example Of Polymorphism


Let's consider a real-life example of polymorphism. A lady behaves like a
teacher in a classroom, mother or daughter in a home and customer in a
market. Here, a single person is behaving differently according to the
situations.

There are two types of polymorphism in C++:

o 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.

1. class A // base class declaration.


2. {
3. int a;
4. public:
5. void display()
6. {
7. cout<< "Class A ";
8. }
9. };
10. class B : public A // derived class declaration.
11. {
12. int b;

Compile time polymorphism Run time polymorphism

The function to be invoked is known at The function to be invoked is known at


the compile time. the run time.

It is also known as overloading, early It is also known as overriding, Dynamic


binding and static binding. binding and late binding.

Overloading is a compile time Overriding is a run time polymorphism


polymorphism where more than one where more than one method is having
method is having the same name but the same name, number of parameters
with the different number of and the type of the parameters.
parameters or the type of the
parameters.

It is achieved by function overloading It is achieved by virtual functions and


and operator overloading. pointers.

It provides fast execution as it is known It provides slow execution as it is known


at the compile time. at the run time.

It is less flexible as mainly all the things It is more flexible as all the things
execute at the compile time. execute at the run time.

13. public:
14. void display()
15. {
16. cout<<"Class B";
17. }
18. };

In the above case, the prototype of display() function is the same in both
the base and derived class. Therefore, the static binding cannot be
applied. It would be great if the appropriate function is selected at the run
time. This is known as run time polymorphism.

o Run time polymorphism: Run time polymorphism is achieved


when the object's method is invoked at the run time instead of
compile time. It is achieved by method overriding which is also
known as dynamic binding or late binding.

Differences b/w compile time and run time


polymorphism.
C++ Runtime Polymorphism Example
Let's see a simple example of run time polymorphism in C++.

// an example without the virtual keyword.

1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat(){
6. cout<<"Eating...";
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void eat()
13. { cout<<"Eating bread...";
14. }
15. };
16. int main(void) {
17. Dog d = Dog();
18. d.eat();
19. return 0;
20. }

Output:

Eating bread...

C++ Run time Polymorphism Example: By using two


derived class
Let's see another example of run time polymorphism in C++ where we
are having two derived classes.

// an example with virtual keyword.

1. #include <iostream>
2. using namespace std;
3. class Shape { // base class
4. public:
5. virtual void draw(){ // virtual function
6. cout<<"drawing..."<<endl;
7. }
8. };
9. class Rectangle: public Shape // inheriting Shape class.
10. {
11. public:
12. void draw()
13. {
14. cout<<"drawing rectangle..."<<endl;
15. }
16. };
17. class Circle: public Shape // inheriting Shape c
lass.
18.
19. {
20. public:
21. void draw()
22. {
23. cout<<"drawing circle..."<<endl;
24. }
25. };
26. int main(void) {
27. Shape *s; // base class pointer.
28. Shape sh; // base class object.
29. Rectangle rec;
30. Circle cir;
31. s=&sh;
32. s->draw();
33. s=&rec;
34. s->draw();
35. s=?
36. s->draw();
37. }

Output:

drawing...
drawing rectangle...
drawing circle...

Runtime Polymorphism with Data Members


Runtime Polymorphism can be achieved by data members in C++. Let's
see an example where we are accessing the field by reference variable
which refers to the instance of derived class.

1. #include <iostream>
2. using namespace std;
3. class Animal { // base class declaration.
4. public:
5. string color = "Black";
6. };
7. class Dog: public Animal // inheriting Animal class.
8. {
9. public:
10. string color = "Grey";
11. };
12. int main(void) {
13. Animal d= Dog();
14. cout<<d.color;
15. }

Output:

Black

C++ Overloading (Function and Operator)


If we create two or more members having the same name but different in
number or type of parameter, it is known as C++ overloading. In C++, we
can overload:

o methods,
o constructors, and
o indexed properties

It is because these members have parameters only.

Types of overloading in C++ are:


o Function overloading
o Operator overloading

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.

C++ Function Overloading Example


Let's see the simple example of function overloading where we are
changing number of arguments of add() method.

// program of function overloading when number of arguments vary.


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. }
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 decl
aration.
15. cout<<C.add(10, 20)<<endl;
16. cout<<C.add(12, 20, 23);
17. return 0;
18. }

Output:

30
55

Let's see the simple example when the type of the arguments vary.

// Program of function overloading with different types of arguments.

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. }
11. float mul(double x, int y)
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. }

Output:

r1 is : 42
r2 is : 0.6

Function Overloading and Ambiguity


When the compiler is unable to decide which function is to be invoked
among the overloaded function, this situation is known as function
overloading.

When the compiler shows the ambiguity error, the compiler does not run
the program.

Causes of Function Overloading:

o Type Conversion.
o Function with default arguments.
o Function with pass by reference.
o Type Conversion:

Let's see a simple example.

1. #include<iostream>
2. using namespace std;
3. void fun(int);
4. void fun(float);
5. void fun(int i)
6. {
7. std::cout << "Value of i is : " <<i<< std::endl;
8. }
9. void fun(float j)
10. {
11. std::cout << "Value of j is : " <<j<< std::endl;
12. }
13. int main()
14. {
15. fun(12);
16. fun(1.2);
17. return 0;
18. }

The above example shows an error "call of overloaded 'fun(double)' is


ambiguous". The fun(10) will call the first function. The fun(1.2) calls the
second function according to our prediction. But, this does not refer to any
function as in C++, all the floating point constants are treated as double
not as a float. If we replace float to double, the program works. Therefore,
this is a type conversion from float to double.

o Function with Default Arguments

Let's see a simple example.

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

The above example shows an error "call of overloaded 'fun(int)' is


ambiguous". The fun(int a, int b=9) can be called in two ways: first is by
calling the function with one argument, i.e., fun(12) and another way is
calling the function with two arguments, i.e., fun(4,5). The fun(int i)
function is invoked with one argument. Therefore, the compiler could not
be able to select among fun(int i) and fun(int a,int b=9).

o Function with pass by reference

Let's see a simple example.

1. #include <iostream>
2. using namespace std;
3. void fun(int);
4. void fun(int &);
5. int main()
6. {
7. int a=10;
8. fun(a); // error, which f()?
9. return 0;
10. }
11. void fun(int x)
12. {
13. std::cout << "Value of x is : " <<x<< std::endl;
14. }
15. void fun(int &b)
16. {
17. std::cout << "Value of b is : " <<b<< std::endl;
18. }

The above example shows an error "call of overloaded 'fun(int&)' is


ambiguous". The first function takes one integer argument and the
second function takes a reference parameter as an argument. In this case,
the compiler does not know which function is needed by the user as there
is no syntactical difference between the fun(int) and fun(int &).

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.

The advantage of Operators overloading is to perform different operations


on the same operand.

Operator that cannot be overloaded are as follows:

o Scope operator (::)


o Sizeof
o member selector(.)
o member pointer selector(*)
o ternary operator(?:)

Syntax of Operator Overloading

1. return_type class_name : : operator op(argument_list)


2. {
3. // body of the function.
4. }

Where the return type is the type of value returned by the function.

class_name is the name of the class.

operator op is an operator function where op is the operator being


overloaded, and the operator is the keyword.
Rules for Operator Overloading

o Existing operators can only be overloaded, but the new operators


cannot be overloaded.
o The overloaded operator contains atleast one operand of the user-
defined data type.
o We cannot use friend function to overload certain operators.
However, the member function can be used to overload those
operators.
o 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.
o 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.

C++ Operators Overloading Example


Let's see the simple example of operator overloading in C++. In this
example, void operator ++ () operator function is defined (inside Test
class).

// program to overload the unary operator ++.

1. #include <iostream>
2. using namespace std;
3. class Test
4. {
5. private:
6. int num;
7. public:
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. }

Output:

The Count is: 10

Let's see a simple example of overloading the binary operators.

// program to overload the binary operators.

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5.
6. int x;
7. public:
8. A(){}
9. A(int i)
10. {
11. x=i;
12. }
13. void operator+(A);
14. void display();
15. };
16.
17. void A :: operator+(A a)
18. {
19.
20. int m = x+a.x;
21. cout<<"The result of the addition of two objects is : "<<m;
22.
23. }
24. int main()
25. {
26. A a1(5);
27. A a2(4);
28. a1+a2;
29. return 0;
30. }

Output:

The result of the addition of two objects is : 9

C++ Function Overriding


If derived class defines same function as defined in its base class, it is
known as function overriding in C++. It is used to achieve runtime
polymorphism. It enables you to provide specific implementation of the
function which is already provided by its base class.

C++ Function Overriding Example


Let's see a simple example of Function overriding in C++. In this example,
we are overriding the eat() function.

1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat(){
6. cout<<"Eating...";
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void eat()
13. {
14. cout<<"Eating bread...";
15. }
16. };
17. int main(void) {
18. Dog d = Dog();
19. d.eat();
20. return 0;
21. }

Output:

Eating bread...

C++ virtual function


o 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.
o It is used to tell the compiler to perform dynamic linkage or late
binding on the function.
o 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.
o A 'virtual' is a keyword preceding the normal declaration of a
function.
o 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.

Late binding or Dynamic linkage


In late binding function call is resolved during runtime. Therefore compiler
determines the type of object at runtime, and then binds the function call.
Rules of Virtual Function

o Virtual functions must be members of some class.


o Virtual functions cannot be static members.
o They are accessed through object pointers.
o They can be a friend of another class.
o A virtual function must be defined in the base class, even though it
is not used.
o 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.
o We cannot have a virtual constructor, but we can have a virtual
destructor
o Consider the situation when we don't use the virtual keyword.

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. int x=5;
6. public:
7. void display()
8. {
9. std::cout << "Value of x is : " << x<<std::endl;
10. }
11. };
12. class B: public A
13. {
14. int y = 10;
15. public:
16. void display()
17. {
18. std::cout << "Value of y is : " <<y<< std::endl;
19. }
20. };
21. int main()
22. {
23. A *a;
24. B b;
25. a = &b;
26. a->display();
27. return 0;
28. }

Output:

Value of x is : 5

In the above example, * a is the base class pointer. The pointer can only
access the base class members but not the members of the derived class.
Although C++ permits the base pointer to point to any object derived
from the base class, it 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.

C++ virtual function Example


Let's see the simple example of C++ virtual function used to invoked the
derived class in a program.

1. #include <iostream>
2. {
3. public:
4. virtual void display()
5. {
6. cout << "Base class is invoked"<<endl;
7. }
8. };
9. class B:public A
10. {
11. public:
12. void display()
13. {
14. cout << "Derived Class is invoked"<<endl;
15. }
16. };
17. int main()
18. {
19. A* a; //pointer of base class
20. B b; //object of derived class
21. a = &b;
22. a->display(); //Late Binding occurs
23. }

Output:

Derived Class is invoked

Pure Virtual Function


o A virtual function is not used for performing any task. It only serves
as a placeholder.
o When the function has no definition, such function is known as "do-
nothing" function.
o 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.
o 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.
o 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.

Pure virtual function can be defined as:

1. virtual void display() = 0;

Let's see a simple example:

1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. virtual void show() = 0;
7. };
8. class Derived : public Base
9. {
10. public:
11. void show()
12. {
13. std::cout << "Derived class is derived from the base clas
s." << std::endl;
14. }
15. };
16. int main()
17. {
18. Base *bptr;
19. //Base b;
20. Derived d;
21. bptr = &d;
22. bptr->show();
23. return 0;
24. }

Output:

Derived class is derived from the base class.

In the above example, the base class contains the pure virtual function.
Therefore, the base class is an abstract base class. We cannot create the
object of the base class.

You might also like