CPP class pointer doubt

Thread Starter

ep.hobbyiest

Joined Aug 26, 2014
201
Hi,
I m new to cpp. I have doubt in following code. Doubt is regarding pointer. here is code
Code:
// pointer to classes example
#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 << "a area: " << a.area() << endl;
    cout << "*b area: " << b->area() << endl;
    cout << "*c area: " << c->area() << endl;
    cout << "d[0] area: " << d[0].area() << endl;
    cout << "d[1] area: " << d[1].area() << endl;
    delete[] d;
    delete b;
    return 0;
}
from the line
cout << "d[0] area: " << d[0].area() << endl;
cout << "d[1] area: " << d[1].area() << endl;

Here d is array which dynamically allocated. but when we are accessing area() function that time we have to use -> instead of ".". but, we are accessing set_value function using dot operator even though it is pointer.


So, i m confused when to use arrow operator and when to use dot operator.
 

vpoko

Joined Jan 5, 2012
267
When you point to an array, the array's element 0 is at the address the pointer points to, element 1 is at that address plus the size of the pointer (also the size of each element of the array), element 2 is at that address plus twice the size of the pointer, and so on. When you say d->set_values(4,5) on line 24, you are hitting element zero of your array using the equivalent pointer notation (you use the arrow because d is, in fact, a pointer, and the arrow is syntactic sugar for deferencing. You could do the same thing with (*d).set_values(4,5) and not use the arrow). Likewise, you can work with d like an array (C mostly lets you treat a pointer to an array like the array itself, think of the [] as another shortcut for the dereference operator). d[0].set_values(4, 5). Why the dot in this case? Because d[0] is not a pointer, it is a reference to a CRectangle instance. References and pointers are similar but not identical, and one of the differences is that references dereference automatically.
 
Last edited:
Top