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

Unit1 Type Casting This Pointer-Part-2

Uploaded by

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

Unit1 Type Casting This Pointer-Part-2

Uploaded by

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

1

Type Conversion in C++


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

P a g e 1 | 10
2

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.
Example:

// 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
Example: 4. Reinterpret Cast

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

P a g e 2 | 10
3

“this” Pointer
Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the invoking object.
The this pointer holds the address of current object, in simple words you can say that
this pointer points to the current object of the class.
Friend functions do not have a this pointer, because friends are not members of a class. Only
member functions have a this pointer.
Let us try the following example to understand the concept of this pointer −

Example-1
#include <iostream>
using namespace std;
class Demo {
private:
int num;
char ch;
public:
void setMyValues(int num, char ch){
this->num =num;
this->ch=ch;
}
void displayMyValues(){
cout<<num<<endl;
cout<<ch;
}
};
int main(){
Demo obj;
obj.setMyValues(100, 'A');
obj.displayMyValues();
return 0;
}

Output
100
A

Example-2 : Calling function with “this” pointer :

#include<iostream.h>
#include<conio.h>
class SYIT // class definition
{
private:
int Roll;

P a g e 3 | 10
char name[20];
public:
void getdata(); // function declaration
void putdata(); // function declaration
}s1; // end of class
void SYIT :: getdata ( ) //function definition outside class
{
cout << “enter your Roll no and name : ”;
cin >> Roll>>name;
}
void SYIT :: putdata ( ) //function definition outside class
{
this →getdata(); // calling function with “this”
cout<< “ your roll no = “ <<Roll;
cout<< “ your Name = “ <<name;
}
void main ( )
{
clrscr(0;
s1.putdata(); // function call
getch();
}

P a g e 2 | 10
4

Array of object
An object of class represents a single record in memory, if we want more than one record of
class type, we have to create an array of class or object. As we know, an array is a collection
of similar type, therefore an array can be a collection of class type.
Syntax for Array of object

class class-name
{
datatype var1;
datatype var2;
----------
datatype varN;

method1();
method2();
----------
methodN();
};

class-name obj[ size ];

In the following example, we shall declare an array of type Student, with size of five. Student
is a class that we defined in the program. Then we shall assign objects using index of array.

#include <iostream>
using namespace std;

class Student {
public:
string name;
int rollno;
Student() {}
Student(string x, int y) {
name = x;
rollno = y;
}

void printDetails() {
cout << rollno << " - " << name << endl;
}
};

int main() {
//declare array with specific size
Student students[5];

//assign objects
students[0] = Student("Ram", 5);
students[1] = Student("Alex", 1);
P a g e 5 | 10
students[2] = Student("Lesha", 4);
5

students[3]
students[4] = Student("Emily", 3);
= Student("Anita", 2);

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


students[i].printDetails();
}
}
Output
5 - Ram
1 - Alex
4 - Lesha
3 - Emily
2 - Anita

Array of Objects – Declare and Initialize in a Single Line


In the following example, we shall declare an array of type Student, and initialize the array
with objects of Student type in a single line.
#include <iostream>
using namespace std;

class Student {
public:
string name;
int rollno;

Student() {}

Student(string x, int y) {
name = x;
rollno = y;
}

void printDetails() {
cout << rollno << " - " << name << endl;
}
};

int main() {
//declare array with specific size
Student students[] = {Student("Ram", 5), Student("Lesha", 4), Student("Anita", 2)};

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


students[i].printDetails();
}
}
Output
5 - Ram
4 - Lesha
2 - Anita
P a g e 6 | 10
6

Example for Array of object


#include<iostream>

class Employee
{
int Id;
char Name[25];
int Age;
long Salary;

public:
void GetData() //Statement 1 : Defining GetData()
{
cout<<"\n\tEnter Employee Id : ";
cin>>Id;

cout<<"\n\tEnter Employee Name : ";


cin>>Name;

cout<<"\n\tEnter Employee Age : ";


cin>>Age;

cout<<"\n\tEnter Employee Salary : ";


cin>>Salary;
}

void PutData() //Statement 2 : Defining PutData()


{
cout<<"\n"<<Id<<"\t"<<Name<<"\t"<<Age<<"\t"<<Salary;
}
};
void main()
{
int i;
Employee E[3]; //Statement 3 : Creating Array of 3 Employees

for(i=0;i<3;i++)
{
cout<<"\nEnter details of "<<i+1<<" Employee";
E[i].GetData();
}
cout<<"\nDetails of Employees";
for(i=0;i<3;i++)
E[i].PutData();
}

