Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Object Oriented Programming and C++

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

OBJECT ORIENTED PROGRAMMING AND C++

UNIT

IV

CONTENTS

Pointers


Pointer Declaration

Pointer to class

Pointer to object

this pointer

Pointer to derived classes and base classes

Arrays


Array of classes

Memory models


new and delete operators

Dynamic objects

Binding, polymorphism and virtual functions

POINTERS
Pointer Declaration
Pointer is a variable which is used to store the address of a memory location. The
data in a memory location can be accessed using the variable name as well as using
its memory address. Memory is arranged in series of bytes and these bytes are
numbered from zero onwards. It is possible to access and display the address of
memory location assigned to a variable, using & operator. The operator & is also
called as address operator, since it is used to get the address of a memory
location. Using pointer a data can be accessed quickly. Pointer can be used to store
the address of variable of basic data types like int, float, double and user defined
data type like object. The pointer variable is declared using the following syntax.
Data type *p;
Where data type may be a basic data type of user
defined data type
When pointers are used, the contents pointed by the pointers are accessed using the
operator *. The operator * is also called as indirection operator. When pointers
are used for objects, the members of the object are accessed using -> operator.
The operator -> is also called as arrow operator, which is a combination of the
symbols - and >. However, the private members cannot be accessed even using
the pointer.
The following program illustrates the use of pointer.
P58.CPP
//PROGRAM USING POINTER TO VARIABLE
#include<iostream.h>
#include<conio.h>
void main()
{ int a, *p;
clrscr();
cout<<"\nEnter a no : ";
cin>>a;
p=&a;
cout<<"\nvalue = "<<*p<<" Address = "<<(unsigned)p;
getch();
}
P58.OUTPUT
Enter a no : 5
value = 5 Address = 65524

Pointer to class and object


As mentioned earlier, pointers can be used to store address of variables as well user
defined data types like objects. When pointers are used for objects, the members of
the objects can be accessed using -> operator or * operator. The syntax of
accessing members of objects using pointer variable is given below.
p->member name
(or)
(*p).member name
Where p is a pointer variable to an object

The pointer for an object should be declared using the following syntax.

Class_name *Pointer_variable;

The address of an object can be accessed using the & operator with the following
syntax.
Pointer_to_object = &object_name;

The following program illustrates the use of pointers to objects.


P59.CPP
//PROGRAM USING POINTER TO OBJECT
#include<iostream.h>
#include<conio.h>
class stud
{ public:
char name[20];
int roll;
};
void main()
{ stud s={"Ashok",12};
stud *p;
p=&s;
//p=&(stud)s;
clrscr();
cout<<"\nName = "<<p->name<<"\nRoll no = "<<(*p).roll;
getch();
}

P59.OUTPUT
Name = Ashok
Roll no = 12

this pointer
C++ provides a special type of pointer called this pointer, which is used to point an
object. this is a local variable of pointer to object type, which is available in all nonstatic member functions in a class. When a member function of an object is called,
the this pointer of that function point to the calling object. The following program
illustrates the use of this pointer.
P60.CPP
//PROGRAM USING this POINTER
#include<iostream.h>
#include<conio.h>
class number
{ int num;
public:
void get()
{ cout<<"\nEnter a number : ";
cin>>num;
}
void show()
{ cout<<"\nMinimum number : "<<num;
}
number min(number t)
{ if(t.num<num)
return t;
else
return *this;
}
};
void main()
{ clrscr();
number n,n1,n2;
n1.get();
n2.get();
n=n1.min(n2);
n.show();
getch();
}
P60.OUTPUT
Enter a number : 100
Enter a number : 200
Minimum number : 100

In the above program the statement n=n1.min(n2) is used to call min member
function of n1 object. The this pointer point to the calling object n1 and returns the
object n1, which is copied to n object. The n objects show function is called which
displays its num value 100, as the minimum number.

Pointer to derived classes and base classes


Pointers can be used to point base class as well as derived class. Pointers can be
declared as base class type or derived class type. Pointers can be used to point both
base class object and derived class object. If the pointer is declared as base class
type, then, only the members of base class can be accessed, using that pointer. Even
though the object is declared as derived class type, the pointer can point only the
base class members, if the pointer is base class type. But the derived class members
can be accessed using base class pointer, if the base class members are declared as
virtual. The concept of virtual function is discussed in later topic. If the pointer is
declared as derived class type, then it can be used to point the members of derived
class object.
P61.CPP

