Instance Variables

Instance Variables

The simplest kind of object stores only data. We can define a mathematical point type as follows:

class Point {
    public:
        double x;
    double y;
};

Notice the semicolon that follows the close curly brace of the class definition. This semicolon is required, but it is easy to forget. By convention class names begin with a capital letter, but class names are just identifiers like variable names and function names. Here, our class name is Point. The body of the class appears within the curly braces.

#include <iostream>
 // The Point class defines the structure of software
// objects that model mathematical, geometric points
class Point {
    public:
        double x; // The point's x coordinate
    double y; // The point's y coordinate
};
int main() {
    // Declare some point objects
    Point pt1, pt2;
    // Assign their x and y fields
    pt1.x = 8.5; // Use the dot notation to get to a part of the object
    pt1.y = 0.0;
    pt2.x = -4;
    pt2.y = 2.5;
    // Print them
    std::cout << "pt1 = (" << pt1.x << "," << pt1.y << ")\n";
    std::cout << "pt2 = (" << pt2.x << "," << pt2.y << ")\n";
    // Reassign one point from the other
    pt1 = pt2;
    std::cout << "pt1 = (" << pt1.x << "," << pt1.y << ")\n";
    std::cout << "pt2 = (" << pt2.x << "," << pt2.y << ")\n";
    // Are pt1 and pt2 aliases? Change pt1's x coordinate and see.
    pt1.x = 0;
    std::cout << "pt1 = (" << pt1.x << "," << pt1.y << ")\n";
    // Note that pt2 is unchanged
    std::cout << "pt2 = (" << pt2.x << "," << pt2.y << ")\n";
}
Two Point objects with their individual data fields AndroWep-Tutorials
Two Point objects with their individual data fields AndroWep-Tutorials
pt1 = (8.5,0)
pt2 = (-4,2.5)
pt1 = (-4,2.5)
pt2 = (-4,2.5)
pt1 = (0,2.5)
pt2 = (-4,2.5)

The variables pt1 and pt2 are the objects, or instances, of the class Point. Each of the objects pt1 and pt2 has its own copies of fields named x and y. Figure 14.1 provides a conceptual view of point objects pt1 and pt2.

Double-precision floating-point numbers on most systems require eight bytes of memory. Since each Point object stores two doubles, a Point object uses at least 16 bytes of memory. In practice, an object may be slightly bigger than the sum its individual components because most computer architectures restrict how data can be arranged in memory.

This means some objects include a few extra bytes for “padding.” We can use the sizeof operator to determine the exact number of bytes an object occupies. Under Visual C++, the expression sizeof pt1 evaluates to 16.

pt1 = pt2

and the statements that follow demonstrate that we may assign one object to another directly without the need to copy each individual member of the object. The above assignment statement accomplishes the following:

pt1.x = pt2.x; // No need to assignment this way;
pt1.y = pt2.y; // direct object assignment does this