Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

riteshkandarics@gmail.

com iamriteshkandari 9259069231

UNIT III:

What is a Class?
A class is a blueprint for the object. A C++ class combines data and methods for manipulating
the data into one. Classes also determine the forms of objects. The data and methods
contained in a class are known as class members. A class is a user-defined data type. To
access the class members, we use an instance of the class.
A class be a prototype for a house. It shows the location and sizes of doors, windows, floors,
etc. From these descriptions, we can construct a house. The house becomes the object. It's
possible to create many houses from the prototype. Also, it's possible to create many objects
from a class.

In the above figure, we have a single house prototype. From this prototype, we have created
two houses with different features.

Create a Class
A class is defined in C++ using keyword class followed by the name of the class.
The body of the class is defined inside the curly brackets and terminated by a semicolon at
the end.

class className {
// some data (private)
// some functions (public)
};
riteshkandarics@gmail.com iamriteshkandari 9259069231

For example,
class Room {
public:
double length;
double breadth;
double height;
double calculateArea()
{
return length * breadth;
}
double calculateVolume()
{
return (length * breadth * height);
}
};
Here, we defined a class named Room.
The variables length, breadth, and height declared inside the class are known as data
members. And, the functions calculateArea() and calculateVolume() are known
as member functions of a class.

C++ Objects
When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, we need
to create objects.

Syntax to Define Object in C++


className objectVariableName;

We can create objects of Room class (defined in the above example) as follows:
// create objects
Room room1, room2;
}
Here, two objects room1 and room2 of the Room class are created in main ().
riteshkandarics@gmail.com iamriteshkandari 9259069231

C++ Access Data Members and Member Functions


We can access the data members and member functions of a class by using a . (dot) operator.
For example,
room2.calculateArea();
This will call the calculateArea() function inside the Room class for object room2.
Similarly, the data members can be accessed as:
room1.length = 5.5;
In this case, it initializes the length variable of room1 to 5.5.

Example 1: Object and Class in C++ Programming


// Program to illustrate the working of objects and class in C++ Programming
#include <iostream.h>
using namespace std;
class Room {
public:
double length;
double breadth;
double height;
double calculateArea()
{
return (length * breadth);
}
double calculateVolume()
{
return (length * breadth * height);
}
};
void main() {
Room room1; // create object of Room class
// assign values to data members
room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;
// calculate and display the area and volume of the room
cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;
}

Output
Area of Room = 1309
Volume of Room = 25132.8
riteshkandarics@gmail.com iamriteshkandari 9259069231

In this program, we have used the Room class and its object room1 to calculate the area and
volume of a room.
In main(), we assigned the values of length, breadth, and height with the code:
room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;
We then called the functions calculateArea() and calculateVolume() to perform the
necessary calculations.

Note: the use of the keyword public in the program. This means the members are public and
can be accessed anywhere from the program.
As per our needs, we can also create private members using the private keyword. The
private members of a class can only be accessed from within the class. For example,
class Test {
private:
int a;
void function1() { }
public:
int b;
void function2() { }
}
Here, a and function1() are private. Thus they cannot be accessed from outside the class.
On the other hand, b and function2() are accessible from everywhere in the program.

Example 2: Using public and private in C++ Class


// Program to illustrate the working of public and private in C++ Class
#include <iostream.h>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
// function to initialize private variables
void getData(double len, double brth, double hgt)
{
length = len;
breadth = brth;
riteshkandarics@gmail.com iamriteshkandari 9259069231
height = hgt;
}
double calculateArea()
{
return (length * breadth);
}
double calculateVolume()
{
return (length * breadth * height);
}
};
void main() {
// create object of Room class
Room room1;
// pass the values of private variables as arguments
room1.getData(42.5, 30.8, 19.2);
cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;
}

Output
Area of Room = 1309
Volume of Room = 25132.8
The above example is nearly identical to the first example, except that the class variables are
now private.
Since the variables are now private, we cannot access them directly from main(). Hence,
using the following code would be invalid:
// invalid code
obj.length = 42.5;
obj.breadth = 30.8;
obj.height = 19.2;
Instead, we use the public function getData() to initialize the private variables via the
function parameters double len, double brth, and double hgt.