//PROGRAM USING POINTERS TO BASE AND DERIVED CLASSES


#include<iostream.h>
#include<conio.h>
class B
{ public:
int b;
void show()
{b=100;
cout<<"\nb = "<<b;
}
};
class D: public B
{ public:
int d;
void show()
{d=200;
cout<<"\nd = "<<d;
}
};
void main()
{ clrscr();
B *p; //base class pointer
B base; //base class object
p=&base;
p->show();
D deri; //derived class object
p=&deri;
p->show();
D *q; //derived class pointer
q=&deri;

q->B::show();// to access base class member


(*q).show();//another way of using pointer
getch();
}

P61.OUTPUT
b = 100
b = 100
d = 100
d = 200
In the above program, the function show is defined in both base and derived
classes. When base class pointer is used to point base class object, the statement
p->show() calls the base class show function. When the base class pointer is used to
point the derived class object, the statement p->shows() calls only the base class
show function. When derived class pointer is used to point the derived class object,
the statement (*q).show (same as q->show) calls the derived class show function.
But with the same pointer, the base class show function can be called by using scope
resolution operator and base class name as in the statement q->B::show().

Arrays
Array is a collection of elements of similar data type. It shares a common name and
each element in an array can be accessed using the subscript or index value. Like C,
the arrays in C++ also start with the subscript 0.

Array of classes
Arrays can be used to store elements of similar basic data types like int, float,
double, char, etc. We can also use array to store user defined data type elements,
like object, which is called as array of objects. The individual object in an array of
objects can be accessed using the subscript. The following program prints whether
the number is positive or negative, using array of objects.
P62.CPP
//PROGRAM USING ARRAY OF OBJECTS
#include<iostream.h>
#include<conio.h>
class arob
{ int n;
public:
void pn()
{ cout<<"\nEnter a no : ";
cin>>n;
if(n<0)
cout<<"Negative";
else
cout<<"Positive";
}
};

void main()
{ clrscr();
arob a[5];
for(int i=0;i<5;i++)
a[i].pn();
getch();
}

P62.OUTPUT
Enter a no
Positive
Enter a no
Negative
Enter a no
Positive
Enter a no
Negative
Enter a no
Positive

: 100
: -50
: 200
: -75
: 350

Memory Models
One of the valuable resources in a computer system is memory. There are different
types of memory models in C++, based on the size allocated for program or data.
The default memory model is small. We can set the size for memory allocated to
code and data based on the memory model.

CODE SEGMENT

DATA SEGMENT

STACK SEGMENT

EXTRA SEGMENT

During the execution of a program, the program from the hard disk is loaded into
RAM. RAM is divided into 4 segments namely,
1. Code Segment
2. Data Segment
3. Stack Segment
4. Extra Segment

Code segment is used to hold the program or code. Similarly, data segment is used
to hold data (input and output) related to the program. Stack segment is used to
hold data during the evaluation of arithmetic expressions and to store return
addresses during the execution of functions. Extra segment is used by the compiler
when it is needed.

Normally the size of a segment is about 64KB. Depending on the memory model, the
program and data can use one or more segments and the size of the memory
occupied will vary, therefore. The content in code, data, stack and extra segment can
be accessed using CS, DS, SS and EX registers, respectively. The various types of
memory models are discussed in the below section.
MEMORY MODEL

CODE

Tiny

SEGMENTS
DATA

STACK

64 KB

Small

64 KB

64 KB

Medium

1 MB

64 KB

Compact

64 KB

1 MB

Large

1 MB

1 MB

Huge

1 MB

64 KB

64 KB

1) Tiny
The total memory capacity is 64 KB and code, data and stack should share this
single segment. This memory model can be selected if code and data are small.
Programs are executed quickly in this model.
2) Small
In this model, code can use a single segment of 64 KB. Another segment of 64 KB
can be shared by data and stack. Execution speed of the program is the same as tiny
model.
3) Medium
Data and stack can share a single segment of 64 KB in this model. But code can
have multiple segments and it can avail a memory of size 1 MB. Program execution
is slower in this model. This model is suitable when the program size is large and the
data size is small.
4) Compact
In this all code should fit in a single segment of 64 KB. But data and stack can have
multiple segments and can avail a memory of size 1MB. This model is suitable for
smaller program which uses large amount of data.

