pointers to objectspassing and returning of


Pointers to Objects

Passing and returning of objects is, though, not very efficient since it includes passing and returning a copy of the data members. This problem can be eliminated using pointers. Like other variables, objects of class can also have pointers. Declaring a pointer to an object of a certain class is same as declaring a pointer to a variable of any other data type. A pointer variable having the address of an object is said to be pointing to that object. Pointers to objects can be used to make a call by address or for dynamic memory allocation. Just like structure pointer, a pointer to an object also uses the arrow operator to access its members. Like pointers to other data types, a pointer to an object also has only one word of memory. It has to be made to point to an already existing object or allocated memory using the keyword 'new'.

e.g.

                string str;             // Object

                string *sp;           // Pointer to an object

                sp = &str;             // Assigns address of an existing object

                sp = new string // Allocates memory with new.

A simple example of using pointers to objects is given below.

                class player

                 {

                  public :

                                                void getstats(void);

                                                void showstats(void);

                  private :                                                            

                                                char  name[40];

                                                int   age;

                                                int   runs;

                                                int   tests;

                                                float average;

                                     float calcaverage(void);

                };

 void main()

                  {

                    player Sachin;

                                Sachin.getstats();

                                Sachin.showstats();

                  player  *Dravid;

                                Dravid = new player;

 

                                Dravid->getstats();

                                Dravid->showstats();

                  }

 

Request for Solution File

Ask an Expert for Answer!!
C/C++ Programming: pointers to objectspassing and returning of
Reference No:- TGS0309364

Expected delivery within 24 Hours