[go: up one dir, main page]

0% found this document useful (0 votes)
6 views26 pages

Unit - 3

Uploaded by

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

Unit - 3

Uploaded by

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

UNIT – III CLASSES AND OBJECTS

Syllabus
Classes and Objects – Member Functions – Private and Public Member function – Nesting of
Member Functions – Array of Objects – Pointer to Members – Constructors – Destructors –
Type Conversions
3.1 Classes and Objects
Class 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.
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.
 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 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.

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().

3.2 Member Functions


 A member function of a class is a function that has its definition or its prototype
within the class definition like any other variable.
 It operates on any object of the class of which it is a member, and has access to
all the members of a class for that object.
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.

Let us take previously defined class to access the members of the class using a member
function instead of directly accessing them −

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void);// Returns box volume
};

Member functions can be defined within the class definition or separately using scope
resolution operator, : −. Defining a member function within the class definition
declares the function inline, even if you do not use the inline specifier. So either you can
define Volume() function as below −

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

double getVolume(void) {
return length * breadth * height;
}
};
If you like, you can define the same function outside the class using the scope resolution
operator (::) as follows −

double Box::getVolume(void) {
return length * breadth * height;
}

Here, only important point is that you would have to use class name just before ::
operator. A member function will be called using a dot operator (.) on a object where it
will manipulate data related to that object only as follows −

Box myBox; // Create an object

myBox.getVolume(); // Call member function for the object

Let us put above concepts to set and get the value of different class members in a class –

#include <iostream>

using namespace std;

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

// Member functions declaration


double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};

// Member functions definitions


double Box::getVolume(void) {
return length * breadth * height;
}

void Box::setLength( double len ) {


length = len;
}
void Box::setBreadth( double bre ) {
breadth = bre;
}
void Box::setHeight( double hei ) {
height = hei;
}
// Main function for the program
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}

When the above code is compiled and executed, it produces the following result −

Volume of Box1 : 210


Volume of Box2 : 1560

3.3 Private and Public Member function


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 :


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.

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;

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.

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>
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;
}
};
// 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:
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.
3.4 Nesting of member Functions
 Whenever we call a member function inside another member function of one class by
using dot operator it is known as Nesting of the member function.
 Normally, the member function which is called by another member function is kept
private so that it cannot be called directly using the dot operator.

Example

#include<iostream.h>
//nested member function

class squarenumb
{
int number;
public:
long square();
void getnumber();
void display();
};

void squarenumb:getnumber()
{
cout<<"Please enter an integer number:";
cin>>number;
}

long squarenumber::square()
{
number=number*number;
return (number);
}

