1.8. Defining Classes and Class Methods

Lecture



Class definitions are usually placed in the header file.

Example 1.8.1

Example 1.8.1

// POINT.H

#ifndef POINTH

#define POINTH 1

class point

{

int x, y;

public:

point (int x1 = 0, int y1 = 0);

int & getx (void);

int & gety (void);

. . .

};

#endif

Because the description of the point class is planned to be included in other classes in the future, to prevent inadmissible duplication of descriptions, the conditional preprocessor directive #ifndef POINTH is included in the text. Thus, the text describing the point class can appear in the compiled file only once, despite the possibility of the repeated appearance of #include “point.h” directives.
Methods can be defined as follows.

// POINT.CPP
#ifndef POINTCPP
#define POINTCPP 1
#include “point.h”
point:: point (int x1, int y1) {x = x1; y = y1;}
int & point:: getx (void) {return x;}
int & point:: gety (void) {return y;}
. . .
#endif
In a program using class objects
#include “point.cpp”
. . .
void main (void)
{
point A (5,6);
point B (7,8);
. . .
}

The external definition of class methods makes it possible, without changing the interface of class objects with other parts of programs, to implement component functions in different ways.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

C ++ (C plus plus)

Terms: C ++ (C plus plus)