Structure instance creation using pointer based notation – Computer Sir Ki Class

Code Learning #CPP#2911

Structure instance creation using pointer based notation

A system of creating structure instances using pointer based notation or the method indicating the address location of the structure.

Learning Objectives

• Using the two varieties of pointer notation for declaring the structure instances.

Source Code

 #include using namespace std; struct Date { int day; int month; int year; }; int main() { Date *d1=new Date(); Date *d2,d; d2=&d; d1->day=11;d1->month=11;d1->year=2011; d2->day=12;d2->month=12;d2->year=2012; cout<<"Date 1= "<day<<"-" <month<<"-" <year<month<<"-" <year<

Run Output

``````Date 1= 11-11-2011
Date 2= 12-12-2012
``````

Code Understanding

struct Date { int day; int month; int year;};
Three integer variables day, month and year are declared in this structure.

Date *d1=new Date();
This is the pointer based declaration with *d1 marked as location of structure and new Date() on the right side completes the instance creation like a constructor is called.

Date *d2,d; d2=&d;
This is another style where *d2 has been declared along with an instance d. Then d2=&d completes the instance creation as the address of d is assigned  to the pointer. This actually creates two instances pointing to same location d2 and d.

d1->day=11;d1->month=11;d1->year=2011;
using the -> type of symbol the pointer type structure instance is accessed. This way we can read or write the instance variable based on the type of variable.

d2->day=12;d2->month=12;d2->year=2012;
Since d2 is also a pointer type for structure we shall again use the -> operator to access its variables.

cout<<“Date 1= “<<d1->day<<“-“<<d1->month<<“-“<<d1->year<<endl;
The address d1 to structure is being printed here again by -> notation.

cout<<“Date 2= “<<d.day<<“-“<<d2->month<<“-“<<d2->year<<endl;
In this printing there is a variation since structure instance d is a normal instance it has been accessed using the . operator as d.day and other instance d2 is a pointer notation is they are accessed using -> operator.

Notes

• Pointer to structures can serve a useful purpose while passing structure to a function as a reference.

Common Errors

• If a structure pointer only is declared, then the instance is not created unless it gets the address value assignment to an instance.

Suggested Filename(s): strupnt.cpp

sunmitra| Created: 22-Jan-2018 | Updated: 22-Jan-2018|

×