void squarenumb::display()
{
cout<<"Square of the number:"<<square();

int main ()
{
squarenumb square;
square.getnumber();
square.display();

return 0;
}
Output:
Please enter an integer number:10
10
Square of the number:100
3.5 Array of Objects
 An array in C/C++ or be it in any programming language is a collection of
similar data items stored at contiguous memory locations and elements can be
accessed randomly using indices of an array.
 They can be used to store the collection of primitive data types such as int,
float, double, char, etc of any particular type.
 To add to it, an array in C/C++ can store derived data types such as structures,
pointers, etc. Given below is the picture representation of an array.

Example:
Let’s consider an example of taking random integers from the user.

Array of 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[number of objects];

The Array of Objects stores objects. An array of a class type is also known as an array
of objects.

Example
Storing more than one Employee data. Let’s assume there is an array of objects for
storing employee data emp[50].
// C++ program to implement the above approach

#include<iostream>
using namespace std;

class Employee
{
int id;
char name[30];
public:

// Declaration of function
void getdata();

// Declaration of function
void putdata();
};
// Defining the function outside the class
void Employee::getdata()
{
cout << "Enter Id : ";
cin >> id;
cout << "Enter Name : ";
cin >> name;
}
// Defining the function outside the class
void Employee::putdata()
{
cout << id << " ";
cout << name << " ";
cout << endl;
}
// Driver code
int main()
{
// This is an array of objects having maximum limit of 30 Employees
Employee emp[30];
int n, i;
cout << "Enter Number of Employees - ";
cin >> n;

// Accessing the function


for(i = 0; i < n; i++)
emp[i].getdata();

cout << "Employee Data - " << endl;

// Accessing the function


for(i = 0; i < n; i++)
emp[i].putdata();
}
Output:

Enter Number of Employees - 2


Enter Id : 1
Enter Name : san
Enter Id : 2
Enter Name : sen
Employee Data -
1 san
2 sen

Explanation:
In this example, more than one Employee’s details with an Employee id and name can be
stored.
 Employee emp[30] – This is an array of objects having a maximum limit of 30
Employees.
 Two for loops are being used-
 First one to take the input from user by calling emp[i].getdata() function.
 Second one to print the data of Employee by calling the function
emp[i].putdata() function.

Advantages of Array of Objects:


1. The array of objects represent storing multiple objects in a single name.
2. In an array of objects, the data can be accessed randomly by using the index number.
3. Reduce the time and memory by storing the data in a single variable.

3.6 Pointer to Members


 Pointers to members are a concept that allows you to store and manipulate pointers to
class or struct members. Unlike regular pointers, which point to data or functions,
pointers to members point to specific members (variables or functions) within a class
or struct.
 They are a powerful feature that enables you to work with class members in a dynamic
and flexible way.

Pointer to members allows you to store and manipulate pointers to class or struct
members.

We can assign the address(using the &) of a class member (variables or functions) and
assign it to a pointer variable.

It is a powerful feature that enables you to work with class members in a dynamic and
flexible way.

A class member pointer can be declared using the operator ::* with the class name.

class MyClass{
private:
int data;
public:
void show();
};
We can define the pointer to a member e.g. data using operator ::* as follows

int MyClass ::* ptr=&MyClass :: data;


Here, the statement MyClass ::* ptr is “pointer-to-member” of the class MyClass.

The statement &MyClass :: data means the address of the


member i.e. data of MyClass.

Important Note!

int *ptr=&data; //It is not valid


Now, the pointer *ptr can be used to access the member data inside member function or
friend function.

Let’s say obj is an object of MyClass, we can access the data using the pointer ptr as
follows.

cout<<obj.*ptr;
cout<<obj.data; //It is same as above

//PointerToMemberEx1.cpp
#include <iostream>
using namespace std;

class MyClass
{
public:
int myData;
MyClass(int data) : myData(data) {}
};

int main()
{
MyClass obj(10);
int MyClass::*ptr = &MyClass::myData; // Define a pointer to a data member

// Access the data member using the pointer


int value = obj.*ptr;

cout << "Value of myData: " << value <<endl;


return 0;
}

Output

Value of myData: 10
3.7 Constructors

Constructor is a special method that is invoked automatically at the time of object


creation.

 Constructor is a member function of a class; whose name is the same as the class
name.
 Constructor is a special type of member function that is used to initialize the
data members for an object of a class automatically when an object of the same
class is created.
 Constructor is invoked at the time of object creation. 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 automatically when we create the object of the class.
 Constructors can be overloaded.
 A constructor cannot be declared virtual.

Syntax of Constructors
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
The below examples demonstrate how to declare constructors for a class :

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;
}

Output
Enter the RollNo: 121
Enter the Name: SSN
Enter the Fee: 5000
121 SSN 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()
{
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: Ani
Enter the Fee:10111
11 Ani 10111

Characteristics of Constructors
The following are some main characteristics of the constructors:
 The name of the constructor is the same as its class name.
 Constructors are mostly declared in the public section of the class though they can be
declared in the private section of the class.
 Constructors do not return values; hence they do not have a return type.
 A constructor gets called automatically when we create the object of the class.
 Constructors can be overloaded.
 A constructor cannot 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
allocation.

Types of Constructor
Constructors can be classified based on in which situations they are being used.
There are 4 types of constructors:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Move Constructor
1. Default Constructor
 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
}