Constructor
A constructor (have the same name as that of the class) is a member function which is
automatically used to initialize the object of the class type with legal initial value.
Special Characteristics of Constructor:
1) These are called automatically when the objects are created.
2) Return type (not even void) cannot be specify for constructor.
3) These cannot be static.
riteshkandarics@gmail.com iamriteshkandari 9259069231
For example,
class Wall {
public:
// create a constructor
Wall() {
// code
}
};
Here, the function Wall() is a constructor of the class Wall. Notice that the constructor
• has the same name as the class,

• does not have a return type, and

• is public

C++ Default Constructor


A constructor with no parameters is known as a default constructor. In the example
above, Wall() is a default constructor.

Example: C++ Default Constructor


// C++ program to demonstrate the use of default constructor
#include <iostream.h>
using namespace std;
// declare a class
class Wall {
private:
double length;
public:
// create a constructor
Wall() {
// initialize private variables
length = 5.5;
cout << "Creating a wall." << endl;
cout << "Length = " << length << endl;
}
};
void main() {
// create an object
Wall wall1;
}
riteshkandarics@gmail.com iamriteshkandari 9259069231

Output
Creating a Wall
Length = 5.5
Here, when the wall1 object is created, the Wall() constructor is called. This sets
the length variable of the object to 5.5.
Note: If we have not defined a constructor in our class, then the C++ compiler will
automatically create a default constructor with an empty code and no parameters.

C++ Parameterized Constructor


In C++, a constructor with parameters is known as a parameterized constructor. This
is the preferred method to initialize member data.

Example: C++ Parameterized Constructor


// C++ program to calculate the area of a wall
#include <iostream.h>
using namespace std;
// declare a class
class Wall {
private:
double length;
double height;
public:
// create parameterized constructor
Wall(double len, double hgt) {
// initialize private variables
length = len;
height = hgt;
}
double calculateArea() {
return length * height;
}
};
void main() {
// create object and initialize data members
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);
cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
cout << "Area of Wall 2: " << wall2.calculateArea() << endl;
riteshkandarics@gmail.com iamriteshkandari 9259069231
}
Output
Area of Wall 1: 90.3
Area of Wall 2: 53.55
Here, we have created a parameterized constructor Wall() that has 2
parameters: double len and double hgt. The values contained in these parameters are
used to initialize the member variables length and height.
When we create an object of the Wall class, we pass the values for the member
variables as arguments. The code for this is:
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);
With the member variables thus initialized, we can now calculate the area of the wall
with the calculateArea() function.

C++ Copy Constructor


The copy constructor in C++ is used to copy data of one object to another. A Copy
constructor is an overloaded constructor used to declare and initialize an object from
another object.
Copy Constructor is of two types:
o Default Copy constructor: The compiler defines the default copy constructor. If

the user defines no copy constructor, compiler supplies its constructor.


o User Defined constructor: The programmer defines the user-defined

constructor.
Syntax Of User-defined Copy Constructor:
Class_name(const class_name &old_object);

Example: C++ Copy Constructor


#include <iostream.h>
using namespace std; // declare a class
class Wall {
private:
double length;
double height;
public:
Wall(double len, double hgt) // parameterized constructor
{
// initialize private variables
riteshkandarics@gmail.com iamriteshkandari 9259069231
length = len;
height = hgt;
}
Wall(Wall &obj) // copy constructor with a Wall object as parameter
{
// initialize private variables
length = obj.length;
height = obj.height;
}
double calculateArea() {
return length * height;
}
};
void main() {
Wall wall1(10.5, 8.6); // create an object of Wall class
cout << "Area of Wall 1: " << wall1.calculateArea() << endl; // print area of wall1
// copy contents of wall1 to another object wall2
Wall wall2 = wall1;
// print area of wall2
cout << "Area of Wall 2: " << wall2.calculateArea() << endl;
}

Output
Area of Wall 1: 90.3
Area of Wall 2: 90.3
In this program, we have used a copy constructor to copy the contents of one object
of the Wall class to another. The code of the copy constructor is:
Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}
Notice that the parameter of this constructor has the address of an object of
the Wall class.
We then assign the values of the variables of the first object to the corresponding
variables of the second object. This is how the contents of the object are copied.
In main(), we then create two objects wall1 and wall2 and then copy the contents of
the first object to the second with the code
Wall wall2 = wall1;
riteshkandarics@gmail.com iamriteshkandari 9259069231
Note: A constructor is primarily used to initialize objects. They are also used to run a
default code when an object is created.

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 (~).
Let's see an example of constructor and destructor in C++ which is called
automatically.
#include <iostream.h>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
void main()
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
}
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked

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.
riteshkandarics@gmail.com iamriteshkandari 9259069231

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.

