Skip to main content

17.10) Using A Class In A Program


To make a class definition available for use, simply include its header file in your program:

#include "rect.hpp"

An instance of the class is created in the same way that you would create a variable of some other data type. You use the class name as the variable's type and follow that with your chosen variable name. If the constructor specifies that values should be supplied to create an instance of the class, these should be supplied as a comma-separated list of arguments, in brackets after the variable's name:

Rectangle rect(0, 0, 100, 75);

You call methods on your object by prefixing the method call with the name of the variable and a period character, as in this example:

cout << rect.get_width() << "x" << rect.get_height();

Remember when compiling your program that it needs to be linked with the previously compiled class implementation:

g++ -c prog.cpp
g++ prog.o rect.o -o prog