0% found this document useful (0 votes)
22 views

Unit 5 Notes

Uploaded by

rpal46419
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Unit 5 Notes

Uploaded by

rpal46419
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 122

lOMoARcPSD|41983625

Unit-5 notes

Object Oriented Programming (Dr. A.P.J. Abdul Kalam Technical University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by ABHINAV PAL ([email protected])
lOMoARcPSD|41983625

Objects and Classes : Basics of object and class in C++, Private and public members,
static
data and function members, constructors and their types, destructors, operator
overloading,
type conversion. Inheritance : Concept of Inheritance, types of inheritance: single,
multiple,
multilevel, hierarchical, hybrid, protected members, overriding, virtual base class
Polymorphism : Pointers in C++, Pointes and Objects, this pointer, virtual and pure
virtual
functions, Implementing polymorphism

C++ Classes and Objects


Class in C++ is the building block that leads to Object-Oriented programming. It is a user-
defined data type, which holds its own data members and member functions, which can be
accessed and used by creating an instance of that class. A C++ class is like a blueprint for an
object. For Example: Consider the Class of Cars. There may be many cars with different
names and brands but all of them will share some common properties like all of them will
have 4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed
limits, and mileage are their properties.

 A Class is a user-defined data type that has data members and member functions.
 Data members are the data variables and member functions are the functions used to
manipulate these variables together, these data members and member functions define
the properties and behavior of the objects in a Class.
 In the above example of class Car, the data member will be speed limit, mileage, etc,
and member functions can be applying brakes, increasing speed, etc.

An Object is an instance of a Class. When a class is defined, no memory is allocated but


when it is instantiated (i.e. an object is created) memory is allocated.

Defining Class and Declaring Objects


A class is defined in C++ using the 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.

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Declaring 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, you need to
create objects.

Syntax
ClassName ObjectName;

Accessing data members and member functions: The data members and member functions
of the class can be accessed using the dot(‘.’) operator with the object. For example, if the
name of the object is obj and you want to access the member function with the name
printName() then you will have to write obj.printName().

Accessing Data Members


The public data members are also accessed in the same way given however the private data
members are not allowed to be accessed directly by the object. Accessing a data member
depends solely on the access control of that data member. This access control is given by
Access modifiers in C++. There are three access modifiers: public, private, and protected.

// C++ program to demonstrate accessing of data members


#include <bits/stdc++.h>
using namespace std;
class Geeks {
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
void printname() { cout << "Geekname is:" << geekname; }
};
int main()
{

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// Declare an object of class geeks


Geeks obj1;
// accessing data member
obj1.geekname = "Abhi";
// accessing member function
obj1.printname();
return 0;
}
Output
Geekname is:Abhi

Member Functions in Classes


There are 2 ways to define a member function:

 Inside class definition


 Outside class definition

To define a member function outside the class definition we have to use the scope
resolution:: operator along with the class name and function name.

// C++ program to demonstrate function


// declaration outside class

#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
string geekname;
int id;

// printname is not defined inside class definition


void printname();

// printid is defined inside class definition


void printid()
{
cout <<"Geek id is: "<<id;
}
};

// Definition of printname using scope resolution operator ::


void Geeks::printname()
{
cout <<"Geekname is: "<<geekname;
}
int main() {

Geeks obj1;
obj1.geekname = "xyz";
obj1.id=15;

// call printname()
obj1.printname();
cout << endl;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// call printid()
obj1.printid();
return 0;
}
Output
Geekname is: xyz
Geek id is: 15

Note that all the member functions defined inside the class definition are by default inline,
but you can also make any non-class function inline by using the keyword inline with them.
Inline functions are actual functions, which are copied everywhere during compilation, like
pre-processor macro, so the overhead of function calls is reduced.

Note: Declaring a friend function is a way to give private access to a non-member function.

Constructors
Constructors are special class members which are called by the compiler every time an object
of that class is instantiated. Constructors have the same name as the class and may be defined
inside or outside the class definition. There are 3 types of constructors:

 Default Constructors
 Parameterized Constructors
 Copy Constructors

// C++ program to demonstrate constructors


#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
int id;

//Default Constructor
Geeks()
{
cout << "Default Constructor called" << endl;
id=-1;
}

//Parameterized Constructor
Geeks(int x)
{
cout <<"Parameterized Constructor called "<< endl;
id=x;
}
};
int main() {

// obj1 will call Default Constructor


Geeks obj1;
cout <<"Geek id is: "<<obj1.id << endl;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// obj2 will call Parameterized Constructor


Geeks obj2(21);
cout <<"Geek id is: " <<obj2.id << endl;
return 0;
}
Output
Default Constructor called
Geek id is: -1
Parameterized Constructor called
Geek id is: 21

A Copy Constructor creates a new object, which is an exact copy of the existing object. The
compiler provides a default Copy Constructor to all the classes.

Syntax:

class-name (class-name &){}

Destructors
Destructor is another special member function that is called by the compiler when the scope
of the object ends.

// C++ program to explain destructors


#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
int id;

//Definition for Destructor


~Geeks()
{
cout << "Destructor called for id: " << id <<endl;
}
};

int main()
{
Geeks obj1;
obj1.id=7;
int i = 0;
while ( i < 5 )
{
Geeks obj2;
obj2.id=i;
i++;
} // Scope for obj2 ends here

return 0;
} // Scope for obj1 ends here
Output
Destructor called for id: 0
Destructor called for id: 1
Destructor called for id: 2
Destructor called for id: 3

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Destructor called for id: 4


Destructor called for id: 7

Interesting Fact (Rare Known Concept)


Why do we give semicolons at the end of class?

Many people might say that it’s a basic syntax and we should give a semicolon at the end of
the class as its rule defines in cpp. But the main reason why semi-colons are there at the end
of the class is compiler checks if the user is trying to create an instance of the class at the end
of it.

Yes just like structure and union, we can also create the instance of a class at the end just
before the semicolon. As a result, once execution reaches at that line, it creates a class and
allocates memory to your instance.

#include <iostream>
using namespace std;

class Demo{
int a, b;
public:
Demo() // default constructor
{
cout << "Default Constructor" << endl;
}
Demo(int a, int b):a(a),b(b) //parameterised constructor
{
cout << "parameterized constructor -values" << a << " "<< b <<
endl;
}

}instance;

int main() {

return 0;
}
Output
Default Constructor

We can see that we have created a class instance of Demo with the name “instance”, as a
result, the output we can see is Default Constructor is called.

Similarly, we can also call the parameterized constructor just by passing values here

#include <iostream>
using namespace std;

class Demo{
public:
int a, b;
Demo()

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

{
cout << "Default Constructor" << endl;
}
Demo(int a, int b):a(a),b(b)
{
cout << "parameterized Constructor values-" << a << " "<< b <<
endl;
}

}instance(100,200);

int main() {

return 0;
}
Output
parameterized Constructor values-100 200

So by creating an instance just before the semicolon, we can create the Instance of class.

Access Modifiers in C++


Access modifiers are used to implement an important aspect of Object-Oriented
Programming known as Data Hiding. Consider a real-life example:
The Research and Analysis Wing (R&AW), having 10 core members, has come into
possession of sensitive confidential information regarding national security. Now we can
correlate these core members to data members or member functions of a class, which in turn
can be correlated to the R&A Wing. These 10 members can directly access the confidential
information from their wing (the class), but anyone apart from these 10 members can’t access
this information directly, i.e., outside functions other than those prevalent in the class itself
can’t access the information (that is not entitled to them) without having either assigned
privileges (such as those possessed by a friend class or an inherited class, as will be seen in
this article ahead) or access to one of these 10 members who is allowed direct access to the
confidential information (similar to how private members of a class can be accessed in the
outside world through public member functions of the class that have direct access to private
members). This is what data hiding is in practice.
Access Modifiers or Access Specifiers in a class are used to assign the accessibility to the
class members, i.e., they set some restrictions on the class members so that they can’t be
directly accessed by the outside functions.
There are 3 types of access modifiers available in C++:

1. Public
2. Private
3. Protected

Note: If we do not specify any access modifiers for the members inside the class, then by
default the access modifier for the members will be Private.

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Let us now look at each one of these access modifiers in detail:


1. Public: All the class members declared under the public specifier will be available to
everyone. The data members and member functions declared as public can be accessed by
other classes and functions too. The public members of a class can be accessed from
anywhere in the program using the direct member access operator (.) with the object of that
class.

Example:

// C++ program to demonstrate public

// access modifier

#include<iostream>

using namespace std;

// class definition

class Circle

public:

double radius;

double compute_area()

return 3.14*radius*radius;

};

// main function

int main()

Circle obj;

// accessing public datamember outside class

obj.radius = 5.5;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

cout << "Radius is: " << obj.radius << "\n";

cout << "Area is: " << obj.compute_area();

return 0;

Output:

Radius is: 5.5


Area is: 94.985

In the above program, the data member radius is declared as public so it could be accessed
outside the class and thus was allowed access from inside main().
2. Private: The class members declared as private can be accessed only by the member
functions inside the class. They are not allowed to be accessed directly by any object or
function outside the class. Only the member functions or the friend functions are allowed to
access the private data members of the class.

Example:

// C++ program to demonstrate private

// access modifier

#include<iostream>

using namespace std;

class Circle

// private data member

private:

double radius;

// public member function

public:

double compute_area()

{ // member function can access private

// data member radius

return 3.14*radius*radius;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

};

// main function

int main()

// creating object of the class

Circle obj;

// trying to access private data member

// directly outside the class

obj.radius = 1.5;

cout << "Area is:" << obj.compute_area();

return 0;

Output:

In function 'int main()':


11:16: error: 'double Circle::radius' is private
double radius;
^
31:9: error: within this context
obj.radius = 1.5;
^

The output of the above program is a compile time error because we are not allowed to access
the private data members of a class directly from outside the class. Yet an access to obj.radius
is attempted, but radius being a private data member, we obtained the above compilation
error.

However, we can access the private data members of a class indirectly using the public
member functions of the class.

Example:

// C++ program to demonstrate private

// access modifier

#include<iostream>

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

using namespace std;

class Circle

// private data member

private:

double radius;

// public member function

public:

void compute_area(double r)

{ // member function can access private

// data member radius

radius = r;

double area = 3.14*radius*radius;

cout << "Radius is: " << radius << endl;

cout << "Area is: " << area;

};

// main function

int main()

// creating object of the class

Circle obj;

// trying to access private data member

// directly outside the class

obj.compute_area(1.5);

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

return 0;

Output:

Radius is: 1.5


Area is: 7.065

3. Protected: The protected access modifier is similar to the private access modifier in the
sense that it can’t be accessed outside of its class unless with the help of a friend class. The
difference is that the class members declared as Protected can be accessed by any subclass
(derived class) of that class as well.

Note: This access through inheritance can alter the access modifier of the elements of base
class in derived class depending on the mode of Inheritance.

Example:

// C++ program to demonstrate

// protected access modifier

#include <bits/stdc++.h>

using namespace std;

// base class

class Parent

// protected data members

protected:

int id_protected;

};

// sub class or derived class from public base class

class Child : public Parent

public:

void setId(int id)

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// Child class is able to access the inherited