Static Class Member


A data member of a class can be static. The property of a static member variables are
similar to that of a static variable. A field which is declared as static is called static field.
A static member variable has certain special characteristics. These are:
1) It is initialized to 0. When the first object of its class is created. No other
initialization is permitted.
2) Only one copy of that member is created for the entire class and is shared by all the
objects of that class. No matter how many objects are created.
3) It can be used with in the class but its lifetime is the entire program.

For making a data member static we require:


1) Declare it within the class
2) Defining outside the class

class student
{
static int count; //declaration within the class
};
The static data member is defined outside the class as follows:
int student :: count; //defining outside the class

For Example:
#include <iostream.h>
using namespace std;
class item
{
static int count;
riteshkandarics@gmail.com iamriteshkandari 9259069231
int no;
public:
void getdata(int a)
{
no=a;
count++;
}
void getcount()
{
Cout<<”Value of count=”<<count;
}
};
int item :: count;
void main()
{
item a,b,c;
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout<<”After reading data<<endl”;
a.getcount();
b.getcount();
c.getcount();
}

Static Member Function


Like static member variable we can also have Static Member Function. A member
function is declared static has the following properties.
1) A static function can have access to only other static member function.
2) A static member function can be called using the class name.
Syntax: class_name :: function_name;

For Example:
#include <iostream.h>
using namespace std;
class student
riteshkandarics@gmail.com iamriteshkandari 9259069231
{
static int count;
int rollno,marks;
public:
void enter(int r,int n)
{
rollno=r;
marks=m;
count++;
}
void show()
{
cout<<”Roll No=”<<rollno;
cout<<”Marks=”<<marks;
}
static void showcount()
{
cout<<”Count=”<<count;
}
};
int student :: count;
void main()
{
student s1,s2,s3;
s1.enter(1001,99);
student :: showcount();
s2.enter(1002,88);
student :: showcount();
s3.enter(1003,77);
student :: showcount();
s1.show();
s2.show();
s3.show();
}

Friend Function
Friend functions of the class are granted access to private and protected members of
the class in C++. They are defined outside the class’ scope. Friend functions are not
riteshkandarics@gmail.com iamriteshkandari 9259069231
member functions of the class. The friend function is declared using the friend
keyword inside the body of the class.
Friend Function Syntax:
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
By using the keyword, the ‘friend’ compiler knows that the given function is a friend
function.
We declare friend function inside the body of a class, starting with the keyword friend
to access the data. We use them when we need to operate between two different
classes at the same time.

Characteristics:
1) It is not in the scope of the class of which it is a friend.
2) We cannot call a friend function using the object of the class.
3) It can be called like a normal function. i.e. without any object.
4) It accept object as its argument.

Example: Working of friend Function


// C++ program to demonstrate the working of friend function
#include <iostream.h>
using namespace std;
class sample {
int a,b;
public:
void setvalue()
{
a=25;
b=40;
}
Friend float mean(sample s);
};
// friend function definition
float mean(sample s)
{
return (s.a+s.b)/2.0;
riteshkandarics@gmail.com iamriteshkandari 9259069231
}
void main() {
sample x;
x.setvalue();
cout << "Average: " << mean(x);
}

Inline Function:
When the program executes the function call instruction the CPU stores the memory
address of the instruction following the function call, copies the arguments of the
function on the stack and finally transfers control to the specified function. The CPU
then executes the function code, stores the function return value in a predefined
memory location/register and returns control to the calling function. This can become
overhead if the execution time of function is less than the switching time from the
caller function to called function (callee). For functions that are large and/or perform
complex tasks, the overhead of the function call is usually insignificant compared to
the amount of time the function takes to run. However, for small, commonly-used
functions, the time needed to make the function call is often a lot more than the time
needed to actually execute the function’s code. This overhead occurs for small
functions because execution time of small function is less than the switching time.
C++ provides an inline functions to reduce the function call overhead.
Inline function is a function that is expanded in line when it is called. When the inline
function is called whole code of the inline function gets inserted or substituted at the
point of inline function call. This substitution is performed by the C++ compiler at
compile time. Inline function may increase efficiency if it is small.

The syntax for defining the function inline is:


inline return-type function-name(parameters)
{
// function code
}

Example:
#include <iostream.h>
using namespace std;
inline int cube(int s)
riteshkandarics@gmail.com iamriteshkandari 9259069231
{
return s*s*s;
}
void main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
}

