Monday, 6 May 2013

Object Pointers in Virtual functions


Object Pointers:
Just like any ordinary pointer of any primitive data type, we may have object pointers that point to some object.

Example:
#include<iostream.h>
#include<conio.h>
class complex
{
      private:
              int a,b;
      public:
             void getdata()
             {
                  cout<<"Enter real and img part";
                  cin>>a>>b;
             }
             void show()
             {
                  cout<<"\na="<<a<<" b="<<b;
             }
};
int main()
{
     complex c1;
     complex *ptr;
     ptr=&c1;
     ptr->getdata();
     ptr->show();
     getch();
}

In the above example,
l  We created an object of type complex and also declared a pointer of type complex. Name of pointer is ptr which is object pointer as it can point to an object of type complex.
l  Pointer ptr stores address of object c1.
l  When ever members of object are accessed using object name we need to use dot (.) operator, but if members are to be accessed through pointer name we need to use arrow (->) operator.
l  In the line ptr->getdata(), function getdata() will work for the object pointed to by ptr.

No comments:

Post a Comment