C++: Accessing Struct Members

C++: Accessing Struct Members

We have discussed about struct in the tutorial: How to group related values of different data types in C++. In this tutorial you are going to learn accessing struct members.

Accessing Struct Members:

In arrays, you access a component by using the array name together with the relative position (index) of the component. The array name and index are separated using square brackets. To access a structure member (component), you use the struct variable name together with the member name; these names are separated by a dot (period). The syntax for accessing a struct member is:

The structVariableName.memberName is just like any other variable. For example, newStudent.courseGrade is a variable of type char, newStudent.firstName is a string variable, and so on. As a result, you can do just about anything with struct members that you normally do with variables. You can, for example, use them in assignment statements or input/output (where permitted) statements.

In C++, the dot (.) is an operator called the member access operator.

Suppose you want to initialize the member GPA of newStudent to 0.0. The following statement accomplishes this task:

Similarly, the statements:


store “John” in the member firstName and “Brown” in the member lastName of newStudent.

After the preceding three assignment statements execute, newStudent is as shown below:

struct members

The statement:

reads the next string from the standard input device and stores it in:


The statement:

reads two integer values from the keyboard and stores them in newStudent.testScore and newStudent.programmingScore, respectively.

Suppose that score is a variable of type int. The statement:

assigns the average of newStudent.testScore and newStudent.programmingScore to score.

The following statement determines the course grade and stores it in newStudent.courseGrade:

Assigning Values:

We can assign the value of one struct variable to another struct variable of the same type by using an assignment statement. Suppose that newStudent is as shown in picture below:

Assign struct value

The statement:

copies the contents of newStudent into student. After this assignment statement executes, the values of student are as shown below:

values assigned to struct

In fact, the assignment statement:

is equivalent to the following statements:

The End!
Share your ideas with codejow through comments!


Previous First program in Visual Basic 2010 Express Edition
Next Comments and White Spaces in Visual Basic 2010

About author

Raza Bayani
Raza Bayani 42 posts

<p>Raza Bayani studies BCE (Bachelor in Computer Engineering) in Poly-technical University of Kabul. He is the CEO of CODEJOW group, a web designer, coder and recently a blogger. Raza thinks, he can help others and also boost-up his own programming skills being on codejow.com.</p>

View all posts by this author →

You might also like