Easy C++


C++ Tutorial - Lesson 21: Arrays of Class Objects

Arrays of Class Objects - Intro, Using Single Objects

by John Kopp

Support this site at no cost to you

Welcome to EasyCPlusPlus.com's free tutorial on C++ programming. In previous lessons we have seen how to create arrays and single objects of automatic extent and how to dynamically allocated arrays and single objects for objects of built-in types. An automatic object has its storage allocated when it is defined. These are just the ordinary objects we have been using through out this tutorial. This lesson extends these concepts to include creating and using arrays of class objects. Let's begin with a quick review of defining and using single class objects and then work with arrays.

Review: Defining and Using Class Objects
The simplest way to learn how to define and use classes is to study a simple example. Let's define a simple Cat class, create a few felines and see what they can do. But, first, let's quickly look at dynamically allocating class objects. We saw the use of new and delete with built-in types in a previous lesson. The operator new dynamically creates an object on the heap and returns a pointer to it. The operator delete is used to free that memory after it is no longer needed so that it may be reused elsewhere by the program. The following syntax is used to dynamically allocate a class object.

class pt = new class;    //Calls default constructor
class pt = new class(arg1, arg2, ....);    /* Calls constructor with a parameter list that matches the number and type of the arguments in the call. */

To delete the dynamically allocated object, that is, to free the memory it occupies:

delete pt;
    //Where pointer contains the address of the object to be freed.

Hiss!!. Here is a brief example.

#include <iostream>
#include <string>
using namespace std;

class Cat {
    Cat(string name = "tom", string color = "black_and_white") : _name(name), _color(color) {}
    ~Cat() {}
    void setName(string name) {_name = name;}
    string getName() {return _name;}
    void setColor(string color) {_color = color;}
    string getColor() {return _color;}
    void speak() {cout << "meow" << endl;}
    string _name;
    string _color;

int main()
    Cat cat1("morris","orange");    //Objects of automatic extent exist on stack.
    Cat *cat2pt = new Cat("felix","black");    /* Dynamically allocated objects exist on the heap. */
    Cat *cat3pt = new Cat;    //Calls default constructor

    cout << cat1.getName() << " is " << cat1.getColor() << endl;
    cout << cat2pt->getName() << " is " << cat2pt->getColor() << endl;
    cout << cat3pt->getName() << " is " << cat3pt->getColor() << endl;


    delete cat2pt;    //Always "delete" dynamically allocated objects!
    delete cat3pt;

    return 0;

Previous Page       Next Page