Often we come across a scenario where we need to group together many variables or functions into a single object. In order to do so, we need to define our own custom data type or “Structures” as we call them in C++ and C.


What are C++ Structures?

In simple words, Structs allow us to take variables of same, or even different types, and create a new, user-defined data-type with a custom name. You can then create new variables using this custom datatype.

After defining a variable using the Struct name, you can then access each of the variables or functions that you defined in it.

Structures are actually mainly used in C, having been replaced almost entirely in C++ by Classes instead. Of course, that doesn’t change what they are capable of, and it’s still important to know about structs and how to use them effectively.

Note: There are significant differences in C structs and C++ structs. As C++ is an OOP language, C++ struct has several OOP properties that are not present in C structs, such as having functions as members, constructors and destructors, and Inheritance.


Defining a C++ Structure (Examples)

Now let’s define a simple struct, and perform some basic operations on it such as accessing it’s members. Members of a struct, refer to the variables and functions that are contained inside of it.

In the example below we have created a simple struct with variables of three different datatypes.

struct Person {
    string name;
    int age;
    char gender;
};

Using a single struct is much more efficient than using three separate variables to store information about a single person.

Now let’s try to create an object out of this struct, store some data in it and then print them out.

#include <iostream>
using namespace std;

struct Person {
    string name;
    int age;
    char gender;
};

int main() {
    struct Person p1;

    p1.age = 15;
    p1.name = "Bob";
    p1.gender = 'M';

    cout << p1.age << " - ";
    cout << p1.name << " - ";
    cout << p1.gender;
}

This is the first method through which you can create a struct and store some values in it. Let’s explore some alternate methods.

int main() {
    Person p1;
    // ...
    // ...
}

You don’t have to use the “struct” keyword when declaring the variable if you are doing this in C++. In C however, not including the struct keyword would give an error. Using struct works both on C++ and C, so it’s good for compatibility if that matters to you.

int main() {
    Person p1 = { "Bob", 15, 'M' };

    cout << p1.age << " - ";
    cout << p1.name << " - ";
    cout << p1.gender;
}

Here is an alternate way of initializing a struct with some values. It’s nice and concise, fitting everything on a single line. It’s a little tricky however, as you need to pass in values in the same order that the variables were declared.

So if “name” was declared first, then “Bob” needs to be the first parameter.


Defining Functions in C++ Structures

Now let’s try and add a simple function into our struct! Contrary to what many expect, (especially people who don’t have a background in C++) structs can also hold functions in the same way that Classes can.

Let’s try and make a print function for our struct, that prints out all the information about a person. This much things much easier, especially if we want to display the details of several people.

#include <iostream>
using namespace std;

struct Person {
    string name;
    int age;
    char gender;

    void print() {
        cout << age << " - ";
        cout << name << " - ";
        cout << gender;
    }
};

int main() {
    Person p1 = { "Bob", 15, 'M' };
    Person p2 = { "Janet", 17, 'F' };

    p1.print();
    p2.print();
}

The above code prints out the following:

15 - Bob - M
17 - Janet - F

For more examples on using Functions with Structs, check out our tutorial for using functions in C++ structures.


Inheritance in Structures

Let’s take a quick look at inheritance in Structs now. If you are familiar with Inheritance in Classes, then know that this is the exact same thing. There aren’t many differences between Structs and Classes, except in this case there are two differences we need to keep in mind.

First, by default all the member variables in a struct are public by default. Secondly, the default inheritance type is public by default as well.

In the example below, we are further continuing our example by creating a Child Class called Student. Remember, that Classes need to make sense. It doesn’t make logical sense to have a Class called “Dog” inherit from “Human” right? But it makes sense for both “Dog” and “Human” to inherit from “Mammal” or “Entity”.

Hence, in the below example we have inherited “Student” from “Person”, as a Student is a Person as well, but also has unique variables and functions that are not available (neither are they meant to be) in Person.

#include <iostream>
using namespace std;

struct Person {
    string name;
    int age;
    char gender;

    void print() {
        cout << age << " - ";
        cout << name << " - ";
        cout << gender << endl;
    }
};

struct Student : Person {
    int RollNo;
    string department;
};

int main() {
    Student s1 = {"Bob", 15, 'M', 146, "IT"};

    s1.print();
}

An interesting thing to note in the above example, is how the structs are initialized. Even though Student only has two variables, we pass 5 values into the initializer list. This is of course, because it has inherited 3 variables from it’s parent. Also remember to pass them in the same order that they were declared.

Here’s another interesting example where we created a Constructor in the struct.

#include <iostream>
using namespace std;

struct Person {
    string name;
    int age;
    char gender;

    void print() {
        cout << age << " - ";
        cout << name << " - ";
        cout << gender << endl;
    }
};

struct Student : Person {
    int RollNo;
    string department;

    Student(string name, int age, char gender, int roll, string dept) {
        this->name = name;
        this->age = age;
        this->gender = gender;
        this->RollNo = roll;
        this->department = dept;
    }
};

int main() {
    Student s1 = { "Bob", 15, 'M', 146, "IT" };
    Student s2 = Student("Janet", 17, 'F', 109, "Medical");

    s1.print();
}

We’ve created two objects here, the first declared through the initializer list, and the second through the constructor.


This marks the end of the Defining Structures in C++ Tutorial. Any suggestions or contributions are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments