Using Objects


This lab includes:

  1. What are objects?
  2. Creating objects
  3. Using objects
  4. Exercise

  1. What are objects?

    Objects are data items that are more complex than the basic data items, such as char, int, float, which we are already familiar with. Objects more closely represent entities in the real world. Examples of objects might be employee records, student records, graphical shapes and so on. Here, we will learn how to use objects. Later, we will learn learn how to define objects.

  2. Creating objects:

    Declaring an object is like declaring a variable of numeric data type, for instance:

      int x; // makes an int
      Point p; // makes a Point object
    

    Both declare a new variable. Apart from the differences in type, there's a big difference in how each is initialized. Unless explicitly initialized, x will contain whatever value is left over from its memory's last use. (Remember, it is recommended to set int x=0 in order to avoid complications due to the leftover data.) In contrast, objects are initialized when they are defined. The actual initialization depends on the object type, for example:

      Point p;
    

    will initialize p to (0,0).

    If you don't want to initialize an object with the default, you supply construction parameters. For example, you can construct a Point object by specifying its x and y coordinates, for example:

      Point q(1, 3); 
    

  3. Using objects:

    An object's member functions are applied to a particular object using the dot-notation. For example, q.get_x() returns the x-coordinate of the point stored in the Point object called q, and q.move(dx, dy) moves the point q by (dx, dy). Member functions that return stored information when applied to an object are called accessors, those that change the stored information are called mutators.

    Given the Point q above, the command

      cout << q.get_x() << ", " << q.get_y();
    

    will print the result:

      1, 3
    

    and the sequence of commands:

      q.move(1, -1);
      cout << q.get_x() << ", " << q.get_y();
    

    will produce the result:

      2, 2
    
  4. Exercise:

    Write a program shapes.cpp to draw the following shapes:

    1. A triangle, using three Line objects.
    2. An automobile, using Circle and Line objects.
    3. Five circles of radii 1, 2, 3, 4, 5. Use Circle's move(dx, dy) member function to draw the circles all tangent to a common point.

    To compile your program type:

    g++ -I/cs/course/cs113/textbook/horstmann/cccfiles -g -o shapes shapes.cpp -L/usr/X11/lib -lX11 -lm
    

    The result of your program should look similar to this:

Useful Resources


BU CAS CS - Using Objects
This page created by Jonathan Alon <jalon@cs.bu.edu>.
Material adapted from the textbook "Computing Concepts with C++ Essentials", by Horstmann.