Output :

Enter details of 1 Employee


P a g e 7 | 10
Enter Employee Id : 101

P a g e 8 | 10
7

Enter Employee Name : Suresh


Enter Employee Age : 29
Enter Employee Salary : 45000

Enter details of 2 Employee


Enter Employee Id : 102
Enter Employee Name : Mukesh
Enter Employee Age : 31
Enter Employee Salary : 51000

Enter details of 3 Employee


Enter Employee Id : 103
Enter Employee Name : Ramesh
Enter Employee Age : 28
Enter Employee Salary : 47000

Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000

In the above example, we are getting and displaying the data of 3 employee using array of
object. Statement 1 is creating an array of Employee Emp to store the records of 3 employees.

Namespace

A namespace is designed to overcome is used as additional information to differentiate


similar functions, classes, variables etc. with the same name available in different libraries.
Using namespace, you can define the context in which names are defined. In essence, a
namespace defines a scope.

Defining a Namespace

A namespace definition begins with the keyword namespace followed by the namespace
name as follows −
namespace namespace_name {
// code declarations
}
To call the namespace-enabled version of either function or variable, prepend (::) thenamespace
name as follows −
name::code; // code could be variable or function.
Let us see how namespace scope the entities including variable and functions −

P a g e 9 | 10
#include <iostream>
using namespace std;

// first name space

P a g e 10 | 10
8

namespace first_space {
void func() {
cout << "Inside first_space" << endl;
}
}

// second name space


namespace second_space {
void func() {
cout << "Inside second_space" << endl;
}
}

int main () {
// Calls function from first name space.
first_space::func();

// Calls function from second name space.


second_space::func();

return 0;
}
If we compile and run above code, this would produce the following result −
Inside first_space Inside
second_space

The using directive

You can also avoid prepending of namespaces with the using namespace directive. This
directive tells the compiler that the subsequent code is making use of names in the specified
namespace. The namespace is thus implied for the following code −
#include <iostream>
using namespace std;

// first name space


namespace first_space {
void func() {
cout << "Inside first_space" << endl;
}
}

// second name space


namespace second_space {
void func() {
cout << "Inside second_space" << endl;
}
}

using namespace first_space;


int main () {

P a g e 11 | 10
9

// This calls function from first name space.


func();

return 0;
}
If we compile and run above code, this would produce the following result −
Inside first_space
The ‘using’ directive can also be used to refer to a particular item within a namespace. For
example, if the only part of the std namespace that you intend to use is cout, you can refer to it
as follows −
using std::cout;
Subsequent code can refer to cout without prepending the namespace, but other items in the
std namespace will still need to be explicit as follows −
#include <iostream>
using std::cout;

int main () {
cout << "std::endl is used with std!" << std::endl;

return 0;
}

If we compile and run above code, this would produce the following result −
std::endl is used with std!
Names introduced in a using directive obey normal scope rules. The name is visible from the
point of the using directive to the end of the scope in which the directive is found. Entities
with the same name defined in an outer scope are hidden.
Nested Classes in C++
• Difficulty Level : Easy
• Last Updated : 04 Jan, 2019
A nested class is a class which is declared in another enclosing class. A nested class is a member
and as such has the same access rights as any other member. The members of an enclosing
class have no special access to members of a nested class; the usual access rules shall be
obeyed.
For example, program 1 compiles without any error and program 2 fails in compilation.
Program 1

#include<iostream>

using namespace std;

/* start of Enclosing class declaration */


class Enclosing {
private:
int x;

P a g e 12 | 10
10

/* start of Nested class declaration */


class Nested {
int y;
void NestedFun(Enclosing *e) {
cout<<e->x; // works fine: nested class can access
// private members of Enclosing class
}
}; // declaration Nested class ends here
}; // declaration Enclosing class ends here

int main ()
{
}

Program 2

#include<iostream>
using namespace std;

/* start of Enclosing class declaration */


class Enclosing {

int x;

/* start of Nested class declaration */


class Nested {
int y;
}; // declaration Nested class ends here

void EnclosingFun(Nested *n) {


cout<<n->y; // Compiler Error: y is private in Nested
}
}; // declaration Enclosing class ends here

int main ()
{
}

P a g e 13 | 10

You might also like