classes

Class in C++

A class is a collection of members that can be either variables or functions. Variables in a class are declared as variables elsewhere are; function prototypes are used to declare a function, and they are defined elsewhere. A class function can access any member in a class.

In C++, class is a reserved word. The class definition is contained in curly braces, after which there should be a semi-colon.

Class members are classified in three categories: private, public, and protected. These categories are defined by the reserved words private, public, and protected, which are member access specifiers.

By default, all members of a class are private.

#ifndef LINE_H
#define LINE_H

class Line
{
 public:
 Line();
 void setPointA(int x, int y);
 void setPointB(int x, int y);
 int getPointAX() const;
 int getPointBX() const;
 int getPointAY()const;
 int getPointBY()const;
 double getLength() const;
 private:
 int aX;
 int aY;
 int bX;
 int bY;
};

#endif // LINE_H

The class declaration is usually put into a header file, of type .h. The public methods are used to modify and retrieve these data members. Note that the functions that retrieve data members from the class are declared const, this ensures that these methods will not modify the data members of the function, only retrieve them.

The definition includes only the function prototypes. For these functions to actually work, we need to include the algorithms that the functions are meant to execute. Member function implementations are usually put in a separate file; the scope resolution operator, ::, is used to reference the member functions to their class.

#include <cmath>

Line::Line()
{

}

void Line::setPointA(int x, int y){
    this->aX = x;
    this->aY = y;
}

void Line::setPointB(int x, int y){
   this->bX = x;
   this->bY = y;
}

int Line::getPointAX() const{
    return this->aX;
}

int Line::getPointBX() const{
    return this->bX;
}

int Line::getPointAY()const{
    return this->aY;
}

int Line::getPointBY()const{
    return this->bY;
}

double Line::getLength() const{
    double length = pow(this->bX - this->aX, 2) + pow(this->bY - this->aY, 2);
    return sqrt(length);
}

Once an object of a class is declared, it can access the members of the class using the dot operator, .  The object of a class is limited to accessing the public members of the class, however.

#include "Line.h";

using namespace std;

int main()
{

    Line aLine = Line();
    aLine.setPointA(1, 2);
    aLine.setPointB(4, 6);

    cout << "The length of the line is " << aLine.getLength() << endl;

    return 0;
}

Every class has member functions that only access and do not modify the data members; these methods are called accessor functions. Likewise, every class has member functions that modify the data members, called mutator functions.