Wednesday, March 7, 2012

How to declare/access the pointer variable inside the class in C++?

             Declaring the pointer variable inside the class is similar to normal C declaration only. While allocating the memory and access the variable will differ. It will be good to have a memory allocation in constructor and deallocation in destructor. See the sample code below for more clarity.

            In the below sample code, there is class ptr with one integer data member i and one integer pointer data member p. These are initialised in constructor using new for pointer variable. In destructor used delete for freeing the dynamic memory. For accessing the pointer data using the instance P and O as saind in main().

     *P->p gives the value of the variable and not P->*p. Where as P->p gives the address of the pointer variable. Similarly for object O, *O.p  gives the value of the variable and not O.*p. Where as O.p gives the address of the pointer variable.

using namespace std;

class ptr
{
    public:
        int i;
        int *p;
        ptr();
        ~ptr();
};

ptr::ptr()  // constructor
{
    i=10;
    p=new int;
    *p = 20;
}
ptr::~ptr() //destructor
{
    delete p;
}
int main()
{
    ptr *P=new ptr(); //dynamic instance

    cout<<"P->i is "<<P->i<<endl;  //accessing normal variable
    cout<<"P->p is "<<P->p<<endl;  // will get address of the poitner variable
    cout<<"*P->p is "<<*P->p<<endl; // accessing the pointer variable. P->*p is a invalid expression

    ptr O; //static instance

    cout<<"O.i is "<<O.i<<endl; //accessing normal int variable
    cout<<"O.p is "<<O.p<<endl; // will get the address of the int pointer
    cout<<"*O.p is "<<*O.p<<endl; //accessing the poiner variable. O.*p is a invalid expression
}


Output:

P->i is 10

P->p is 0xfda4030
*P->p is 20

O.i is 10
O.p is 0xfda4050
*O.p is 20

No comments:

Popular Posts