5) Large
In this model, both code and data are allowed to use multiple segments and can
avail a memory of size 1 MB. Program execution is slower in this model. This model
is preferred for very big programs only.
6) Huge
In this model, code can use multiple segments and can avail memory of size 1 MB.
Data and stack can use a segment of 64 KB, each. This model is preferred for very
big programs only. Program execution is slower in this model.

new and delete operators


C++ provides another two additional operators namely, new and delete. These two
operators are used for using the memory effectively. Even though new and delete
looks like keywords, they are operators like sizeof. The new operator not only
creates an object but also allocates memory. This operator allocates correct amount
of memory needed and hence no memory is wasted. The object created and memory
allocated using new operator should be deleted using delete operator. The delete
operator not only destroys object but also releases the memory allocated.
The functions malloc() and free(), used in C are for individual data. But new and
delete operators are suitable for objects. Another difference between new operator
and malloc function is that, new operator can be overloaded, whereas malloc cannot
be. The following program uses new operator for allocating memory to store
elements of basic data type, say of integer type.
P63.CPP
//PROGRAM USING NEW OPERATOR TO STORE INTEGERS
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
int *p;
p=new int[3];
*p=1;
*(p+1)=2;
*(p+2)=3;
for(int i=0;i<3;i++)
cout<<"\nValue = "<<*(p+i)<<" Address = "<<(unsigned)(p+i);
delete []p;
getch();
}

P63.OUTPUT
Value = 1 Address = 3520
Value = 2 Address = 3522
Value = 3 Address = 3524

Dynamic objects
Normally objects are created during compilation time. But we can also create objects
during the execution time or run time. Such objects are called as dynamic objects.
Dynamic object can be created using new operator and can be pointed by pointer to
that object. Since pointer is used to access the object, object name need not be
specified in the program. The following program illustrates how dynamic objects can
be created.
P64.CPP
//PROGRAM USING DYNAMIC OBJECTS
#include<iostream.h>
#include<conio.h>
class num
{ int x;
public:
num()
{ x=100;
}
void show()
{cout<<"\nx = "<<x;
}
};
void main()
{ num *p;
clrscr();
p=new num;
p->show();
delete p;
getch();
}

P64.OUTPUT
x = 100
In the above program, an object is created dynamically, of the type num. The object
is pointed by the pointer p. Using the pointer the member function show is accessed
which displays 100 as output.

Binding, Polymorphism and Virtual functions


We can use the name of a member function of base class to a member function of
derived class also. During the compilation time, the compiler will link the appropriate
member function to the call to the member function. This is called as early binding
or static binding.

Consider a situation in which the base class and the derived class are having
member functions with the same name. We use a pointer of base class type to point
a derived class object. If we call the member function of an object of derived class
type, the member function of base class will be executed. We can override the
member function of base class and we can execute the member function of derived
class. This can be done by declaring the base class member function as virtual.
When a base class function is declared as virtual, it will be overridden when we use
base class pointer to point derived class object. The selection or linking of derived
class function is done during the run time. This is called as late binding or dynamic
binding. This process of selecting member function is called as run time
polymorphism.

The following program illustrates the function of virtual functions.


P65.CPP

//PROGRAM USING VIRTUAL FUNCTION


#include<iostream.h>
#include<conio.h>
class B
{ public:
virtual void show()
{ cout<<"\nBASE";
}
};
class D: public B
{ public:
void show()
{ cout<<"\nDERIVED";
}
};
void main()
{ clrscr();
B *p;
B base;
p=&base;
p->show();
D deri;
p=&deri;
p->show();
getch();
}

P65.OUTPUT

BASE
DERIVED
In the above program, the first p->show statement will execute the show function of
base class, since the pointer p points to the base class object. Similarly, when the
second p->show statement is executed, the member function of base class will be
executed normally, since the pointer is base class type. But, since the base class
function is declared as virtual, it was overridden and the show function of derived
class is executed.

You might also like