next up previous
Next: Constructors Up: complex Previous: complex


Simple Classes: mycomplex0.h

Classes are a fundamental tool of object-oriented programming. A class is a device for constructing objects that generally contain values and special functions called "methods" for manipulating their values. The simplest classes contain only values and can be thought of as a simple extension of the concept of "type". Class definitions can be selected from standard libraries, in which case an appropriate header file is usually included or they can be user-defined, in which case the user puts the definition in a separate custom header file.

To introduce the concept we consider a simple complex number class. Complex numbers are not a basic data type in C++, so they must be defined. Most modern C++ compilers provide a header file that defines a complex class. In order to use such canned classes effectively, it is important to understand how they are constructed. So here, we build our own primitive complex class for the sake of illustrating how classes work.

#include <iostream>

class complex {
public:
  double re;
  double im;
};

int main(){
   complex a;

   cout << "Enter Re and Im\n";
   cin >> a.re >> a.im;
   cout << "Your number is " << a.re << " + I * " << a.im << "\n";
}

The class declaration and definition begins with the class keyword, followed by the name you choose (here we chose complex), and includes all the statements enclosed in braces. This complex class is built from two double precision values, the real and imaginary parts of the number. Once the class is defined, it becomes another type. So a in the main program is declared a complex object, or simply put, a variable of type "complex". It is said that a is an "instance" of a complex object. We can create as many such instances as we like, just as we can declare as many variables of type float as we like. Each of them has its own real and imaginary part.

The variables re and im are called "members" of the complex class. Inside the class definition they are known by these names. Every instance of the complex class has them. To refer to them individually outside the class definition, e.g. in the main program, we use the dot . membership operator. So in this example, to refer to the real part of a we use a.re to specify that member. The same holds for a.im. Similarly, if b is declared complex, b.re would refer to its real part, etc.

Notice that we can't just say cin >> a or |cout « a|, because we haven't told the compiler how to read or print a complex number. (To be more precise, the operators >> and << in the iostream class have not been defined for complex types.) So we had to work with variables a.re and a.im, which are of the base type double, which iostream understands.



Subsections
next up previous
Next: Constructors Up: complex Previous: complex
Carleton DeTar 2017-02-13