Friday 17 April 2015

Pointers to Objects


The allocation and deallocation of memory is done by new and delete operators in C++. A pointer to a variable can be defined to hold the address of an object, which is created statically or dynamically. Such pointer variables can be used to access data or function members of a class using the * or -> operators.

Pointer can be used to hold addresses of objects, just as they can hold addresses of primitives and userdefined data items. The need for using pointers to objects becomes clear when objects are to be created while the program is being executed, which is an instance of dynamic allocation of memory.

The new operator can also be used to obtain the address of the allocated memory area besides allocating storage area to the objects of the given class. The general format for defining a pointer to an object is

Class_name * pointer_to_object


The address operator & can be used to get the address of an object, which is defined statically during the compile time. The general form is as follows.

Pointer_to_object = &Object;

A pointer can be made to point to an existing object, or to a newly created object using new operator. The general form is as follows.

Pointer_to_object = new Class_name


Accessing Members of Objects


As in the case of pointers to structures, there are two approaches to referring and accessing the members of an object whose address resides in a pointer. The expression to access a class member using pointer is as follows:


Pointer_to_Object -> member_name;
                   
                     ( or )

*Pointer_to_Object . member_name



The member can be accessed through the object pointer can be either a data, or function member.


Sample Program

#include <iostream.h>
class de
{
public:
int data1;
char data2;
de(void)
{
cout<<”Constructor”<<endl;
data1 = 1;
data2 = ‘A’;
}
~de()
{
cout<<”Destructor”<<endl;
}
void show(void)
{
cout<<data1<<data2<<endl;
}
};
void main()
{

de *ptr1;
de obj;
ptr1 = &obj;
cout<<”Accessing members through object”<<endl;
obj.show();
cout<<”Accessing members through object pointer”<<endl;
ptr1->show();
}







No comments:

Post a Comment