Saturday, December 15, 2012

Pointer with classes

Pointer with classes:
                           c++ supports dynamic binding which is one of the powerful features of object oriented programming. To achieve dynamic binding we require virtual functions, which is implemented by concept of pointers with classes and object. Here we discuss concept of pointer, after that we explain virtual function.

1.1 Pointer of objects:
                                Car * santro; (is a pointer to an object of class Car)
as it happened with datastructure, in order to refer directly to a member of an object pointed by a pointer we use the arrow operator (->) of indirection. here is an example with some possible combinations:

//Pointer to classes

#include <iostream>
using namespace std;

class CRectangle
{
    int width, height;

    public:
        void set_values (int, int);
        int area(void)
        {
            return (width * height);
        }
};

void CRectangle::set_values (int a, int b)
{
    width = a;
    height = b;
}

int main()
{
    CRectangle a, *b, *c;
    CRectangle *d = new CRectangle[2];
    b = new CRectangle;
    c = &a;
   
    a.set_values (1, 2);
    b->set_values (3, 4);
    d->set_values (5, 6);
    d[1].set_values (7, 8);
   
    cout << "\n      a area: " << a.area();
    cout << "\n    *b area: " << b->area();
    cout << "\n    *c area: " << c->area();
    cout << "\n d[0] area: " << d[0].area();
    cout << "\n d[1] area: " << d[1].area();
}

No comments:

Post a Comment