Structures in C++


Structures in C++ are user defined data type that can contain multiple variables  of different data types. They can also contain member functions.

Functions in structures are public by default.

Structure declaration example :
 struct Dog {  
  int age;  
  char name[50];  
  char owner[100];  
  string type;  
 };  

Here structure is Dog with entries age, name , owner and type.


To create structure variables d1 and d2,

 struct Dog d1;  
 struct Dog d2;  

Accessing variable values :

 strcpy(d1.name, "Shera");  
 strcpy(d2.name, "Jimmy");  
 d1.type = "Labrador";  

Structures can be used as any other variables to pass to other functions and to create structure pointers:
 void myfunction(struct Dog d) {} // function with structure as argument  
 struct Dog d1;  
 struct Dog * dp; // structure pointer  
 dp = &d1;  

Typedef can be used to avoid writing struct while creating variables, such as:
 typedef struct {   
 .  
 .  
 .   
 }Dog;  
 Dog d1;  

Comments

Popular posts from this blog

In Place Algorithms

References in C++