C++: Structures

Remember our driver’s license example we discussed in an earlier post. A license holds several pieces of information:

License Number: 12345
Name: Arthur Dent
Address: Near Dean Street
Date Of Birth: 03/08/1978

When a structure is mentioned in C++ context, in fact, we are talking about a feature of the language that enables the programmer to create data structures that can represent data grouping like what you would find on a license, library card, price tag for a product, a card game card, etc.


If we want to write C++ code that represents Arthur’s driver’s license we would write:

struct DriversLicense {
	int number;
	string name;
	string address;
	/**
	we'll cover DOB later 
	(hint: think of it as a struct.)
	*/
} MyLicense, YourLicense;

Here is what we did. Using the keyword struct we defined a data structure by the name DriversLicense. Also we defined that this data structure has the following¬†members:¬† number, name, address, and we didn’t implement the DOB field yet (we’ll discuss this later). Finally, we declared two objects named MyLicense and YourLicense.

Here is how we’d use the structure in our main program:

#include 
using namespace std;

struct DriversLicense {
	int number;
	string name;
	string address;
	/**
	DOB
	*/
} MyLicense, YourLicense;

int main()
{
	MyLicense.number = 54321;
	MyLicense.name = "Marvin The Paranoid Android";
	MyLicense.address = "Magrathea";

	YourLicense.number = 12345;
	YourLicense.name = "Arthur Dent";
	YourLicense.address = "Near Dean Street";

	return 0;
}

As you can see in the above code. We have access to two objects that can hold different data but in the same format which is enforced by DriversLicense.

We’ll continue our discussion in the next post [here].

Loading Facebook Comments ...

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>