// protected data members of base class

id_protected = id;

void displayId()

cout << "id_protected is: " << id_protected << endl;

};

// main function

int main() {

Child obj1;

// member function of the derived class can

// access the protected data members of the base class

obj1.setId(81);

obj1.displayId();

return 0;

Output:

id_protected is: 81

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time of object
creation. It is used to initialize the data members of new objects generally. The constructor in
C++ has the same name as the class or structure. It constructs the values i.e. provides data for
the object which is why it is known as a constructor.

 Constructor is a member func琀椀on of a class, whose name is the same as the class name.

 Constructor is a special type of member func琀椀on that is used to ini琀椀alize the data members
for an object of a class automa琀椀cally when an object of the same class is created.

 Constructor is invoked at the 琀椀me of object crea琀椀on. It constructs the values i.e. provides
data for the object that is why it is known as a constructor.

 Constructors do not return value, hence they do not have a return type.

 A constructor gets called automa琀椀cally when we create the object of the class.

 Constructors can be overloaded.

 A constructor can not be declared virtual.

Syntax of Constructors in C++


The prototype of the constructor looks like this:

<class-name> (list-of-parameters);

The constructor can be defined inside the class declaration or outside the class declaration

Syntax for Defining the Constructor Within the Class


<class-name> (list-of-parameters)
{
// constructor definition
}

Syntax for Defining the Constructor Outside the Class


<class-name>: :<class-name>(list-of-parameters)
{
// constructor definition
}

Examples of Constructors in C++


The below examples demonstrate how to declare constructors for a class in C++:

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Example 1: Defining the Constructor Within the Class


// defining the constructor within the class

#include <iostream>

using namespace std;

class student {

int rno;

char name[50];

double fee;

public:

// constructor

student()

cout << "Enter the RollNo:";

cin >> rno;

cout << "Enter the Name:";

cin >> name;

cout << "Enter the Fee:";

cin >> fee;

void display()

cout << endl << rno << "\t" << name << "\t" << fee;

};

int main()

student s; // constructor gets called automatically when

// we create the object of the class

s.display();

return 0;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Output

Enter the RollNo:121


Enter the Name:Geeks
Enter the Fee:5000
121 Geeks 5000

Example 2: Defining the Constructor Outside the Class


// defining the constructor outside the class

#include <iostream>

using namespace std;

class student {

int rno;

char name[50];

double fee;

public:

// constructor declaration only

student();

void display();

};

// outside definition of constructor

student::student()

cout << "Enter the RollNo:";

cin >> rno;

cout << "Enter the Name:";

cin >> name;

cout << "Enter the Fee:";

cin >> fee;

void student::display()

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

cout << endl << rno << "\t" << name << "\t" << fee;

// driver code

int main()

student s;

s.display();

return 0;

Output

Enter the RollNo:11


Enter the Name:Aman
Enter the Fee:10111
11 Aman 10111

Note: We can make the constructor defined outside the class as inline to make it equivalent
to the in class definition. But note that inline is not an instruction to the compiler, it is only
the request which compiler may or may not implement depending on the circumtances.

Characteristics of Constructors in C++


The following are some main characteristics of the constructors in C++:

 The name of the constructor is the same as its class name.

 Constructors are mostly declared in the public sec琀椀on of the class though they can be
declared in the private sec琀椀on of the class.

 Constructors do not return values; hence they do not have a return type.

 A constructor gets called automa琀椀cally when we create the object of the class.

 Constructors can be overloaded.

 A constructor can not be declared virtual.

 A constructor cannot be inherited.

 The addresses of the Constructor cannot be referred to.

 The constructor makes implicit calls to new and delete operators during memory alloca琀椀on.

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Types of Constructor in C++


Constructors can be classified based on in which situations they are being used. There are 4
types of constructors in C++:

1. Default Constructor

2. Parameterized Constructor

3. Copy Constructor

4. Move Constructor

Let us understand the types of constructors in C++ by taking a real-world example. Suppose
you went to a shop to buy a marker. When you want to buy a marker, what are the options?
The first one you go to a shop and say give me a marker. So just saying give me a marker
means that you did not set which brand name and which color, you didn’t mention anything
just say you want a marker. So when we said just I want a marker whatever the frequently
sold marker is there in the market or his shop he will simply hand over that. And this is what
a default constructor is!

The second method is you go to a shop and say I want a marker red in color and XYZ brand.
So you are mentioning this and he will give you that marker. So in this case you have given
the parameters. And this is what a parameterized constructor is!

Then the third one you go to a shop and say I want a marker like this(a physical marker on
your hand). So the shopkeeper will see that marker. Okay, and he will give a new marker for
you. So copy of that marker. And that’s what a copy constructor is!

Now, assume that you don’t to buy a new marker but instead take ownership of your friend’s
marker. It means taking ownership of already present resources instead of getting a new one.
That’s what a move constructor is!

1. Default Constructor in C++


A default constructor is a constructor that doesn’t take any argument. It has no parameters. It
is also called a zero-argument constructor.

Syntax of Default Constructor


className() {
// body_of_constructor
}

Examples of Default Constructor

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

The below examples demonstrate how to use the default constructors in C++.

Example 1:

// C++ program to illustrate the concept of default

// constructors

#include <iostream>

using namespace std;

class construct {

public:

int a, b;

// Default Constructor

construct()

a = 10;

b = 20;

};

int main()

// Default constructor called automatically

// when the object is created

construct c;

cout << "a: " << c.a << endl << "b: " << c.b;

return 1;

Output
a: 10
b: 20

Note: Even if we do not define any constructor explicitly, the compiler will automatically
provide a default constructor implicitly.

Example 2:

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// C++ program to demonstrate the implicit default

// constructor

#include <iostream>

using namespace std;

// class

class student {

int rno;

char name[50];

double fee;

public:

};

int main()

// creating object without any parameters

student s;

return 0;

Output

(no output)

As we can see, we are able the object of class student is created without passing any
argument even when we haven’t defined any explicit default constructor for it.

2. Parameterized Constructor in C++


Parameterized Constructors make it possible to pass arguments to constructors. Typically,
these arguments help initialize an object when it is created. To create a parameterized
constructor, simply add parameters to it the way you would to any other function. When you
define the constructor’s body, use the parameters to initialize the object.

Syntax of Parameterized Constructor


className (parameters...) {
// body
}

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Examples of Parameterized Constructor

The below examples demonstrate how to use the parameterized constructors in C++.

Example 1: Defining Parameterized Constructor Inside the Class.

// CPP program to illustrate parameterized constructors

#include <iostream>

using namespace std;

class Point {

private:

int x, y;

public:

// Parameterized Constructor

Point(int x1, int y1)

x = x1;

y = y1;

int getX() { return x; }

int getY() { return y; }

};

int main()

// Constructor called

Point p1(10, 15);

// Access values assigned by constructor

cout << "p1.x = " << p1.getX()

<< ", p1.y = " << p1.getY();

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

return 0;

Output
p1.x = 10, p1.y = 15

Example 2: Defining Parameterized Constructor Outside the Class.

// C++ Program to illustrate how to define the parameterized

// constructor outside the class

#include <iostream>

#include <string.h>

using namespace std;

// class definition

class student {

int rno;

char name[50];

double fee;

public:

student(int, char[], double);

void display();

};

// parameterized constructor outside class

student::student(int no, char n[], double f)

rno = no;

strcpy(name, n);

fee = f;

void student::display()

cout << endl << rno << "\t" << name << "\t" << fee;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// driver code

int main()

student s(1001, "Ram", 10000);

s.display();

return 0;

Output
1001 Ram 10000

When an object is declared in a parameterized constructor, the initial values have to be passed
as arguments to the constructor function. The normal way of object declaration may not
work. The parameterized constructors can be called explicitly or implicitly:

Example e = Example(0, 50); // Explicit call


Example e(0, 50); // Implicit call

When the parameterized constructor is defined and no default constructor is defined


explicitly, the compiler will not implicitly create the default constructor and hence create a
simple object as:

Student s;

will flash an error.

Example 3:

// C++ Program to illustrate the error caused be not

// defining the explicit defualt constructor after

// parameterized constructor

#include <iostream>

#include <string.h>

using namespace std;

// class definition

class student {

int rno;

char name[50];

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

double fee;

public:

student(int no, char n[], double f)

rno = no;

strcpy(name, n);

fee = f;

};

// driver code

int main()

student s; // this will cause error

return 0;

Output

main.cpp: In function ‘int main()’:


main.cpp:25:13: error: no matching function for call to
‘student::student()’
25 | student s; // this will cause error
| ^
main.cpp:14:5: note: candidate: ‘student::student(int, char*, double)’
14 | student(int no, char n[], double f)
| ^~~~~~~
main.cpp:14:5: note: candidate expects 3 arguments, 0 provided
main.cpp:8:7: note: candidate: ‘constexpr student::student(const student&)’
8 | class student {
| ^~~~~~~
main.cpp:8:7: note: candidate expects 1 argument, 0 provided
main.cpp:8:7: note: candidate: ‘constexpr student::student(student&&)’
main.cpp:8:7: note: candidate expects 1 argument, 0 provided ^~

Important Note: Whenever we define one or more non-default constructors( with


parameters ) for a class, a default constructor( without parameters ) should also be explicitly
defined as the compiler will not provide a default constructor in this case. However, it is not
necessary but it’s considered to be the best practice to always define a default constructor.

Uses of Parameterized Constructor

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

 It is used to ini琀椀alize the various data elements of di昀昀erent objects with di昀昀erent values
when they are created.

 It is used to overload constructors.

Default Arguments with C++ Parameterized Constructor

Just like normal functions, we can also define default values for the arguments of
parameterized constructors. All the rules of the default arguments will be applied to these
parameters.

Example 3: Defining Parameterized Constructor with Default Values

// C++ Program to illustrate how to use default arguments

// with parameterized constructor

#include <iostream>

using namespace std;

// class

class GFG {

private:

int data;

public:

// parameterized constructor with default values

GFG(int x = 0) { data = x; }

int getData() { return data; }

};

int main()

GFG obj1; // will not throw error

GFG obj2(25);

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

cout << "First Object Data: " << obj1.getData() << endl;

cout << "Second Object Data: " << obj2.getData()

<< endl;

return 0;

Output
First Object Data: 0
Second Object Data: 25

As we can see, when the default values are assigned to every argument of the parameterized
constructor, it is legal to create the object without passing any parameters just like default
constructors. So, this type of constructor works as both a default and parameterized
constructor.

3. Copy Constructor in C++


A copy constructor is a member function that initializes an object using another object of the
same class.

Syntax of Copy Constructor

Copy constructor takes a reference to an object of the same class as an argument.

ClassName (ClassName &obj)


{
// body_containing_logic
}

Just like the default constructor, the C++ compiler also provides an implicit copy
constructor if the explicit copy constructor definition is not present. Here, it is to be
noted that, unlike the default constructor where the presence of any type of explicit
constructor results in the deletion of the implicit default constructor, the implicit copy
constructor will always be created by the compiler if there is no explicit copy constructor or
explicit move constructor is present.

Examples of Copy Constructor

The below examples demonstrate how to use the copy constructors in C++.

Example 1: Illustration of Implicit Copy Constructor

// C++ program to illustrate the use of Implicit copy

// constructor

#include <iostream>

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

using namespace std;

class Sample {

int id;

public:

// parameterized constructor

Sample(int x) { id = x; }

void display() { cout << "ID=" << id; }

};

int main()

Sample obj1(10);

obj1.display();

cout << endl;

// creating an object of type Sample from the obj

Sample obj2(obj1); // or obj2=obj1;

obj2.display();

return 0;

Output
ID=10
ID=10

Example 2: Defining of Explicit Copy Constructor

// C++ Program to demonstrate how to define the explicit

// copy constructor

#include <iostream>

using namespace std;

class Sample {

int id;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

public:

// default constructor with empty body

Sample() {}

// parameterized constructor

Sample(int x) { id = x; }

// copy constructor

Sample(Sample& t) { id = t.id; }

void display() { cout << "ID=" << id; }

};

// driver code

int main()

Sample obj1(10);

obj1.display();

cout << endl;

// copy constructor called

Sample obj2(obj1); // or obj2=obj1;

obj2.display();

return 0;

Output
ID=10
ID=10

Example 3: Defining of Explicit Copy Constructor with Parameterized Constructor

// C++ program to demonstrate copy construction along with

// parameterized constructor

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

#include <iostream>

#include <string.h>

using namespace std;

// class definition

class student {

int rno;

char name[50];

double fee;

public:

student(int, char[], double);

student(student& t) // copy constructor

rno = t.rno;

strcpy(name, t.name);

fee = t.fee;

void display();

};

student::student(int no, char n[], double f)

rno = no;

strcpy(name, n);

fee = f;

void student::display()

cout << endl << rno << "\t" << name << "\t" << fee;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

int main()

student s(1001, "Manjeet", 10000);

s.display();

student manjeet(s); // copy constructor called

manjeet.display();

return 0;

Output
1001 Manjeet 10000
1001 Manjeet 10000

Uses of Copy Constructor

 Constructs a new object by copying values from an exis琀椀ng object.

 Can be used to perform deep copy.

 Modify speci昀椀c a琀琀ributes during the copy process if needed.

4. Move Constructor in C++


The move constructor is a recent addition to the family of constructors in C++. It is like a
copy constructor that constructs the object from the already existing objects., but instead
of copying the object in the new memory, it makes use of move semantics to transfer the
ownership of the already created object to the new object without creating extra copies.

It can be seen as stealing the resources from other objects.

Syntax of Move Constructor in C++


className (className&& obj) {
// body of the constructor
}

The move constructor takes the rvalue reference of the object of the same class and transfers
the ownership of this object to the newly created object.

Like a copy constructor, the compiler will create a move constructor for each class that does
not have any explicit move constructor.

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Examples of Move Constructor

The below examples demonstrate how to use the move constructors in C++.

Example 1: Defining Move Constructor

// C++ Program to illustrate how to define a move

// constructor

#include <iostream>

using namespace std;

class Box {

public:

int* data; // Pointer to an integer value

// Constructor

Box(int value)

data = new int;

*data = value;

// Move constructor

Box(Box&& other) noexcept

cout << "Move Constructor Called" << endl;

data = other.data; // Transfer ownership of 'other'

// data

other.data = nullptr; // Null out 'other' to prevent

// double deletion

// Destructor

~Box() { delete data; }

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

};

int main()

// Create a Box with value 42

Box originalBox(42);

// Create a new Box by moving resources from the

// originalBox

Box newBox(move(originalBox));

cout << "newBox.data: " << *newBox.data;

// originalBox is now in a valid but unspecified

// state (its resources were moved to newBox)

return 0;

Output
Move Constructor Called
newBox.data: 42

Uses of Move Constructor

 Instead of making copies, move constructors e昀케ciently transfer ownership of these


resources.

 This prevents unnecessary memory copying and reduces overhead.

 You can de昀椀ne your own move constructor to handle speci昀椀c resource transfers.

Destructors in C++
A destructor is also a special member function as a constructor. Destructor destroys the class
objects created by the constructor. Destructor has the same name as their class name preceded
by a tilde (~) symbol. It is not possible to define more than one destructor. The destructor is
only one way to destroy the object created by the constructor. Hence destructor can-not be
overloaded. Destructor neither requires any argument nor returns any value. It is
automatically called when the object goes out of scope. Destructors release memory space

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

occupied by the objects created by the constructor. In destructor, objects are destroyed in the
reverse of object creation.

Syntax of Destructors in C++

Like constructors, destructors can also be defined either inside or outside of the class.

The syntax for defining the destructor within the class

~ <class-name>(){}

The syntax for defining the destructor outside the class

<class-name>: : ~<class-name>(){}

Examples of Destructors in C++

The below examples demonstrate how to use the destructors in C++.

Example 1: Defining a Simple Destructor

#include <iostream>

using namespace std;

class Test {

public:

Test() { cout << "\n Constructor executed"; }

~Test() { cout << "\n Destructor executed"; }

};

main()

Test t;

return 0;

Output
Constructor executed
Destructor executed

Example 2: Counting the Number of Times Object is Created and Destroyed

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// C++ Program to count the number of objects created and

// destroyed

#include <iostream>

using namespace std;

// global variable to count

int count = 0;

// class definition

class Test {

public:

Test()

count++;

cout << "No. of Object created: " << count << endl;

~Test()

cout << "No. of Object destroyed: " << count

<< endl;

--count;

};

// driver code

int main()

Test t, t1, t2, t3;

return 0;

Output

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

No. of Object created: 1


No. of Object created: 2
No. of Object created: 3
No. of Object created: 4
No. of Object destroyed: 4
No. of Object destroyed: 3
No. of Object destroyed: 2
No. of Object destroyed: 1

Characteristics of Destructors in C++

The following are some main characteristics of destructors in C++:

 Destructor is invoked automa琀椀cally by the compiler when its corresponding constructor goes
out of scope and releases the memory space that is no longer required by the program.

 Destructor neither requires any argument nor returns any value therefore it cannot be
overloaded.

 Destructor cannot be declared as sta琀椀c and const;

 Destructor should be declared in the public sec琀椀on of the program.

 Destructor is called in the reverse order of its constructor invoca琀椀on.

When is a Copy Constructor Called in C+


+?
A copy constructor is a member function that initializes an object using another object of the
same class. The Copy constructor is called mainly when a new object is created from an
existing object, as a copy of the existing object.

In C++, a Copy Constructor may be called for the following cases:


1) When an object of the class is returned by value.
2) When an object of the class is passed (to a function) by value as an argument.
3) When an object is constructed based on another object of the same class.
4) When an object is constructed using initialization lists with braces
5) When the compiler generates a temporary object.

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

C++ Static Data Members


Static data members are class members that are declared using static keywords. A static
member has certain special characteristics which are as follows:

 Only one copy of that member is created for the en琀椀re class and is shared by all the objects
of that class, no ma琀琀er how many objects are created.
 It is ini琀椀alized before any object of this class is created, even before the main starts.
 It is visible only within the class, but its life琀椀me is the en琀椀re program.

Syntax:

static data_type data_member_name;

Below is the C++ program to demonstrate the working of static data members:

// C++ Program to demonstrate

// the working of static data member

#include <iostream>

using namespace std;

class A {

public:

A()

cout << "A's Constructor Called " <<

endl;

};

class B {

static A a;

public:

B()

cout << "B's Constructor Called " <<

endl;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

};

// Driver code

int main()

B b;

return 0;

Output
B's Constructor Called

Explanation: The above program calls only B’s constructor, it doesn’t call A’s
constructor. The reason is,

Static members are only declared in a class declaration, not defined. They must be explicitly
defined outside the class using the scope resolution operator.

Accessing a Static Member


As told earlier, the static members are only declared in the class declaration. If we try to
access the static data member without an explicit definition, the compiler will give an error.

Below is the C++ program to show when static member ‘a’ is accessed without explicit
definition:

// C++ Program to demonstrate

// the Compilation Error occurred

// due to violation of Static

// Data Memeber Rule

#include <iostream>

using namespace std;

class A {

int x;

public:

A()

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

cout << "A's constructor called " <<

endl;

};

class B {

static A a;

public:

B()

cout << "B's constructor called " <<

endl;

static A getA()

return a;

};

// Driver code

int main()

B b;

A a = b.getA();

return 0;

Output