//Output: The cube of 3 is: 27

Inline function doesn’t work for following situation:


1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return statement doesn’t exist
in function body.
5) If a function contains switch or goto statement.

Function Overloading
Overloading means to use the same thing for different purposes. In C++ overload
function refers to a function having one name and more than one distinct meaning.

Note: A function argument list is also known as function signature. For overloading a
function declare & define all the functions with the same name but different
signatures separately.

Example:
float volume (float,float); //prototype 1
float volume (float,int); //prototype 2
float volume (float,float,float); //prototype 3

Example:
#include <iostream.h>
using namespace std;
void cal(int,int);
riteshkandarics@gmail.com iamriteshkandari 9259069231
void cal(float,float);
void cal(int b,int h)
{
int area;
area=(b*h)/2;
cout<<”Area of triangle=”<<area;
}
void cal(float x,float y)
{
float result;
result=x*y;
cout<<”Area of rectangle=”<<result;
}
void main()
{
cal(10,20);
cal(2.5,6.5);
}

Inheritance
In C++, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such way, you can reuse, extend or
modify the attributes and behaviors which are defined in other class.
In C++, the class which inherits the members of another class is called derived class
and the class whose members are inherited is called base class. The derived class is
the specialized class for the base class.

Advantage of C++ Inheritance


Code reusability: Now you can reuse the members of your parent class. So, there is no
need to define the member again. So less code is required in the class.

Types of Inheritance
C++ supports five types of inheritance:
1) Single inheritance
riteshkandarics@gmail.com iamriteshkandari 9259069231
2) Multiple inheritance
3) Hierarchical inheritance
4) Multilevel inheritance
5) Hybrid inheritance

Derived Classes
A Derived class is defined as the class derived from the base class.
The Syntax of Derived class:
class derived_class_name :: visibility-mode base_class_name
{
// body of the derived class.
}
Where,
derived_class_name: It is the name of the derived class.
Visibility mode: The visibility mode specifies whether the features of the base class
are publicly inherited or privately inherited. It can be public or private.
base_class_name: It is the name of the base class.
• When the base class is privately inherited by the derived class, public members of
the base class becomes the private members of the derived class. Therefore, the
public members of the base class are not accessible by the objects of the derived
class only by the member functions of the derived class.
• When the base class is publicly inherited by the derived class, public members of
the base class also become the public members of the derived class. Therefore, the
public members of the base class are accessible by the objects of the derived class
as well as by the member functions of the base class.
Note:
• In C++, the default mode of visibility is private.
riteshkandarics@gmail.com iamriteshkandari 9259069231
• The private members of the base class are never inherited.

C++ Single Inheritance


Single inheritance is defined as the inheritance in which a derived class is inherited
from the only one base class.

Where 'A' is the base class, and 'B' is the derived class

For Example:
#include <iostream.h>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
void main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
}

How to make a Private Member Inheritable


The private member is not inheritable. If we modify the visibility mode by making it
public, but this takes away the advantage of data hiding.
C++ introduces a third visibility modifier, i.e., protected. The member which is
declared as protected will be accessible to all the member functions within the class
as well as the class immediately derived from it.

Visibility modes can be classified into three categories:


riteshkandarics@gmail.com iamriteshkandari 9259069231

• Public: When the member is declared as public, it is accessible to all the


functions of the program.
• Private: When the member is declared as private, it is accessible within the class
only.
• Protected: When the member is declared as protected, it is accessible within its
own class as well as the class immediately derived from it.

C++ Multiple Inheritance


Multiple inheritance is the process of deriving a new class that inherits the attributes
from two or more classes

Syntax of the Derived class:


class D : visibility B-1, visibility B-2, ?
{
// Body of the class;
}

Let's see a simple example of multiple inheritance.


#include <iostream.h>
using namespace std;
class A
{
protected:
int a;
public:
void get_a(int n)
{
a = n;
riteshkandarics@gmail.com iamriteshkandari 9259069231
}
};

class B
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
class C : public A,public B
{
public:
void display()
{
scout << "The value of a is : " <<a<< endl;
cout << "The value of b is : " <<b<< endl;
cout<<"Addition of a and b is : "<<a+b;
}
};
void main()
{
C c;
c.get_a(10);
c.get_b(20);
c.display();
}

Output:
The value of a is : 10
The value of b is : 20
Addition of a and b is : 30
In the above example, class 'C' inherits two base classes 'A' and 'B' in a public mode.