Example:

// 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

2. Parameterized Constructor
 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
}

Example

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();

return 0;
}

Output
p1.x = 10,
p1.y = 15
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;
}

// driver code
int main()
{
student s(1001, "Ram", 10000);
s.display();
return 0;
}

Output
1001 Ram 10000

Uses of Parameterized Constructor


 It is used to initialize the various data elements of different objects with different 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);

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

3. Copy Constructor
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.

Example 1: Illustration of Implicit Copy Constructor

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


#include <iostream>
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;

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

Uses of Copy Constructor


 Constructs a new object by copying values from an existing object.
 Can be used to perform deep copy.
 Modify specific attributes during the copy process if needed.

4. Move Constructor
The move constructor is a recent addition to the family of constructors . 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


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 .
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; }
};

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 efficiently transfer ownership of these
resources.
 This prevents unnecessary memory copying and reduces overhead.
 You can define your own move constructor to handle specific resource transfers.

3.8 Destructors
 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 occupied by the objects created by the
constructor.
 In destructor, objects are destroyed in the reverse of object creation.

Syntax of Destructors
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>(){}

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

// 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
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
The following are some main characteristics of destructors:
 Destructor is invoked automatically 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 static and const;
 Destructor should be declared in the public section of the program.
 Destructor is called in the reverse order of its constructor invocation.
Properties of Destructor
The following are the main properties of Destructor:
 The destructor function is automatically invoked when the objects are destroyed.
 It cannot be declared static or const.
 The destructor does not have arguments.
 It has no return type not even void.
 An object of a class with a Destructor cannot become a member of the union.
 A destructor should be declared in the public section of the class.
 The programmer cannot access the address of the destructor.

3.9 Type Conversions


A type cast is basically a conversion from one type to another. There are two types of type
conversion:
1. Implicit Type Conversion Also known as ‘automatic type conversion’.
 Done by the compiler on its own, without any external trigger from the user.
 Generally takes place when in an expression more than one data type is present. In
such condition type conversion (type promotion) takes place to avoid lose of data.
 All the data types of the variables are upgraded to the data type of the variable with
largest data type.
 bool -> char -> short int -> int ->

 unsigned int -> long -> unsigned ->


 long long -> float -> double -> long double
 It is possible for implicit conversions to lose information, signs can be lost (when
signed is implicitly converted to unsigned), and overflow can occur (when long long
is implicitly converted to float).

Example of Type Implicit Conversion:

// An example of implicit conversion

#include <iostream>
using namespace std;

int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y;

// x is implicitly converted to float


float z = x + 1.0;

cout << "x = " << x << endl


<< "y = " << y << endl
<< "z = " << z << endl;
return 0;
}
Output:
x = 107
y=a
z = 108

2. Explicit Type Conversion: This process is also called type casting and it is user
defined. Here the user can typecast the result to make it of a particular data type.

In C++, it can be done by two ways:


 Converting by assignment: This is done by explicitly defining the required type in
front of the expression in parenthesis. This can be also considered as forceful casting.

Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
// C++ program to demonstrate explicit type casting
#include <iostream>
using namespace std;
int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

cout << "Sum = " << sum;

return 0;
}
Output:
Sum = 2
 Conversion using Cast operator:
A Cast operator is an unary operator which forces one data type to be converted
into another data type.

C++ supports four types of casting:


1. Static Cast
2. Dynamic Cast
3. Const Cast
4. Reinterpret Cast

Example
#include <iostream>
using namespace std;
int main()
{
float f = 3.5;
// using cast operator
int b = static_cast<int>(f);
cout << b;
}

Output:
3

Advantages of Type Conversion:


 This is done to take advantage of certain features of type hierarchies or type
representations.
 It helps to compute expressions containing variables of different data types.

You might also like