Chapter 13. Point and Stare at Objects

In This Chapter

  • Examining the object of arrays of objects

  • Getting a few pointers on object pointers

  • Strong typing — getting picky about our pointers

  • Navigating through lists of objects

C++ programmers are forever generating arrays of things — arrays of ints, arrays of floats — so why not arrays of students? Students stand in line all the time — a lot more than they care to. The concept of Student objects all lined up quietly awaiting their name to jump up to perform some mundane task is just too attractive to pass up.

Declaring Arrays of Objects

Arrays of objects work the same way arrays of simple variables work. (Chapter 7 goes into the care and feeding of arrays of simple — intrinsic — variables, and Chapters 8 and 9 describe simple pointers in detail.) Take, for example, the following snippet from the ArrayOfStudents program:

// ArrayOfStudents - define an array of Student objects
//                   and access an element in it. This
//                   program doesn't do anything
class Student
    int  semesterHours;
    float gpa;
    float addCourse(int hours, float grade);

void someFn()
    // declare an array of 10 students
    Student s[10];

    // assign the 5th student a gpa of 4.0 (lucky guy)
    s[4].gpa = 4.0;
    s[4].semesterHours = 32;

    // add another course to the 5th student;
    // this time he failed - serves him right
    s[4].addCourse(3, 0.0);

Here s is an array of Student objects. s[4] refers to the fifth Student object in the array. By extension, s[4].gpa refers to the GPA of the 5th ...

Get C++ For Dummies®, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.