C++ 08 – Structs

A lot of the variables we use in our programs are related. For example, the two coordinates of a 2D vector, or a pointer pointing to an array and the size of said array. It would be useful if we could define types that consist of several variables grouped together.

In C++ and other languages, this can be achieved through the use of structs. In this lesson we will see how and why structs are used.

Defining structs

struct struct_name{
     member_type1 member_name1;
     ...
     member_typeN member_nameN;
};

You can see the general form of a struct definition above. As an example you can see a definition for a 2D vector below:

struct vector2d {
    float x,y;
};

vector2d is the name of the struct and x,y are member variables.

Using structs

Structs are types in almost all ways. You can use a vector2d from above, just like you use a double or an int. To access the member variables you use the ‘.’ operator:

vector2d v1, v2;
v1.x = 5; v1.y = 10;
v2.x = 7; v2.y = 3;
v1.x = v1.x + v2.x;
std::cout << v1.x << "\n";

In the example above we declared and used a vector2d instance.You can also dynamically allocate a vector2d instance like any other type. To access a member through a pointer you can use the ‘->’ operator, which is equivelant to ‘*().’ – dereference followed by ‘.’ operator :

vector2d * v1 = new vector2d;
std::cout << v1->x << "\n";
std::cout << *(v1).x << "\n";

Since structs are types, you can imagine how you can use arrays of structs:

vector2d * v1 = new vector2d[100];
std::cout << v1[10].x << "\n";

vector2d v2[100];
std::cout << v2[10].x << "\n";

Notice that even if v1 is a pointer, we don’t use the ‘->’, we use dot. This is of course because v1[10] is of type ‘vector2d’, not ‘vector2d *’, the dereference is the ‘[]’ operation

You can initialize structs by providing the values inside {}. Like this:

vector2d v1 = {10,12};
std::cout << v1.x << "\n";

Passing structs to functions is analogous to any other type:

void print_vector(vector2d v){
    std::cout << v.x << "," << v.y << "\n"; 
} 

void increment_vector(vector2d * v){ 
   v->x++;
   v->y++;
}

int main(){
   vector2d v1 = {5,5};
   print_vector(v1);
   increment_vector(&v1);
   print_vector(v1);

   return 0;
}

Final words

We saw how we can group variables together. This is very useful for organizing our code and programs. A closely related feature of C++ and also the basis of Object-Oriented Programming is classes that we will see more in depth on the next post.

You can download the updated version of our game, organizing game data in structs.

08-structs

Author: lefteris_33ss8812

Lefteris is a Co-Founder and CTO over at HAM Systems. He has wide experience in electrical engineering including electronics and embedded systems, mobile, web services and video games development.

Leave a Reply

Your email address will not be published. Required fields are marked *