Array of Pointers to objects


#include <iostream.h>
class A
{
        int a1;                    // private data member
    public :
        int a2;                    // public data member

        void set_a1(int);
        void display_a1a2();
};
/*----------------------Class Implementations---------------------*/
// member function definitions for class A
void A::set_a1(int x)
{
    a1 = x;
}
void A::display_a1a2()
{
    cout << "a1 = " << a1 << "\n";
    cout << "a2 = " << a2 << "\n";
}
void main(void)
{
    A obj[5];                // array of objects declaration
    for (int i=0; i<5; i++)    // array of objects initialisation
    {
        obj[i].set_a1(i+1);
        obj[i].a2 = (i+1)*10;
    }
    A *p[5];                // array of pointers to objects - declaration
    for (i=0; i<5; i++) // array of pointers to objects -                                           initialisation
        p[i] = &obj[i];

    for (i=0; i<5; i++)     // usage of array of pointers to objects
    {
        cout << "Object - " << i+1 << ":\n";
        p[i]->display_a1a2();
        cout << "\n";
    }
}

/*
output
Object - 1:
a1 = 1
a2 = 10

Object - 2:
a1 = 2
a2 = 20

Object - 3:
a1 = 3
a2 = 30

Object - 4:
a1 = 4
a2 = 40

Object - 5:
a1 = 5
a2 = 50
*/

0 comments:

Post a Comment

 
 
 
 


Copyright © 2012 http://codeprecisely.blogspot.com. All rights reserved |Term of Use and Policies|