Ambiguity Resolution in Inheritance


riteshkandarics@gmail.com iamriteshkandari 9259069231
Ambiguity can be occurred in using the multiple inheritance when a function with the
same name occurs in more than one base class.
Let's understand this through an example
#include <iostream.h>
using namespace std;
class A
{
public:
void display()
{
cout << "Class A" << endl;
}
};
class B
{
public:
void display()
{
cout << "Class B" <<endl;
}
};
class C : public A, public B
{
void view()
{
display();
}
};
void main()
{
C c;
c.display();
}

Output:
error: reference to 'display' is ambiguous
display();

o The above issue can be resolved by using the class resolution operator with the
function. In the above example, the derived class code can be rewritten as:
riteshkandarics@gmail.com iamriteshkandari 9259069231
class C : public A, public B
{
void view()
{
A :: display(); // Calling the display() function of class A.
B :: display(); // Calling the display() function of class B.

}
};

C++ Multilevel Inheritance


Multilevel inheritance is a process of deriving a class from another derived class.

Multi Level Inheritance Example


When one class inherits another class which is further inherited by another class, it is
known as multi-level inheritance in C++. Inheritance is transitive so the last derived
class acquires all the members of all its base classes.

#include <iostream.h>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
riteshkandarics@gmail.com iamriteshkandari 9259069231
}
};
class BabyDog: public Dog
{
public:
void weep() {
cout<<"Weeping...";
}
};
void main() {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
}

Output:
Eating...
Barking...
Weeping...

C++ Hybrid Inheritance


Hybrid inheritance is a combination of more than one type of inheritance.

#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
riteshkandarics@gmail.com iamriteshkandari 9259069231
void get_a()
{
cout << "Enter the value of 'a' : " << endl;
cin>>a;
}
};
class B : public A
{
protected:
int b;
public:
void get_b()
{
cout << "Enter the value of 'b' : " << endl;
cin>>b;
}
};
class C
{
protected:
int c;
public:
void get_c()
{
cout << "Enter the value of c is : " << endl;
cin>>c;
}
};

class D : public B, public C


{
protected:
int d;
public:
void mul()
{
get_a();
get_b();
get_c();
cout << "Multiplication of a,b,c is : " <<a*b*c<< endl;
}
};
riteshkandarics@gmail.com iamriteshkandari 9259069231
void main()
{
D d;
d.mul();
}

Hierarchical Inheritance
Hierarchical inheritance is defined as the process of deriving more than one class from
a base class.

Operator Overloading
In C++, it can add special features to the functionality and behaviour of already existing
operators like athematic and other operations. The mechanism of giving special
meaning to an operator is known as operator overloading. For example, we can
overload an operator ‘+’ in a class like string to concatenate two strings by just using
+.

Syntax for Operator Overloading


To overload an operator, we use a special operator function. We define the function
inside the class or structure whose objects/variables we want the overloaded operator
to work with.
class className {
... .. ...
public
returnType operator symbol (arguments) {
... .. ...
}
... .. ...
};
Here,
riteshkandarics@gmail.com iamriteshkandari 9259069231
• returnType is the return type of the function.
• operator is a keyword.
• symbol is the operator we want to overload. Like: +, <, -, ++, etc.
• arguments is the arguments passed to the function.

Operator Overloading in Unary Operators


Unary operators operate on only one operand. The increment operator ++ and
decrement operator -- are examples of unary operators.
Example: ++ Operator (Unary Operator) Overloading
// Overload ++ when used as prefix
#include <iostream>
using namespace std;
class count {
private:
int value;
public:
count()
{
value=5;
}
// Overload ++ when used as prefix
void operator ++ () {
++value;
}
void display() {
cout << "Count: " << value << endl;
}
};
void main() {
count count1;
// Call the "void operator ++ ()" function
++count1;
count1.display();
}

Output
Count: 6
Here, when we use ++count1;, the void operator ++ () is called. This increases
the value attribute for the object count1 by 1.
riteshkandarics@gmail.com iamriteshkandari 9259069231
Example: ++ Operator (Unary Operator) Overloading
// Overload ++ when used as prefix and postfix
#include <iostream.h>
using namespace std;
class count {
private:
int value;
public:
// Constructor to initialize count to 5
count() {
value=5;
}
// Overload ++ when used as prefix
void operator ++ () {
++value;
}
// Overload ++ when used as postfix
void operator ++ (int) {
value++;
}
void display() {
cout << "Count: " << value << endl;
}
};
void main() {
count count1;
// Call the "void operator ++ (int)" function
count1++;
count1.display();
// Call the "void operator ++ ()" function
++count1;
count1.display();
}

