Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Use of Pointers in Classes 1

Status
Not open for further replies.

sbarkeruk

Programmer
Jul 9, 2004
1
GB
I am an experienced VB6 developer, aware of object-oriented design, but have just started learning C++ this week! I have hit a brick wall with trying to understand the following snippet of code:

CRectangle a, *b, *c;
CRectangle * d = new CRectangle[2];

I am trying to work out the following:

a) Are *b and *c both pointing to a, or are they pointing to a new instance each (i.e. is 1 instance created or 3)?

b) I understand the use of [2] if this was an array (i.e. 3rd element), but here it is used with a class - CRectangle[2]. What exactly would the '3rd element' be in this case, is it *c (3rd instance) or third parameter of the class prototype/definition??

Thanks in advance,

Simon.
 
a) Both b and c are pointers to CRectange) and a is an object of type CRectangle. It is the same as:
Code:
CRectangle  a;
CRectangle* b; // or *b, (*b) etc...
CRectangle* c;
It's C language inheritance: type declarator of a name like using this name in expression.

b) This is a definition (declaration + initialization) of d variable. Its type is pointer to CRectangle. It's value is a pointer to array of two elements of type CRectangle. Operator new creates this array on the fly in dynamic storage and returns a pointer to it. Now you have d[0] and d[1] elements of type CRectangle. To deallocate this array you must write (and execute) delete []d;

Any occurence of array name in C and C++ (except in sizeof() operation) returns pointer to the 1st element (with index 0). And vice versa: you may treat any pointer as a pointer to an array (of proper type). Index operator [] in C (and C++) means
Code:
 a[x] is the same as *(a+i)

I hope now you can understand this dynamic array creation with access via pointer to its start element...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top