Final UNIT-4-C++
Final UNIT-4-C++
BSc CS, IT, CT, SS, CSA, MM & B.C.A (Regular) –II SEMESTER
CORE 3: C++ PROGRAMMING
UNIT-IV
Staff Name: S. Ganeshmoorthy MCA., M.Phil., MBA (Ph.D.)
-----------------------------------------------------------------------------------------------------------------------------------------
UNIT IV: Pointers – Declaration – Pointer to Class , Object – this pointer – Pointers to derived
classes and Base classes – Arrays – Characteristics – array of classes – Memory models – new and
delete operators – dynamic object – Binding, Polymorphism and Virtual Functions
------------------------------------------------------------------------------------------------------------------------------
Pointers and its declaration
Synopsis
1. Introduction
2. Definition
3. 2 operators of pointers
4. Declaration and Initialization of Pointer Variable
5. Address of operator (&)
6. Dereference (*) or ‘Value of’ or Indirection
Operator
7. Types of pointers
Pointer to integer
Pointer to char
Pointer float
Introduction
A pointer is an address that refers to a location in memory.
Pointers are usable with both primitive (built-in) or user-defined types.
Pointers make use of the "dereference" *, "address of” &, and "arrow" -> operators.
'*' and '->' operators are used to access the memory being pointed at
‘&’ operator is used to get an address in memory.
Definition:
A pointer is a variable which store the memory address of another variable.
It supports dynamic memory allocation routines.
A pointer variable and normal variable is always same data type.
2 Operators Of Pointers
There are two operators for pointers:
Address-of operator (&): Returns the memory address of its operand.
Contents-of (Dereference) operator (*): Returns the value of the variable located at
the address specified by its operator.
Example:
int *x;
Float *y;
1
Char *z;
Syntax
Ptr_name=&variable name;
Example
int x = 10;
int *Ptr;
Ptr = &x;
Now Ptr will contain address where the variable x is stored in memory
#include<iostream.h>
Int main()
{
Int *ptr,x;
x=10;
ptr=&q; // address of q is assigned to ptr
Cout<<ptr; // address stored at ptr will be displayed
Cout<<*ptr; //display x value using ptr variable
Return 0;
}
Output
2
0x5f0fff2
10
3
Pointer to class and objects
Synopsis
1. Introduction
2. Syntax
3. Example
4. Example program using pointer to class and object
Introduction
“Pointers can be defined to hold the address of an object, which is created statically or
dynamically”.
Pointers can also be used with objects of derived classes
When address of an object of a class is stored into the pointer variable of the same
class Type then it is pointer of object.
This pointer can be used to access the data member and member function of same
class.
Syntax:
Class_name object_name;
Class_name *pointer_variable;
Pointer_variable = &object_name;
Pointer_variable -> function_name ();
Example:
//create a class syco;
//and declare data member and function;
//Now, in main function:
Class bca
bca obj;
bca *ptr; // pointer to object
Ptr=&obj; // used to access the data member & member function of same class.
Obj->getdata();
Obj->putdata();
4
Example program using pointer to class and object
#include <iostream.h>
#include<conio.h>
Class bca
{
Private:
………
………
Public:
Void getdata();
{
--------
--------
}
Void putdata();
{
--------
--------
}
}
Main( )
{
Class bca
bca obj;
bca *ptr; // pointer to object
Ptr=&obj; // used to access the data member & member function of same class.
Obj->getdata();
Obj->putdata();
Return();
}
5
This Pointer
Synopsis
1. Introduction
2. Syntax
3. Example of this pointer:
4. Advantages of Pointer
5. Limitations of Pointer
Introduction
C++ uses a unique keyword called “this”
It is used to represent an object that invokes a member Function.
This is a pointer that points to the object for which this function was called.
This is a unique pointer is automatically passed to a member function when it is
called.
The pointer this acts as an implicit argument to all the member function.
It’s an in-built pointer so programmer doesn’t need to explicitly create this pointer.
One class can have exactly one this pointer.
Definition
The this pointer holds the address of current object
This pointer points to the current object of the class
It uses a unique keyword called “this”.
Syntax:
There are two ways of accessing member with this pointer as follows:
this->data_member;
this->member_function();
OR
*this(data_member);
Here you can see that we have two data members => num and ch.
6
In member function setMyValues() we have two local variables having same name as data
members name.
In such case if you want to assign the local variable value to the data members then you won’t
be able to do until unless you use this pointer, because the compiler won’t know that you are
referring to object’s data members unless you use this pointer.
This is one of the example where you must use this pointer.
#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
Advantages of Pointer
Pointer can handle array more efficiently.
As they provide direct access to memory, they process data very fast.
They reduce storage space.
They give alternate way to access elements of an array.
Pointers avoid any confusion by the compiler due to variables with same name.
They help in building complex data structures like linked list, stacks, queues, trees,
graphs etc.
Limitations of Pointer
They are slower than normal variables.
7
Pointers store only address but cannot store a value.
It requires a null pointer reference.
If a pointer is initialized with incorrect value, it can lead to a garbage value which
may cause error in the program.
Class Base
{
public:
int x;
void display ()
{
cout<<”X=”<<x<<endl;
}
};
Now you can declare a pointer that contains address of the base class object as shown
below:
Base *ptr; // declare a pointer of base class
Base B1; // declare an object of base class
Ptr = &B1; // assign address of object to base class pointer
Using this pointer you can access members of the base class as shown below:
ptr->x = 10;
ptr->display ();
8
Public:
int y;
Void display ();
{
cout<<”X=”<<x<<endl;
cout<<”Y=”<<y<<endl;
}
};
C++ allows you to assign the address of the derived class object to the base class
pointer as shown below:
Derive D1; // declare an object of derived class
ptr = &D1; // assign address of derive class object to base class pointer.
Now if you try to access the member of derived class using base class pointer it will
not allow you to access the member of derived class as shown below:
ptr->y = 20; // It will generate an error
ptr ->display (); // It will invoke the display () of base class
Thus to overcome this problem you have to declare a pointer of derived class and
then assign the address of derived class object to this pointer as shown below:
Derive *ptr1;
Derive D1;
*ptr1 = &D1;
ptr1->y = 20;
ptr1->display (); // it will invoke the display () of derived class.
Thus in order to access member of particular class you need to create a pointer of
that class and then assign the address of that class object to the pointer.
Output:
X= 10
X = 10
Y = 20
Arrays and its characteristics
Synopsis
1. Introduction
2. Definition for Arrays:
3. Array Declaration
4. Syntax for arrays
5. Example for Arrays:
6. Types of Arrays:
One Dimensional Array
Two Dimensional Array
Multi-Dimensional Array
7.Characteristics of Array
Introduction
Array is a fixed size collection of similar data type items.
Arrays are used to store and access group of data of same data type.
Arrays can of any data type.
Arrays must have constant size.
Continuous memory locations are used to store array.
It is an aggregate data type that lets you access multiple variables through a single
name by use of an index.
Array index always starts with 0.
10
Definition for Arrays:
Array is a collection of similar data type items.
An array is a collection of similar data type value in a single variable.
It is a derived data type in C++, which is constructed from fundamental data type of
C++ language.
Array Declaration
To declare an array in C++ required type of array elements and size of array.
Array declaration
int age [5];
Array initialization
int age[5]={0, 1, 2, 3, 4, 5};
Accessing array
age[0]; /*0_is_accessed*/
age[1]; /*1_is_accessed*/
age[2]; /*2_is_accessed*/
11
Syntax
Data_type array_Name [rows_size][column_size];
Array declaration
int arr[2][2];
Array initialization
int arr[2][2] = {{1,2}, {3,4}};
Accessing array
arr [0][0] = 1;
arr [0][1] = 2;
arr [1][0] = 3;
arr [1][1] = 4;
3 Multi-Dimensional Arrays
C++ programming language allows programmer to create arrays of arrays known as
multidimensional arrays.
A list of items can be given one variable name using more than two subscript and such
a variable is called Multi-dimensional arrays
Syntax
Data_type array_Name [s1][s2][s3]…..[sm];
For example:
Int survey [3][5][12];
Float table [5][4][5][3];
Pointer to an array
An array name is a constant pointer to the first element of the array.
Therefore, in the declaration:
Double *p;
Double balance [10];
p = balance;
Advantage of array
Code Optimization: Less code is required, one variable can store large numbers of value easily
with single name.
Easy to traverse data: By using array easily retrieve the data of array.
Easy to sort data: Easily short the data using swapping technique
Random Access: With the help of array index you can randomly access any elements from array.
Disadvantage of array
Fixed Size: Whatever size, we define at the time of declaration of array, we cannot change their size,
if you need more memory in that time you cannot increase memory size, and if you need less memory
in that case also wastage of memory.
Characteristics of Array
Store large number of values with single name
The values store in the array can sorted easily
Searching process can be applied on array easily
It can be used to implement other data struture like stacks, queues, trees, linked list etc
12
Continuous memory locations
Used for random access
Array can be used to process many values easily and quickly
Array of Classes
Synopsis
1. Introduction
2. Declaration of Array of Classes
3. Example program
Introduction
We know that array is a collection of similar data types.
In the same way, we can also define array of classes.
In such type of array, every element is of class type.
In the above example, st[3] is an array of three elements containing three objects of
Class stud.
Each element of st[3] has its own set class member variables i.e., char name[12],
int rollno and char grade[2].
Example program
#include<iostream.h>
#include<conio.h>
Class number
{
public: int num;
void input( )
{
cin >> num;
}
void display( )
{
cout << num;
}
};
void main( )
{
13
clrscr( );
cout <<"\n\n\n";
Number n [10];
for (int i=0; i<3;i++)
{
n[i].input ( );
n[i].display ( );
}
getch( );
}
Memory Models
Synopsis
1. Introduction
2. Memory Organization
3. Table for representing properties of memory models
4. Properties of memory models
Tiny, Small, Medium, Compact, Large, Huge
5. Program to obtain segment and offset address:
6. Keywords
7. Keyword details in table format
8. Program to declare far, near and huge pointers. Display their sizes.
Introduction
The memory model sets the supportable size of code and data areas as shown in figure
below.
Memory Organization
Before compiling and linking the source code, we need to specify the appropriate
memory model.
Using memory models, we can set the size limits of the data and code.
C/ C++ programs always use different segments of code and data.
The memory model we opt decides the default method of memory addressing.
The default memory model is small.
14
3 Medium 1 MB 64K Far Near
4 Compact 64K 1 MB Near Far
5 Large 1 MB 1 MB Far Far
6 Huge 1 MB 64 K EACH 64 K STACK Far Far
1. Tiny:-
Use this model when memory is at an absolute premium.
All four segments (cs, ds, es, ss) are initialized with same address and all addressing
is accomplished using 16 bits.
Total capacity in this case is 64k bytes Programs are executed quickly near
pointers are always used.
Programs can be converted to .com format.
2. Small:-
All code should fit in a single 64kb segment and
All data should fit in a second 64kb segment.
All pointers are 16 bits in length.
Execution speed is same as tiny model.
Used in average size programs.
Near pointer are always used.
3. Medium:-
All data should fit in a single 64kb segments.
*The code is allowed to use multiple segments.
All pointers to data are 16 bits, jumps & call need 32 bits.
Access to data is fast.
Slower program execution.
Far pointers are used for code but not for data.
4. Compact:-
All code should fit in 64kb segment but the data can use multiple segments.
NO data item can surpass 64kb.
All pointers to data are 32 bits, jumps and call use 16bit.
Slow access to data and quick code execution.
5. Large:-
Both code and data are allowed to use multiple segments.
All pointers are 32 bits in length.
NO single data item can exceed 64kb, code execution is slower.
Preferred for very big programs only.
Far pointers are used for both code and data, both 1MB All functions and data
pointers are far by default.
6. Huge:-
Both code and data are allowed to use multiple segment.
15
Every pointer is of 32 bits in length.
Code execution is the slowest.
Preferred for very big programs only.
Far pointers are used for both code and data.
#include<dos.h>
#include<iostream.h>
#include<constream.h>
void main( )
{
int ch;
cout<<”\n complete address of ch:”<<&ch;
cout<<”\n segment address :”<<hex<<FP_SEG(&ch);
cout<<”\n offset address:”<<hex<<FP_OFF(&ch);
}
Output:
Complete address of ch: 0*8F4FFF2
Segment address: 8F34
Offset address :FFF2
Keywords
16
Keyword details in table format
Program to declare far, near and huge pointers. Display their sizes.
#include <iostream.h>
#include<constream.h>
void main( )
{
char far *f; // far pointer declaration
char near *n; //near pointer declaration
char huge *n; //huge pointer declaration
cout<<”\n size of far pointer :”<< size of(f);
cout<<”\n size of near pointer :”<<size of(n);
cout<<”\n size of huge pointer :”<<size of(n);
}
Output:
Size of far pointer:4
Size of near pointer:2
Size of huge pointer:4
Output: W
This expression in the above program returns a pointer to a section of memory just large
enough to hold the num number of floating-point data.
delete [ ] ptr;
int main()
{
int num;
cout << "Enter total number of students: ";
cin >> num;
float *ptr;
// memory allocation of num number of floats
ptr = new float[num];
return 0;
}
Output
Enter total number of students: 4
Enter GPA of students.
Student1: 3.6
Student2: 3.1
Student3: 3.9
Student4: 2.9
19
Dynamic object- Binding, Polymorphism and Virtual Functions
Synopsis
1. Introduction
2. Polymorphism
3. Real life example of Polymorphism
4. Type of Polymorphism
5. Static polymorphism
6. dynamic polymorphism
7. Binding
8. Static Binding
9. dynamic Binding
10. Virtual functions
11. Using Virtual Keyword Example
Introduction
Early binding and Late binding in C++
Binding refers to the process of converting identifiers (such as variable and performance
names) into addresses.
Binding is done for each variable and functions.
For functions, it means that matching the call with the right function definition by the
compiler.
It takes place either at compile time or at runtime.
Types of binding
2 types
1. Early binding (static or compile time)
2. Late binding (dynamic or runtime)
// CPP Program to illustrate early binding. Any normal function call (without virtual)
is binded early. Here we have taken base and derived class example so that readers
can easily compare and see difference in outputs.
#include<iostream>
using namespace std;
class Base
{
public:
void show()
{
cout<<" In Base \n";
20
}
};
class Derived: public Base
{
public:
void show()
{
cout<<"In Derived \n";
}
};
int main(void)
{
Base *bp = new Derived;
// The function call decided at compile time (compiler sees type of pointer and calls
base class function.
bp->show();
return 0;
}
Output:
In Base
Output:
In Derived
Polymorphism
22
Suppose if you are in class room that time you behave like a student, when you are in
market at that time you behave like a customer, when you at your home at that time you
behave like a son or daughter, Here one person have different-different behaviors.
Type of Polymorphism
Static polymorphism
Static polymorphism is also known as early binding and compile-time
polymorphism.
In static polymorphism memory will be allocated at compile-time.
Consist of two types
o Function overloading
Refer previous notes
o Operator overloading
Refer previous notes
Dynamic polymorphism
Dynamic polymorphism is also known as late binding and run-time polymorphism.
In dynamic polymorphism memory will be allocated at run-time.
It consist of one type
Binding
Binding refers to the process which is used for converting functions and variables into
machine language addresses.
Dynamic binding is the method of linking a procedure call to the relevant code that will be
executed only at run time.
Consist of two types
o Static binding
o dynamic binding
Static (Early)Binding
Even though similar function names are used at many places, but during their
References their position is indicated explicitly.
Their ambiguities are fixed at compile time.
Dynamic (Late) Binding
23
In some programs, it is not possible to know which function will be called until
Runtime (when the program is run).
This is known as late binding (or dynamic binding).
Virtual functions
Refer previous notes
A virtual function is a member function that is declared as virtual within a base class
and redefined by a derived class.
To create virtual function, precede the base version of function’s declaration with the
keyword virtual.
Here we use a pointer to the base class to refer to all the derived objects.
The method name and type signature should be same for both base and derived version of
function.
24