Output
Count: 6
Count: 7

Operator Overloading in Binary Operators


Binary operators work on two operands. For example,
result = num + 9;
riteshkandarics@gmail.com iamriteshkandari 9259069231
Here, + is a binary operator that works on the operands num and 9.
When we overload the binary operator for user-defined types by using the code:
obj3 = obj1 + obj2;
The operator function is called using the obj1 object and obj2 is passed as an
argument to the function.

Example : C++ Binary Operator Overloading


// C++ program to overload the binary operator +
#include <iostream>
using namespace std;
class sum {
int a;
public:
void getdata(int x)
{
a=x;
}
void operator+(sum s1);
};
void sum::operator+(sum s1)
{
int c;
c=a+s1.a;
cout<<c;
}
void main()
{
sum s2,s3;
s2.getdata(10);
s3.getdata(20);
s2+s3;
}

Example: C++ Binary Operator Overloading with return

#include <iostream>
using namespace std;
class sum {
int a;
public:
riteshkandarics@gmail.com iamriteshkandari 9259069231
void getdata(int x)
{
a=x;
}
int operator+(sum s1);
};
int sum::operator+(sum s1)
{
int c;
c=a+s1.a;
return c;
}
void main()
{
sum s2,s3;
s2.getdata(10);
s3.getdata(20);
int c=s2+s3;
cout<<"value="<<c;
}

Example : C++ Binary Operator Overloading (add two complex number)

#include <iostream>
using namespace std;
class sum {
int a,b;
public:
void getdata(int x,int y)
{
a=x;
b=y;
}
sum operator+(sum s1);
void display();
};
sum sum::operator+(sum s1)
{
sum c;
c.a=a+s1.a;
c.b=b+s1.b;
return (c);
riteshkandarics@gmail.com iamriteshkandari 9259069231
}
void sum::display()
{
cout<<a<<" j"<<b;
}
void main()
{
sum s2,s3,s4;
s2.getdata(10,20);
s3.getdata(50,60);
s4=s2+s3;
s4.display();
}

Things to Remember in C++ Operator Overloading


1. Two operators = and & are already overloaded by default in C++. For example,
to copy objects of the same class, we can directly use the = operator. We do not
need to create an operator function.
2. Operator overloading cannot change the precedence and associativity of
operators. However, if we want to change the order of evaluation, parentheses
should be used.
3. There are 4 operators that cannot be overloaded in C++. They are:
a. :: (scope resolution)
b. . (member selection)
c. .* (member selection through pointer to function)
d. ?: (ternary operator)

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.
riteshkandarics@gmail.com iamriteshkandari 9259069231
#include <iostream.h>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
void main() {
Dog d;
d.eat();
}

Output:
Eating bread...

Early Binding / Static Binding / Compile Time Binding

#include <iostream.h>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
riteshkandarics@gmail.com iamriteshkandari 9259069231
};
void main() {
Animal *a;
Dog d;
a=&d;
a->eat(); // early binding
}

Output: Eating
In the above example the object is of Derived class still base class method is called.
This happen due to early binding.

Using Virtual Keyword

#include <iostream.h>
using namespace std;
class Animal {
public:
virtual void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
void main() {
Animal *a;
Dog d;
a=&d;
a->eat(); // late binding
}

Output: Eating bread


riteshkandarics@gmail.com iamriteshkandari 9259069231
Abstract Class
Abstract class is a class which contain atleast one pure virtual function in it. Abstract
class are used to provide an Interface for its SUB CLASS.
Characteristics
1) Abstract class cannot be instantiated.
2) Abstract class can have normal functions and variables along with the pure
virtual function.

Pure Virtual Function


Pure virtual functions are virtual functions with no definition. They start with virtual
keyword and end with =0.
Syntax: virtual void display=0; // they are also called abstract function.

#include <iostream.h>
using namespace std;
class Animal {
public:
virtual void eat()=0; //pure virtual function
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
void main() {
Animal *a;
Dog d;
a=&d;
a->eat(); // late binding
}

Output: Eating bread


riteshkandarics@gmail.com iamriteshkandari 9259069231
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.

this Pointer Example


#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 id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
void main() {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee

Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee


e1.display();
e2.display();
}

Output:
101 Sonoo 890000
102 Nakul 59000

You might also like