Compiler Error: undefined reference to `B::a'

Explanation: Here static member ‘a’ is accessed without explicit definition. If we add the
definition, the program will work fine and call A’s constructor.

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Defining Static Data Member


To access the static data member of any class we have to define it first.

Below is the C++ program to show how to resolve the above error:

// C++ program to access static data

// member with explicit definition

#include <iostream>

using namespace std;

class A {

int x;

public:

A()

cout << "A's constructor called " <<

endl;

};

class B {

static A a;

public:

B()

cout << "B's constructor called " <<

endl;

static A getA()

return a;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

};

// Definition of a

A B::a;

// Driver code

int main()

B b1, b2, b3;

A a = b1.getA();

return 0;

Output
A's constructor called
B's constructor called
B's constructor called
B's constructor called

Explanation: The above program calls B’s constructor 3 times for 3 objects (b1, b2, and b3),
but calls A’s constructor only once. The reason is that the static members are shared among
all objects. That is why they are also known as class members or class fields.

Also, static members can be accessed without any object.

NOTE: Static data members can only be defined globally in C++. The only exception to this
are static const data members of integral type which can be initialized in the class declaration.

Access Static Members Without Any Object


We can access any static member without any object by using the scope resolution operator
directly with the class name.

Below is the C++ program to show access to the static member without an object:

// C++ Program to demonstrate

// static members can be accessed

// without any object

#include <iostream>

using namespace std;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

class A {

int x;

public:

A()

cout << "A's constructor called " <<

endl;

};

class B {

static A a;

public:

B()

cout << "B's constructor called " <<

endl;

static A getA()

return a;

};

// Definition of a

A B::a;

// Driver code

int main()

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// static member 'a' is accessed

// without any object of B

A a = B::getA();

return 0;

Output
A's constructor called

Static Member Function in C++


The static keyword is used with a variable to make the memory of the variable static once a
static variable is declared its memory can’t be changed. To know more about static keywords
refer to the article static Keyword in C++.

Static Member in C++


Static members of a class are not associated with the objects of the class. Just like a static
variable once declared is allocated with memory that can’t be changed every object points to
the same memory. To know more about the topic refer to a static Member in C++.

Example:

class Person{
static int index_number;
};

Once a static member is declared it will be treated as same for all the objects associated with
the class.

Example:

// C++ Program to demonstrate

// Static member in a class

#include <iostream>

using namespace std;

class Student {

public:

// static member

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

static int total;

// Constructor called

Student() { total += 1; }

};

int Student::total = 0;

int main()

// Student 1 declared

Student s1;

cout << "Number of students:" << s1.total << endl;

// Student 2 declared

Student s2;

cout << "Number of students:" << s2.total << endl;

// Student 3 declared

Student s3;

cout << "Number of students:" << s3.total << endl;

return 0;

Output
Number of students:1
Number of students:2
Number of students:3

Static Member Function in C++


Static Member Function in a class is the function that is declared as static because of which
function attains certain properties as defined below:

 A sta琀椀c member func琀椀on is independent of any object of the class.


 A sta琀椀c member func琀椀on can be called even if no objects of the class exist.
 A sta琀椀c member func琀椀on can also be accessed using the class name through the scope
resolu琀椀on operator.

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

 A sta琀椀c member func琀椀on can access sta琀椀c data members and sta琀椀c member func琀椀ons
inside or outside of the class.
 Sta琀椀c member func琀椀ons have a scope inside the class and cannot access the current object
pointer.
 You can also use a sta琀椀c member func琀椀on to determine how many objects of the class have
been created.

The reason we need Static member function:

 Sta琀椀c members are frequently used to store informa琀椀on that is shared by all objects in a
class.
 For instance, you may keep track of the quan琀椀ty of newly generated objects of a speci昀椀c
class type using a sta琀椀c data member as a counter. This sta琀椀c data member can be
increased each 琀椀me an object is generated to keep track of the overall number of objects.

Example:

// C++ Program to show the working of

// static member functions

#include <iostream>

using namespace std;

class Box

private:

static int length;

static int breadth;

static int height;

public:

static void print()

cout << "The value of the length is: " << length << endl;

cout << "The value of the breadth is: " << breadth << endl;

cout << "The value of the height is: " << height << endl;

};

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// initialize the static data members

int Box :: length = 10;

int Box :: breadth = 20;

int Box :: height = 30;

// Driver Code

int main()

Box b;

cout << "Static member function is called through Object name: \n" <<
endl;

b.print();

cout << "\nStatic member function is called through Class name: \n" <<
endl;

Box::print();

return 0;

Output
Static member function is called through Object name:

The value of the length is: 10


The value of the breadth is: 20
The value of the height is: 30

Static member function is called through Class name:

The value of the length is: 10


The value of the breadth is: 20
The value of the height is: 30

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called
Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming.

Inheritance is a feature or a process in which, new classes are created from the existing
classes. The new class created is called “derived class” or “child class” and the existing class
is known as the “base class” or “parent class”. The derived class now is said to be inherited
from the base class.

When we say derived class inherits the base class, it means, the derived class inherits all the
properties of the base class, without changing the properties of base class and may add new
features to its own. These new features in the derived class will not affect the base class. The
derived class is the specialized class for the base class.

 Sub Class: The class that inherits proper琀椀es from another class is called Subclass or Derived
Class.

 Super Class: The class whose proper琀椀es are inherited by a subclass is called Base Class or
Superclass.

The article is divided into the following subtopics:

 Why and when to use inheritance?

 Modes of Inheritance

 Types of Inheritance

Why and when to use inheritance?

Consider a group of vehicles. You need to create classes for Bus, Car, and Truck. The
methods fuelAmount(), capacity(), applyBrakes() will be the same for all three classes. If we
create these classes avoiding inheritance then we have to write all of these functions in each
of the three classes as shown below figure:

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

You can clearly see that the above process results in duplication of the same code 3 times.
This increases the chances of error and data redundancy. To avoid this type of situation,
inheritance is used. If we create a class Vehicle and write these three functions in it and
inherit the rest of the classes from the vehicle class, then we can simply avoid the duplication
of data and increase re-usability. Look at the below diagram in which the three classes are
inherited from vehicle class:

Using inheritance, we have to write the functions only one time instead of three times as we
have inherited the rest of the three classes from the base class (Vehicle).
Implementing inheritance in C++: For creating a sub-class that is inherited from the base
class we have to follow the below syntax.

Derived Classes: A Derived class is defined as the class derived from the base class.
Syntax:

class <derived_class_name> : <access-specifier> <base_class_name>


{
//body
}

Where
class — keyword to create a new class
derived_class_name — name of the new class, which will inherit the base class
access-specifier — either of private, public or protected. If neither is specified, PRIVATE is
taken as default
base-class-name — name of the base class
Note: A derived class doesn’t inherit access to private data members. However, it does
inherit a full parent object, which contains any private members which that class declares.

Example:
1. class ABC : private XYZ //private derivation
{ }
2. class ABC : public XYZ //public derivation
{ }
3. class ABC : protected XYZ //protected derivation

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

{ }
4. class ABC: XYZ //private derivation by default
{ }

Note:

o When a base class is privately inherited by the derived class, public members of the base
class becomes the private members of the derived class and therefore, the public members of
the base class can only be accessed by the member functions of the derived class. They are
inaccessible to the objects of the derived class.
o On the other hand, 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 derived class.

// Example: define member function without argument within


// the class

#include <iostream>
using namespace std;

class Person {
int id;
char name[100];

public:
void set_p()
{
cout << "Enter the Id:";
cin >> id;
cout << "Enter the Name:";
cin >> name;
}

void display_p()
{
cout << endl <<"Id: "<< id << "\nName: " << name <<endl;
}
};

class Student : private Person {


char course[50];
int fee;

public:
void set_s()
{
set_p();
cout << "Enter the Course Name:";
cin >> course;
cout << "Enter the Course Fee:";
cin >> fee;
}

void display_s()

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

{
display_p();
cout <<"Course: "<< course << "\nFee: " << fee << endl;
}
};

int main()
{
Student s;
s.set_s();
s.display_s();
return 0;
}

Output:

Enter the Id: 101


Enter the Name: Dev
Enter the Course Name: GCS
Enter the Course Fee:70000

Id: 101
Name: Dev
Course: GCS
Fee: 70000
// Example: define member function without argument outside the class

#include<iostream>
using namespace std;

class Person
{
int id;
char name[100];

public:
void set_p();
void display_p();
};

void Person::set_p()
{
cout<<"Enter the Id:";
cin>>id;
cout<<"Enter the Name:";
cin>>name;
}

void Person::display_p()
{
cout<<endl<<"id: "<< id<<"\nName: "<<name;
}

class Student: private Person


{
char course[50];
int fee;

public:

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

void set_s();
void display_s();
};

void Student::set_s()
{
set_p();
cout<<"Enter the Course Name:";
cin>>course;
cout<<"Enter the Course Fee:";
cin>>fee;
}

void Student::display_s()
{
display_p();
cout<<"\nCourse: "<<course<<"\nFee: "<<fee<<endl;
}

int main()
{
Student s;
s.set_s();
s.display_s();
return 0;
}

Output:

Enter the Id: 101


Enter the Name: Dev
Enter the Course Name: GCS
Enter the Course Fee: 70000
Id: 101
Name: Dev
Course: GCS
Fee: 70000

// Example: define member function with argument outside the class

#include<iostream>
#include<string.h>
using namespace std;

class Person
{
int id;
char name[100];

public:
void set_p(int,char[]);
void display_p();
};

void Person::set_p(int id,char n[])


{
this->id=id;
strcpy(this->name,n);
}

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

void Person::display_p()
{
cout<<endl<<id<<"\t"<<name;
}

class Student: private Person


{
char course[50];
int fee;
public:
void set_s(int,char[],char[],int);
void display_s();
};

void Student::set_s(int id,char n[],char c[],int f)


{
set_p(id,n);
strcpy(course,c);
fee=f;
}

void Student::display_s()
{
display_p();
cout<<"t"<<course<<"\t"<<fee;
}

main()
{
Student s;
s.set_s(1001,"Ram","B.Tech",2000);
s.display_s();
return 0;
}

// C++ program to demonstrate implementation


// of Inheritance

#include <bits/stdc++.h>
using namespace std;

// Base class
class Parent {
public:
int id_p;
};

// Sub class inheriting from Base Class(Parent)


class Child : public Parent {
public:
int id_c;
};

// main function

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

int main()
{
Child obj1;

// An object of class child has all data members


// and member functions of class parent
obj1.id_c = 7;
obj1.id_p = 91;
cout << "Child id is: " << obj1.id_c << '\n';
cout << "Parent id is: " << obj1.id_p << '\n';

return 0;
}
Output
Child id is: 7
Parent id is: 91

Output:

Child id is: 7
Parent id is: 91

In the above program, the ‘Child’ class is publicly inherited from the ‘Parent’ class so the
public data members of the class ‘Parent’ will also be inherited by the class ‘Child’.
Modes of Inheritance: There are 3 modes of inheritance.

1. Public Mode: If we derive a subclass from a public base class. Then the public
member of the base class will become public in the derived class and protected
members of the base class will become protected in the derived class.

2. Protected Mode: If we derive a subclass from a Protected base class. Then both
public members and protected members of the base class will become protected in the
derived class.

3. Private Mode: If we derive a subclass from a Private base class. Then both public
members and protected members of the base class will become Private in the derived
class.

Note: The private members in the base class cannot be directly accessed in the derived class,
while protected members can be directly accessed. For example, Classes B, C, and D all
contain the variables x, y, and z in the below example. It is just a question of access.

// C++ Implementation to show that a derived class


// doesn’t inherit access to private data members.
// However, it does inherit a full parent object.
class A {
public:
int x;

protected:
int y;

private:
int z;
};

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

class B : public A {
// x is public
// y is protected
// z is not accessible from B
};

class C : protected A {
// x is protected
// y is protected
// z is not accessible from C
};

class D : private A // 'private' is default for classes


{
// x is private
// y is private
// z is not accessible from D
};

The below table summarizes the above three modes and shows the access specifier of the
members of the base class in the subclass when derived in public, protected and private
modes:

The below table summarizes the above three modes and shows the access specifier of the
members of the base class in the subclass when derived in public, protected and private
modes:

Types Of Inheritance:-

1. Single inheritance

2. Mul琀椀level inheritance

3. Mul琀椀ple inheritance

4. Hierarchical inheritance

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

5. Hybrid inheritance

Types of Inheritance in C++

1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class.
i.e. one subclass is inherited by one base class only.

Syntax:

class subclass_name : access_mode base_class


{
// body of subclass
};
OR
class A
{
... .. ...
};
class B: public A
{
... .. ...
};
// C++ program to explain

// Single inheritance

#include<iostream>

using namespace std;

// base class

class Vehicle {

public:

Vehicle()

cout << "This is a Vehicle\n";

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

};

// sub class derived from a single base classes

class Car : public Vehicle {

};

// main function

int main()

// Creating object of sub class will

// invoke the constructor of base classes

Car obj;

return 0;

Output
This is a Vehicle

// Example:

#include<iostream>

using namespace std;

class A

protected:

int a;

public:

void set_A()

cout<<"Enter the Value of A=";

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

cin>>a;

void disp_A()

cout<<endl<<"Value of A="<<a;

};

class B: public A

int b,p;

public:

void set_B()

set_A();

cout<<"Enter the Value of B=";

cin>>b;

void disp_B()

disp_A();

cout<<endl<<"Value of B="<<b;

void cal_product()

p=a*b;

cout<<endl<<"Product of "<<a<<" * "<<b<<" = "<<p;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

};

main()

B _b;

_b.set_B();

_b.cal_product();

return 0;

Output:- Enter the Value of A= 3 3 Enter the Value of B= 5 5 Product of 3 * 5 = 15

// Example:

#include<iostream>

using namespace std;

class A

protected:

int a;

public:

void set_A(int x)

a=x;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

void disp_A()

cout<<endl<<"Value of A="<<a;

};

class B: public A

int b,p;

public:

void set_B(int x,int y)

set_A(x);

b=y;

void disp_B()

disp_A();

cout<<endl<<"Value of B="<<b;

void cal_product()

p=a*b;

cout<<endl<<"Product of "<<a<<" * "<<b<<" = "<<p;

};

main()

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

B _b;

_b.set_B(4,5);

_b.cal_product();

return 0;

Output
Product of 4 * 5 = 20

2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit
from more than one class. i.e one subclass is inherited from more than one base class.

Syntax:

class subclass_name : access_mode base_class1, access_mode


base_class2, ....
{
// body of subclass
};
class B
{
... .. ...
};
class C
{
... .. ...
};
class A: public B, public C
{
... ... ...
};

Here, the number of base classes will be separated by a comma (‘, ‘) and the access mode for
every base class must be specified.

// C++ program to explain

// multiple inheritance

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

#include <iostream>

using namespace std;

// first base class

class Vehicle {

public:

Vehicle() { cout << "This is a Vehicle\n"; }

};

// second base class

class FourWheeler {

public:

FourWheeler()

cout << "This is a 4 wheeler Vehicle\n";

};

// sub class derived from two base classes

class Car : public Vehicle, public FourWheeler {

};

// main function

int main()

// Creating object of sub class will

// invoke the constructor of base classes.

Car obj;

return 0;

Output
This is a Vehicle
This is a 4 wheeler Vehicle

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// Example:

#include<iostream>

using namespace std;

class A

protected:

int a;

public:

void set_A()

cout<<"Enter the Value of A=";

cin>>a;

void disp_A()

cout<<endl<<"Value of A="<<a;

};

class B: public A

protected:

int b;

public:

void set_B()

cout<<"Enter the Value of B=";

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

cin>>b;

void disp_B()

cout<<endl<<"Value of B="<<b;

};

class C: public B

int c,p;

public:

void set_C()

cout<<"Enter the Value of C=";

cin>>c;

void disp_C()

cout<<endl<<"Value of C="<<c;

void cal_product()

p=a*b*c;

cout<<endl<<"Product of "<<a<<" * "<<b<<" * "<<c<<" =


"<<p;

};

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

main()

C _c;

_c.set_A();

_c.set_B();

_c.set_C();

_c.disp_A();

_c.disp_B();

_c.disp_C();

_c.cal_product();

return 0;

To know more about it, please refer to the article Multiple Inheritances.

3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another
derived class.

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Syntax:-

class C
{
... .. ...
};
class B:public C
{
... .. ...
};
class A: public B
{
... ... ...
};
// C++ program to implement

// Multilevel Inheritance

#include <iostream>

using namespace std;

// base class

class Vehicle {

public:

Vehicle() { cout << "This is a Vehicle\n"; }

};

// first sub_class derived from class vehicle

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

class fourWheeler : public Vehicle {

public:

fourWheeler()

cout << "Objects with 4 wheels are vehicles\n";

};

// sub class derived from the derived base class fourWheeler

class Car : public fourWheeler {

public:

Car() { cout << "Car has 4 Wheels\n"; }

};

// main function

int main()

// Creating object of sub class will

// invoke the constructor of base classes.

Car obj;

return 0;

Output
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels

4. Hierarchical Inheritance: In this type of inheritance, more than one subclass is inherited
from a single base class. i.e. more than one derived class is created from a single base class.

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Syntax:-

class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
// C++ program to implement

// Hierarchical Inheritance

#include <iostream>

using namespace std;

// base class

class Vehicle {

public:

Vehicle() { cout << "This is a Vehicle\n"; }

};

// first sub class

class Car : public Vehicle {

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

};

// second sub class

class Bus : public Vehicle {

};

// main function

int main()

// Creating object of sub class will

// invoke the constructor of base class.

Car obj1;

Bus obj2;

return 0;

Output
This is a Vehicle
This is a Vehicle

5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more


than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple
Inheritance.
Below image shows the combination of hierarchical and multiple inheritances:

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// C++ program for Hybrid Inheritance

#include <iostream>

using namespace std;

// base class

class Vehicle {

public:

Vehicle() { cout << "This is a Vehicle\n"; }

};

// base class

class Fare {

public:

Fare() { cout << "Fare of Vehicle\n"; }

};

// first sub class

class Car : public Vehicle {

};

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// second sub class

class Bus : public Vehicle, public Fare {

};

// main function

int main()

// Creating object of sub class will

// invoke the constructor of base class.

Bus obj2;

return 0;

Output
This is a Vehicle
Fare of Vehicle

// Example:

#include <iostream>

using namespace std;

class A

protected:

int a;

public:

void get_a()

cout << "Enter the value of 'a' : ";

cin>>a;

};

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

class B : public A

protected:

int b;

public:

void get_b()

cout << "Enter the value of 'b' : ";

cin>>b;

};

class C

protected:

int c;

public:

void get_c()

cout << "Enter the value of c is : ";

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;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

};

int main()

D d;

d.mul();

return 0;

6. A special case of hybrid inheritance: Multipath inheritance:


A derived class with two base classes and these two base classes have one common base class
is called multipath inheritance. Ambiguity can arise in this type of inheritance.
Example:

// C++ program demonstrating ambiguity in Multipath

// Inheritance

#include <iostream>

using namespace std;

class ClassA {

public:

int a;

};

class ClassB : public ClassA {

public:

int b;

};

class ClassC : public ClassA {

public:

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

int c;

};

class ClassD : public ClassB, public ClassC {

public:

int d;

};

int main()

ClassD obj;

// obj.a = 10; // Statement 1, Error

// obj.a = 100; // Statement 2, Error

obj.ClassB::a = 10; // Statement 3

obj.ClassC::a = 100; // Statement 4

obj.b = 20;

obj.c = 30;

obj.d = 40;

cout << " a from ClassB : " << obj.ClassB::a;

cout << "\n a from ClassC : " << obj.ClassC::a;

cout << "\n b : " << obj.b;

cout << "\n c : " << obj.c;

cout << "\n d : " << obj.d << '\n';

Output
a from ClassB : 10
a from ClassC : 100
b : 20
c : 30
d : 40

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Output:

a from ClassB : 10
a from ClassC : 100
b : 20
c : 30
d : 40

In the above example, both ClassB and ClassC inherit ClassA, they both have a single copy
of ClassA. However Class-D inherits both ClassB and ClassC, therefore Class-D has two
copies of ClassA, one from ClassB and another from ClassC.
If we need to access the data member of ClassA through the object of Class-D, we must
specify the path from which a will be accessed, whether it is from ClassB or ClassC, bcoz
compiler can’t differentiate between two copies of ClassA in Class-D.

There are 2 Ways to Avoid this Ambiguity:

1) Avoiding ambiguity using the scope resolution operator: Using the scope resolution
operator we can manually specify the path from which data member a will be accessed, as
shown in statements 3 and 4, in the above example.

obj.ClassB::a = 10; // Statement 3

obj.ClassC::a = 100; // Statement 4

Note: Still, there are two copies of ClassA in Class-D.


2) Avoiding ambiguity using the virtual base class:

#include<iostream>

class ClassA

public:

int a;

};

class ClassB : virtual public ClassA

public:

int b;

};

class ClassC : virtual public ClassA

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

public:

int c;

};

class ClassD : public ClassB, public ClassC

public:

int d;

};

int main()

ClassD obj;

obj.a = 10; // Statement 3

obj.a = 100; // Statement 4

obj.b = 20;

obj.c = 30;

obj.d = 40;

cout << "\n a : " << obj.a;

cout << "\n b : " << obj.b;

cout << "\n c : " << obj.c;

cout << "\n d : " << obj.d << '\n';

Output:

a : 100
b : 20
c : 30
d : 40

According to the above example, Class-D has only one copy of ClassA, therefore, statement
4 will overwrite the value of a, given in statement 3.

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Operator Overloading in C++


in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving
special meaning to an existing operator in C++ without changing its original meaning.

In this article, we will further discuss about operator overloading in C++ with examples and
see which operators we can or cannot overload in C++.

C++ Operator Overloading


C++ has the ability to provide the operators with a special meaning for a data type, this
ability is known as operator overloading. Operator overloading is a compile-time
polymorphism. For example, we can overload an operator ‘+’ in a class like String so that we
can concatenate two strings by just using +. Other example classes where arithmetic operators
may be overloaded are Complex Numbers, Fractional Numbers, Big integers, etc.

Example:

int a;
float b,sum;
sum = a + b;

Here, variables “a” and “b” are of types “int” and “float”, which are built-in data types.
Hence the addition operator ‘+’ can easily add the contents of “a” and “b”. This is because
the addition operator “+” is predefined to add variables of built-in data type only.

Implementation:

// C++ Program to Demonstrate the

// working/Logic behind Operator

// Overloading

class A {

statements;

};

int main()

A a1, a2, a3;

a3 = a1 + a2;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

return 0;

In this example, we have 3 variables “a1”, “a2” and “a3” of type “class A”. Here we are
trying to add two objects “a1” and “a2”, which are of user-defined type i.e. of type “class A”
using the “+” operator. This is not allowed, because the addition operator “+” is predefined to
operate only on built-in data types. But here, “class A” is a user-defined type, so the compiler
generates an error. This is where the concept of “Operator overloading” comes in.

Now, if the user wants to make the operator “+” add two class objects, the user has to
redefine the meaning of the “+” operator such that it adds two class objects. This is done by
using the concept of “Operator overloading”. So the main idea behind “Operator
overloading” is to use C++ operators with class variables or class objects. Redefining the
meaning of operators really does not change their original meaning; instead, they have been
given additional meaning along with their existing ones.

Example of Operator Overloading in C++


// C++ Program to Demonstrate

// Operator Overloading

#include <iostream>

using namespace std;

class Complex {

private:

int real, imag;

public:

Complex(int r = 0, int i = 0)

real = r;

imag = i;

// This is automatically called when '+' is used with

// between two Complex objects

Complex operator+(Complex const& obj)

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Complex res;

res.real = real + obj.real;

res.imag = imag + obj.imag;

return res;

void print() { cout << real << " + i" << imag << '\n'; }

};

int main()

Complex c1(10, 5), c2(2, 4);

Complex c3 = c1 + c2;

c3.print();

Output
12 + i9

Difference between Operator Functions and Normal


Functions
Operator functions are the same as normal functions. The only differences are, that the name
of an operator function is always the operator keyword followed by the symbol of the
operator, and operator functions are called when the corresponding operator is used.

Example
#include <iostream>

using namespace std;

class Complex {

private:

int real, imag;

public:

Complex(int r = 0, int i = 0)

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

real = r;

imag = i;

void print() { cout << real << " + i" << imag << endl; }

// The global operator function is made friend of this

// class so that it can access private members

friend Complex operator+(Complex const& c1,

Complex const& c2);

};

Complex operator+(Complex const& c1, Complex const& c2)

return Complex(c1.real + c2.real, c1.imag + c2.imag);

int main()

Complex c1(10, 5), c2(2, 4);

Complex c3

= c1

+ c2; // An example call to "operator+"

c3.print();

return 0;

Output
12 + i9

Can We Overload All Operators?


Almost all operators can be overloaded except a few. Following is the list of operators that
cannot be overloaded.

sizeof
typeid
Scope resolution (::)
Class member access operators (.(dot), .* (pointer to member operator))
Ternary or conditional (?:)

Operators that can be Overloaded in C++


We can overload

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

 Unary operators
 Binary operators
 Special operators ( [ ], (), etc)

But, among them, there are some operators that cannot be overloaded. They are

 Scope resolu琀椀on operator (:


 Member selec琀椀on operator
 Member selec琀椀on through *

Pointer to a member variable

 Condi琀椀onal operator (?
 Sizeof operator sizeof()

Operators that can be overloaded Examples

Binary Arithme琀椀c +, -, *, /, %

Unary Arithme琀椀c +, -, ++, —

Assignment =, +=,*=, /=,-=, %=

Bitwise & , | , << , >> , ~ , ^

De-referencing (->)

Dynamic memory alloca琀椀on,


New, delete
De-alloca琀椀on

Subscript []

Func琀椀on call ()

Logical &, | |, !

Rela琀椀onal >, < , = =, <=, >=

Why can’t the above-stated operators be overloaded?


1. sizeof Operator

This returns the size of the object or datatype entered as the operand. This is evaluated by the
compiler and cannot be evaluated during runtime. The proper incrementing of a pointer in an
array of objects relies on the sizeof operator implicitly. Altering its meaning using
overloading would cause a fundamental part of the language to collapse.

2. typeid Operator

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

This provides a CPP program with the ability to recover the actually derived type of the
object referred to by a pointer or reference. For this operator, the whole point is to uniquely
identify a type. If we want to make a user-defined type ‘look’ like another type,
polymorphism can be used but the meaning of the typeid operator must remain unaltered, or
else serious issues could arise.

3. Scope resolution (::) Operator

This helps identify and specify the context to which an identifier refers by specifying a
namespace. It is completely evaluated at runtime and works on names rather than values. The
operands of scope resolution are note expressions with data types and CPP has no syntax for
capturing them if it were overloaded. So it is syntactically impossible to overload this
operator.

4. Class member access operators (.(dot), .* (pointer to member operator))

The importance and implicit use of class member access operators can be understood through
the following example:

Example:

// C++ program to demonstrate operator overloading

// using dot operator

#include <iostream>

using namespace std;

class ComplexNumber {

private:

int real;

int imaginary;

public:

ComplexNumber(int real, int imaginary)

this->real = real;

this->imaginary = imaginary;

void print() { cout << real << " + i" << imaginary; }

ComplexNumber operator+(ComplexNumber c2)

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

ComplexNumber c3(0, 0);

c3.real = this->real + c2.real;

c3.imaginary = this->imaginary + c2.imaginary;

return c3;

};

int main()

ComplexNumber c1(3, 5);

ComplexNumber c2(2, 4);

ComplexNumber c3 = c1 + c2;

c3.print();

return 0;

Output
5 + i9

Explanation:

The statement ComplexNumber c3 = c1 + c2; is internally translated as ComplexNumber c3


= c1.operator+ (c2); in order to invoke the operator function. The argument c1 is implicitly
passed using the ‘.’ operator. The next statement also makes use of the dot operator to access
the member function print and pass c3 as an argument.

Besides, these operators also work on names and not values and there is no provision
(syntactically) to overload them.

5. Ternary or conditional (?:) Operator

The ternary or conditional operator is a shorthand representation of an if-else statement. In


the operator, the true/false expressions are only evaluated on the basis of the truth value of
the conditional expression.

conditional statement ? expression1 (if statement is TRUE) : expression2


(else)

A function overloading the ternary operator for a class say ABC using the definition

ABC operator ?: (bool condition, ABC trueExpr, ABC falseExpr);

would not be able to guarantee that only one of the expressions was evaluated. Thus, the
ternary operator cannot be overloaded.

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Important Points about Operator Overloading


1) For operator overloading to work, at least one of the operands must be a user-defined class
object.

2) Assignment Operator: Compiler automatically creates a default assignment operator with


every class. The default assignment operator does assign all members of the right side to the
left side and works fine in most cases (this behavior is the same as the copy constructor). See
this for more details.

3) Conversion Operator: We can also write conversion operators that can be used to convert
one type to another type.

Example:

// C++ Program to Demonstrate the working

// of conversion operator

#include <iostream>

using namespace std;

class Fraction {

private:

int num, den;

public:

Fraction(int n, int d)

num = n;

den = d;

// Conversion operator: return float value of fraction

operator float() const

return float(num) / float(den);

};

int main()

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Fraction f(2, 5);

float val = f;

cout << val << '\n';

return 0;

Output
0.4

Overloaded conversion operators must be a member method. Other operators can either be
the member method or the global method.

4) Any constructor that can be called with a single argument works as a conversion
constructor, which means it can also be used for implicit conversion to the class being
constructed.

Example:

// C++ program to demonstrate can also be used for implicit

// conversion to the class being constructed

#include <iostream>

using namespace std;

class Point {

private:

int x, y;

public:

Point(int i = 0, int j = 0)

x = i;

y = j;

void print()

cout << "x = " << x << ", y = " << y << '\n';

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

};

int main()

Point t(20, 20);

t.print();

t = 30; // Member x of t becomes 30

t.print();

return 0;

Output
x = 20, y = 20
x = 30, y = 0

Public vs Protected in C++ with Examples


Public

All the class members declared under public will be available to everyone. The data members
and member functions declared public can be accessed by other classes too. The public
members of a class can be accessed from anywhere in the program using the direct member
access operator (.) with the object of that class.

Example:

// C++ program to demonstrate public

// access modifier

#include <iostream>

using namespace std;

// class definition

class Circle {

public:

double radius;

double compute_area()

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

return 3.14 * radius * radius;

};

// main function

int main()

Circle obj;

// accessing public data member outside class

obj.radius = 5.5;

cout << "Radius is: " << obj.radius << "\n";

cout << "Area is: " << obj.compute_area();

return 0;

Output:
Radius is: 5.5
Area is: 94.985

In the above program, the data member radius is public so we are allowed to access it outside
the class.

Protected

Protected access modifier is similar to that of private access modifiers, the difference is that
the class member declared as Protected are inaccessible outside the class but they can be
accessed by any subclass(derived class) of that class.
Example:

// C++ program to demonstrate

// protected access modifier

#include <bits/stdc++.h>

using namespace std;

// base class

class Parent {

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// protected data members

protected:

int id_protected;

};

// sub class or derived class

class Child : public Parent {

public:

void setId(int id)

// Child class is able to access the inherited

// protected data members of base class

id_protected = id;

void displayId()

cout << "id_protected is: " << id_protected << endl;

};

// main function

int main()

Child obj1;

// member function of the derived class can

// access the protected data members of the base class

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

obj1.setId(81);

obj1.displayId();

return 0;

Difference between Public and Protected

Public Protected

All the class members declared under Protected access modi昀椀er is similar to that of private access
public will be available to everyone. modi昀椀ers.

The data members and member The class member declared as Protected are inaccessible
func琀椀ons declared public can be outside the class but they can be accessed by any
accessed by other classes too. subclass(derived class) of that class.

Function Overriding in C++


A function is a block of statements that together performs a specific task by taking some
input and producing a particular output. Function overriding in C++ is termed as the
redefinition of base class function in its derived class with the same signature i.e. return type
and parameters. It falls under the category of Runtime Polymorphism.

Real-Life Example of Function Overriding


The best Real-life example of this concept is the Constitution of India. India took the political
code, structure, procedures, powers, and duties of government institutions and set out
fundamental rights, directive principles, and the duties of citizens of other countries and
implemented them on its own; making it the biggest constitution in the world.

Another Development real-life example could be the relationship between RBI(The Reserve
Bank of India) and Other state banks like SBI, PNB, ICICI, etc. Where the RBI passes the
same regulatory function and others follow it as it is.

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Function Overriding

Syntax:

class Parent{

access_modifier:

// overridden function

return_type name_of_the_function(){}

};

class child : public Parent {

access_modifier:

// overriding function

return_type name_of_the_function(){}

};

Example:

// C++ program to demonstrate function overriding

#include <iostream>

using namespace std;

class Parent {

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

public:

void GeeksforGeeks_Print()

cout << "Base Function" << endl;

};

class Child : public Parent {

public:

void GeeksforGeeks_Print()

cout << "Derived Function" << endl;

};

int main()

Child Child_Derived;

Child_Derived.GeeksforGeeks_Print();

return 0;

Output
Derived Function

Variations in Function Overriding


1. Call Overridden Function From Derived Class
// C++ program to demonstrate function overriding

// by calling the overridden function

// of a member function from the child class

#include <iostream>

using namespace std;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

class Parent {

public:

void GeeksforGeeks_Print()

cout << "Base Function" << endl;

};

class Child : public Parent {

public:

void GeeksforGeeks_Print()

cout << "Derived Function" << endl;

// call of overridden function

Parent::GeeksforGeeks_Print();

};

int main()

Child Child_Derived;

Child_Derived.GeeksforGeeks_Print();

return 0;

Output
Derived Function
Base Function

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

The output of Call Overridden Function From Derived Class

2. Call Overridden Function Using Pointer


// C++ program to access overridden function using pointer

// of Base type that points to an object of Derived class

#include <iostream>

using namespace std;

class Parent {

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

public:

void GeeksforGeeks()

cout << "Base Function" << endl;

};

class Child : public Parent {

public:

void GeeksforGeeks()

cout << "Derived Function" << endl;

};

int main()

Child Child_Derived;

// pointer of Parent type that points to derived1

Parent* ptr = &Child_Derived;

// call function of Base class using ptr

ptr->GeeksforGeeks();

return 0;

Output
Base Function

3. Access of Overridden Function to the Base Class


// C++ program to access overridden function

// in main() using the scope resolution operator ::

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

#include <iostream>

using namespace std;

class Parent {

public:

void GeeksforGeeks()

cout << "Base Function" << endl;

};

class Child : public Parent {

public:

void GeeksforGeeks()

cout << "Derived Function" << endl;

};

int main()

Child Child_Derived;

Child_Derived.GeeksforGeeks();

// access GeeksforGeeks() function of the Base class

Child_Derived.Parent::GeeksforGeeks();

return 0;

Output
Derived Function
Base Function

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Access of Overridden Function to the Base Class

4. Access to Overridden Function


// C++ Program Demonstrating

// Accessing of Overridden Function

#include <iostream>

using namespace std;

// defining of the Parent class

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

class Parent

public:

// defining the overridden function

void GeeksforGeeks_Print()

cout << "I am the Parent class function" << endl;

};

// defining of the derived class

class Child : public Parent

public:

// defining of the overriding function

void GeeksforGeeks_Print()

cout << "I am the Child class function" << endl;

};

int main()

// create instances of the derived class

Child GFG1, GFG2;

// call the overriding function

GFG1.GeeksforGeeks_Print();

// call the overridden function of the Base class

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

GFG2.Parent::GeeksforGeeks_Print();

return 0;

Output
I am the Child class function
I am the Parent class function

Function Overloading Vs Function Overriding


Function Overloading Function Overriding
It falls under Compile-Time polymorphism It falls under Run琀椀me Polymorphism

A func琀椀on can be overloaded mul琀椀ple 琀椀mes as it A func琀椀on cannot be overridden mul琀椀ple 琀椀mes
is resolved at Compile 琀椀me as it is resolved at Run 琀椀me

Can be executed without inheritance Cannot be executed without inheritance

They are in the same scope They are of di昀昀erent scopes.

Virtual base class in C++


Virtual base classes are used in virtual inheritance in a way of preventing multiple
“instances” of a given class appearing in an inheritance hierarchy when using multiple
inheritances.

Need for Virtual Base Classes: Consider the situation where we have one class A . This
class A is inherited by two other classes B and C. Both these class are inherited into another
in a new class D as shown in figure below.

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

As we can see from the figure that data members/function of class A are inherited twice to
class D. One through class B and second through class C. When any data / function member
of class A is accessed by an object of class D, ambiguity arises as to which data/function
member would be called? One inherited through B or the other inherited through C. This
confuses compiler and it displays error.

Example: To show the need of Virtual Base Class in C++

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

#include <iostream>

using namespace std;

class A {

public:

void show()

cout << "Hello form A \n";

};

class B : public A {

};

class C : public A {

};

class D : public B, public C {

};

int main()

D object;

object.show();

Compile Errors:

prog.cpp: In function 'int main()':


prog.cpp:29:9: error: request for member 'show' is ambiguous
object.show();
^
prog.cpp:8:8: note: candidates are: void A::show()
void show()
^
prog.cpp:8:8: note: void A::show()

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

How to resolve this issue?


To resolve this ambiguity when class A is inherited in both class B and class C, it is declared
as virtual base class by placing a keyword virtual as :

Syntax for Virtual Base Classes:

Syntax 1:
class B : virtual public A
{
};
Syntax 2:
class C : public virtual A
{
};

Note:
virtual can be written before or after the public. Now only one copy of data/function
member will be copied to class C and class B and class A becomes the virtual base class.
Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that
use multiple inheritances. When a base class is specified as a virtual base, it can act as an
indirect base more than once without duplication of its data members. A single copy of its
data members is shared by all the base classes that use virtual base.

Example 1

#include <iostream>

using namespace std;

class A {

public:

int a;

A() // constructor

a = 10;

};

class B : public virtual A {

};

class C : public virtual A {

};

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

class D : public B, public C {

};

int main()

D object; // object creation of class d

cout << "a = " << object.a << endl;

return 0;

Output
a = 10

Explanation :
The class A has just one data member a which is public. This class is virtually inherited in
class B and class C. Now class B and class C use the virtual base class A and no duplication
of data member a is done; Classes B and C share a single copy of the members in the virtual
base class A.

Example 2:

#include <iostream>

using namespace std;

class A {

public:

void show()

cout << "Hello from A \n";

};

class B : public virtual A {

};

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

class C : public virtual A {

};

class D : public B, public C {

};

int main()

D object;

object.show();

Output
Hello from A

Difference between Virtual function and


Pure virtual function in C++
Virtual Function in C++
A virtual function is a member function which is declared within a base class and is re-
defined(Overridden) by a derived class. When you refer to a derived class object using a
pointer or a reference to the base class, you can call a virtual function for that object and
execute the derived class’s version of the function.

Pure Virtual Functions in C++


A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t
have an implementation, we only declare it. A pure virtual function is declared by assigning 0
in the declaration.

Similarities between virtual function and pure virtual function

1. These are the concepts of Run-琀椀me polymorphism.


2. Prototype i.e. Declara琀椀on of both the func琀椀ons remains the same throughout the program.
3. These func琀椀ons can’t be global or sta琀椀c.

Difference between virtual function and pure virtual function in C++

Virtual func琀椀on Pure virtual func琀椀on

A virtual func琀椀on is a member func琀椀on of A pure virtual func琀椀on is a member func琀椀on of base
base class which can be rede昀椀ned by derived class whose only declara琀椀on is provided in base class
class. and should be de昀椀ned in derived class otherwise

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Virtual func琀椀on Pure virtual func琀椀on

derived class also becomes abstract.

Classes having virtual func琀椀ons are not Base class containing pure virtual func琀椀on becomes
abstract. abstract.

Syntax:
virtual<func_type><func_name>() Syntax:
{ virtual<func_type><func_name>()

// code = 0;

De昀椀ni琀椀on is given in base class. No de昀椀ni琀椀on is given in base class.

Base class having virtual func琀椀on can be Base class having pure virtual func琀椀on becomes
instan琀椀ated i.e. its object can be made. abstract i.e. it cannot be instan琀椀ated.

If derived class do not rede昀椀ne virtual If derived class do not rede昀椀ne virtual func琀椀on of
func琀椀on of base class, then it does not a昀昀ect base class, then no compila琀椀on error but derived
compila琀椀on. class also becomes abstract just like the base class.

All derived class must rede昀椀ne pure virtual func琀椀on


All derived class may or may not rede昀椀ne
of base class otherwise derived class also becomes
virtual func琀椀on of base class.
abstract just like base class.

C++ Polymorphism
The word “polymorphism” means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A real-life
example of polymorphism is a person who at the same time can have different characteristics.
A man at the same time is a father, a husband, and an employee. So the same person exhibits
different behavior in different situations. This is called polymorphism. Polymorphism is
considered one of the important features of Object-Oriented Programming.

Types of Polymorphism
 Compile-琀椀me Polymorphism

 Run琀椀me Polymorphism

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Types of Polymorphism

1. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator overloading.

A. Function Overloading

When there are multiple functions with the same name but different parameters, then the
functions are said to be overloaded, hence this is known as Function Overloading. Functions
can be overloaded by changing the number of arguments or/and changing the type of
arguments. In simple terms, it is a feature of object-oriented programming providing many
functions that have the same name but distinct parameters when numerous tasks are listed
under one function name. There are certain Rules of Function Overloading that should be
followed while overloading a function.

Below is the C++ program to show function overloading or compile-time polymorphism:

// C++ program to demonstrate

// function overloading or

// Compile-time Polymorphism

#include <bits/stdc++.h>

using namespace std;

class Geeks {

public:

// Function with 1 int parameter

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

void func(int x)

cout << "value of x is " << x << endl;

// Function with same name but

// 1 double parameter

void func(double x)

cout << "value of x is " << x << endl;

// Function with same name and

// 2 int parameters

void func(int x, int y)

cout << "value of x and y is " << x << ", " << y

<< endl;

};

// Driver code

int main()

Geeks obj1;

// Function being called depends

// on the parameters passed

// func() is called with int value

obj1.func(7);

// func() is called with double value

obj1.func(9.132);

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// func() is called with 2 int values

obj1.func(85, 64);

return 0;

Output
value of x is 7
value of x is 9.132
value of x and y is 85, 64

Explanation: In the above example, a single function named function func() acts differently
in three different situations, which is a property of polymorphism. To know more about this,
you can refer to the article – Function Overloading in C++.

B. Operator Overloading

C++ has the ability to provide the operators with a special meaning for a data type, this
ability is known as operator overloading. For example, we can make use of the addition
operator (+) for string class to concatenate two strings. We know that the task of this operator
is to add two operands. So a single operator ‘+’, when placed between integer operands, adds
them and when placed between string operands, concatenates them.

Below is the C++ program to demonstrate operator overloading:

// C++ program to demonstrate

// Operator Overloading or

// Compile-Time Polymorphism

#include <iostream>

using namespace std;

class Complex {

private:

int real, imag;

public:

Complex(int r = 0, int i = 0)

real = r;

imag = i;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// This is automatically called

// when '+' is used with between

// two Complex objects

Complex operator+(Complex const& obj)

Complex res;

res.real = real + obj.real;

res.imag = imag + obj.imag;

return res;

void print() { cout << real << " + i" << imag << endl; }

};

// Driver code

int main()

Complex c1(10, 5), c2(2, 4);

// An example call to "operator+"

Complex c3 = c1 + c2;

c3.print();

Output
12 + i9

Explanation: In the above example, the operator ‘+’ is overloaded. Usually, this operator is
used to add two numbers (integers or floating point numbers), but here the operator is made
to perform the addition of two imaginary or complex numbers. To know more about this one,
refer to the article – Operator Overloading.

2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and dynamic
polymorphism are other names for runtime polymorphism. The function call is resolved at

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

runtime in runtime polymorphism. In contrast, with compile time polymorphism, the


compiler determines which function call to bind to the object after deducing it at runtime.

A. Function Overriding

Function Overriding occurs when a derived class has a definition for one of the member
functions of the base class. That base function is said to be overridden.

Function overriding Explanation

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Runtime Polymorphism with Data Members

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

// C++ program for function overriding with data members

#include <bits/stdc++.h>

using namespace std;

// base class declaration.

class Animal {

public:

string color = "Black";

};

// inheriting Animal class.

class Dog : public Animal {

public:

string color = "Grey";

};

// Driver code

int main(void)

Animal d = Dog(); // accessing the field by reference

// variable which refers to derived

cout << d.color;

Output
Black

We can see that the parent class reference will always refer to the data member of the parent
class.

B. Virtual Function

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

A virtual function is a member function that is declared in the base class using the keyword
virtual and is re-defined (Overridden) in the derived class.

Some Key Points About Virtual Functions:

 Virtual func琀椀ons are Dynamic in nature.

 They are de昀椀ned by inser琀椀ng the keyword “virtual” inside a base class and are always
declared with a base class and overridden in a child class

 A virtual func琀椀on is called during Run琀椀me

Below is the C++ program to demonstrate virtual function:

// C++ Program to demonstrate

// the Virtual Function

#include <iostream>

using namespace std;

// Declaring a Base class

class GFG_Base {

public:

// virtual function

virtual void display()

cout << "Called virtual Base Class function"

<< "\n\n";

void print()

cout << "Called GFG_Base print function"

<< "\n\n";

};

// Declaring a Child Class

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

class GFG_Child : public GFG_Base {

public:

void display()

cout << "Called GFG_Child Display Function"

<< "\n\n";

void print()

cout << "Called GFG_Child print Function"

<< "\n\n";

};

// Driver code

int main()

// Create a reference of class GFG_Base

GFG_Base* base;

GFG_Child child;

base = &child;

// This will call the virtual function

base->GFG_Base::display();

// this will call the non-virtual function

base->print();

Output

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Called virtual Base Class function

Called GFG_Base print function

Example 2:

// C++ program for virtual function overriding

#include <bits/stdc++.h>

using namespace std;

class base {

public:

virtual void print()

cout << "print base class" << endl;

void show() { cout << "show base class" << endl; }

};

class derived : public base {

public:

// print () is already virtual function in

// derived class, we could also declared as

// virtual void print () explicitly

void print() { cout << "print derived class" << endl; }

void show() { cout << "show derived class" << endl; }

};

// Driver code

int main()

base* bptr;

derived d;

bptr = &d;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// Virtual function, binded at

// runtime (Runtime polymorphism)

bptr->print();

// Non-virtual function, binded

// at compile time

bptr->show();

return 0;

Output
print derived class
show base class

Difference between Inheritance and Polymorphism:


S.NO Inheritance Polymorphism

Inheritance is one in which a new class is


created (derived class) that inherits the Whereas polymorphism is that which
1.
features from the already exis琀椀ng class(Base can be de昀椀ned in mul琀椀ple forms.
class).

Whereas it is basically applied to


2. It is basically applied to classes.
func琀椀ons or methods.

Polymorphism allows the object to


Inheritance supports the concept of decide which form of the func琀椀on to
3. reusability and reduces code length in object- implement at compile-琀椀me
oriented programming. (overloading) as well as run-琀椀me
(overriding).

Whereas it can be compiled-琀椀me


Inheritance can be single, hybrid, mul琀椀ple,
4. polymorphism (overload) as well as
hierarchical and mul琀椀level inheritance.
run-琀椀me polymorphism (overriding).

While it is also used in pa琀琀ern


5. It is used in pa琀琀ern designing.
designing.

6. Example : Example :

The class bike can be inherit from the The class bike can have method

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

S.NO Inheritance Polymorphism

name set_color(), which changes


class of two-wheel vehicles, which is turn
the bike’s color based on the name
could be a subclass of vehicles.
of color you have entered.

C++ Pointers
Pointers are symbolic representations of addresses. They enable programs to simulate call-by-
reference as well as to create and manipulate dynamic data structures. Iterating over elements
in arrays or other data structures is one of the main use of pointers.

The address of the variable you’re working with is assigned to the pointer variable that points
to the same data type (such as an int or string).

Syntax:

datatype *var_name;
int *ptr; // ptr can point to an address which holds int data

How to use a pointer?


 De昀椀ne a pointer variable

 Assigning the address of a variable to a pointer using the unary operator (&) which returns
the address of that variable.

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

 Accessing the value stored in the address using unary operator (*) which returns the value of
the variable located at the address speci昀椀ed by its operand.

The reason we associate data type with a pointer is that it knows how many bytes the data
is stored in. When we increment a pointer, we increase the pointer by the size of the data
type to which it points.

// C++ program to illustrate Pointers

#include <bits/stdc++.h>
using namespace std;
void geeks()
{
int var = 20;

// declare pointer variable


int* ptr;

// note that data type of ptr and var must be same


ptr = &var;

// assign the address of a variable to a pointer


cout << "Value at ptr = " << ptr << "\n";
cout << "Value at var = " << var << "\n";
cout << "Value at *ptr = " << *ptr << "\n";
}
// Driver program
int main()
{
geeks();
return 0;
}

Output
Value at ptr = 0x7ffe454c08cc

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Value at var = 20
Value at *ptr = 20

References and Pointers


There are 3 ways to pass C++ arguments to a function:

 Call-By-Value

 Call-By-Reference with a Pointer Argument

 Call-By-Reference with a Reference Argument

// C++ program to illustrate call-by-methods

#include <bits/stdc++.h>
using namespace std;

// Pass-by-Value
int square1(int n)
{
// Address of n in square1() is not the same as n1 in
// main()
cout << "address of n1 in square1(): " << &n << "\n";

// clone modified inside the function


n *= n;
return n;
}
// Pass-by-Reference with Pointer Arguments
void square2(int* n)
{
// Address of n in square2() is the same as n2 in main()
cout << "address of n2 in square2(): " << n << "\n";

// Explicit de-referencing to get the value pointed-to


*n *= *n;
}
// Pass-by-Reference with Reference Arguments
void square3(int& n)
{
// Address of n in square3() is the same as n3 in main()
cout << "address of n3 in square3(): " << &n << "\n";

// Implicit de-referencing (without '*')


n *= n;
}
void geeks()
{
// Call-by-Value
int n1 = 8;
cout << "address of n1 in main(): " << &n1 << "\n";
cout << "Square of n1: " << square1(n1) << "\n";
cout << "No change in n1: " << n1 << "\n";

// Call-by-Reference with Pointer Arguments


int n2 = 8;
cout << "address of n2 in main(): " << &n2 << "\n";

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

square2(&n2);
cout << "Square of n2: " << n2 << "\n";
cout << "Change reflected in n2: " << n2 << "\n";

// Call-by-Reference with Reference Arguments


int n3 = 8;
cout << "address of n3 in main(): " << &n3 << "\n";
square3(n3);
cout << "Square of n3: " << n3 << "\n";
cout << "Change reflected in n3: " << n3 << "\n";
}
// Driver program
int main() { geeks(); }

Output
address of n1 in main(): 0x7fffa7e2de64
address of n1 in square1(): 0x7fffa7e2de4c
Square of n1: 64
No change in n1: 8
address of n2 in main(): 0x7fffa7e2de68
address of n2 in square2(): 0x7fffa7e2de68
Square of n2: 64
Change reflected in n2: 64
address of n3 in main(): 0x7fffa7e2de6c
address of n3 in square3(): 0x7fffa7e2de6c
Square of n3: 64
Change reflected in n3: 64

In C++, by default arguments are passed by value and the changes made in the called
function will not reflect in the passed variable. The changes are made into a clone made by
the called function. If wish to modify the original copy directly (especially in passing huge
object or array) and/or avoid the overhead of cloning, we use pass-by-reference. Pass-by-
Reference with Reference Arguments does not require any clumsy syntax for referencing and
dereferencing.

 Func琀椀on pointers in C

 Pointer to a Func琀椀on

Array Name as Pointers


An array name contains the address of the first element of the array which acts like a constant
pointer. It means, the address stored in the array name can’t be changed. For example, if we
have an array named val then val and &val[0] can be used interchangeably.

// C++ program to illustrate Array Name as Pointers


#include <bits/stdc++.h>
using namespace std;
void geeks()
{
// Declare an array
int val[3] = { 5, 10, 20 };

// declare pointer variable


int* ptr;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// Assign the address of val[0] to ptr


// We can use ptr=&val[0];(both are same)
ptr = val;
cout << "Elements of the array are: ";
cout << ptr[0] << " " << ptr[1] << " " << ptr[2];
}
// Driver program
int main() { geeks(); }

Output
Elements of the array are: 5 10 20

If pointer ptr is sent to a function as an argument, the array val can be accessed in a similar
fashion. Pointer vs Array

Pointer Expressions and Pointer Arithmetic


A limited set of arithmetic operations can be performed on pointers which are:

 incremented ( ++ )

 decremented ( — )

 an integer may be added to a pointer ( + or += )

 an integer may be subtracted from a pointer ( – or -= )

 di昀昀erence between two pointers (p1-p2)

(Note: Pointer arithmetic is meaningless unless performed on an array.)

// C++ program to illustrate Pointer Arithmetic


#include <bits/stdc++.h>
using namespace std;
void geeks()
{
// Declare an array
int v[3] = { 10, 100, 200 };

// declare pointer variable


int* ptr;

// Assign the address of v[0] to ptr


ptr = v;

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

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

cout << "Value at ptr = " << ptr << "\n";


cout << "Value at *ptr = " << *ptr << "\n";

// Increment pointer ptr by 1


ptr++;
}
}

// Driver program
int main() { geeks(); }

Output
Value at ptr = 0x7ffe5a2d8060
Value at *ptr = 10
Value at ptr = 0x7ffe5a2d8064
Value at *ptr = 100
Value at ptr = 0x7ffe5a2d8068
Value at *ptr = 200

Advanced Pointer Notation


Consider pointer notation for the two-dimensional numeric arrays. consider the following
declaration

int nums[2][3] = { { 16, 18, 20 }, { 25, 26, 27 } };

In general, nums[ i ][ j ] is equivalent to *(*(nums+i)+j)

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

Pointers and String literals


String literals are arrays containing null-terminated character sequences. String literals are
arrays of type character plus terminating null-character, with each of the elements being of
type const char (as characters of string can’t be modified).

This declares an array with the literal representation for “geek”, and then a pointer to its first
element is assigned to ptr. If we imagine that “geek” is stored at the memory locations that
start at address 1800, we can represent the previous declaration as:

As pointers and arrays behave in the same way in expressions, ptr can be used to access the
characters of a string literal. For example:

char ptr = 0;
char x = *(ptr+3);
char y = ptr[3];

Here, both x and y contain k stored at 1803 (1800+3).

Pointers to pointers
In C++, we can create a pointer to a pointer that in turn may point to data or another pointer.
The syntax simply requires the unary operator (*) for each level of indirection while
declaring the pointer.

char a;
char *b;
char ** c;
a = ’g’;
b = &a;
c = &b;

Here b points to a char that stores ‘g’ and c points to the pointer b.

Void Pointers
This is a special type of pointer available in C++ which represents the absence of type. Void
pointers are pointers that point to a value that has no type (and thus also an undetermined
length and undetermined dereferencing properties). This means that void pointers have great
flexibility as they can point to any data type. There is a payoff for this flexibility. These
pointers cannot be directly dereferenced. They have to be first transformed into some other
pointer type that points to a concrete data type before being dereferenced.

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

// C++ program to illustrate Void Pointer


#include <bits/stdc++.h>
using namespace std;
void increase(void* data, int ptrsize)
{
if (ptrsize == sizeof(char)) {
char* ptrchar;

// Typecast data to a char pointer


ptrchar = (char*)data;

// Increase the char stored at *ptrchar by 1


(*ptrchar)++;
cout << "*data points to a char"
<< "\n";
}
else if (ptrsize == sizeof(int)) {
int* ptrint;

// Typecast data to a int pointer


ptrint = (int*)data;

// Increase the int stored at *ptrchar by 1


(*ptrint)++;
cout << "*data points to an int"
<< "\n";
}
}
void geek()
{
// Declare a character
char c = 'x';

// Declare an integer
int i = 10;

// Call increase function using a char and int address


// respectively
increase(&c, sizeof(c));
cout << "The new value of c is: " << c << "\n";
increase(&i, sizeof(i));
cout << "The new value of i is: " << i << "\n";
}
// Driver program
int main() { geek(); }

Output
*data points to a char
The new value of c is: y
*data points to an int
The new value of i is: 11

Invalid pointers
A pointer should point to a valid address but not necessarily to valid elements (like for
arrays). These are called invalid pointers. Uninitialized pointers are also invalid pointers.

int *ptr1;

Downloaded by ABHINAV PAL ([email protected])


lOMoARcPSD|41983625

int arr[10];
int *ptr2 = arr+20;

Here, ptr1 is uninitialized so it becomes an invalid pointer and ptr2 is out of bounds of arr so
it also becomes an invalid pointer. (Note: invalid pointers do not necessarily raise compile
errors)

NULL Pointers
A null pointer is a pointer that point nowhere and not just an invalid address. Following are 2
methods to assign a pointer as NULL;

int *ptr1 = 0;
int *ptr2 = NULL;

Advantages of Pointers
 Pointers reduce the code and improve performance. They are used to retrieve strings, trees,
arrays, structures, and func琀椀ons.

 Pointers allow us to return mul琀椀ple values from func琀椀ons.

 In addi琀椀on to this, pointers allow us to access a memory loca琀椀on in the computer’s memory.

Downloaded by ABHINAV PAL ([email protected])

You might also like