CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Classes and internal methods

As with other object-oriented languages, C++ 'collects' strongly related data and functions operating on that data in classes.

C++ classes may legally have only data members (fields), with no internal methods, and they are then very similar to C11's structures.

In this example, the class MyVector has two public methods that have access to the class's data members.
They can access or modify the values associated with an instance of the class.

#include <iostream>

class MyVector {
public:
    Point start;
    Point end;

    void offset(double offsetX, double offsetY) {
	start.x += offsetX;
	end.x   += offsetX;
	start.y += offsetY;
	end.y   += offsetY;
    }

    void print(void) {
	cout << "(" << start.x << "," << start.y << ") -> ("
	     << end.x << "," << end.y << ")" << endl;
    }
};

Note that the methods offset() and print() are internal to the class definition and, thus, act as both declarations and definitions of the methods.

 


CITS2002 Systems Programming, Lecture 23, p5, 17th October 2023.