Classes - sheerazwalid/COMP-I GitHub Wiki

Classes

Classes is a feature of C++ (as well as many other languages) that let's the programmer define new data types with specially defined functionality that is accessible via the dot operator. As an example, the following code defines a data type, or class, named Point, which is used to represent points in 2-dimensions. The test code shows how instances of the Point class are created and how Point functionality is invoked through the dot operator.

#include <iostream>
#include <cmath>
#include <cassert>

using namespace std;

class Point {
public:
	Point() : x(0), y(0) {}
	Point(double x) : x(x), y(0) {}
	Point(double x, double y) : x(x), y(y) {}
	double getX() const { return x; }
	double getY() const { return y; }
	void setX(double x) { this->x = x; }
	void setY(double y) { this->y = y; }
	double distanceFromOrigin() const { return sqrt(x * x + y * y); }
	double distanceFrom(const Point & p) const {
		return sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y)); 
	}
private:
	double x;
	double y;
};

int main() {
	Point p1;
	p1.setX(0);
	p1.setY(3);
	assert(p1.distanceFromOrigin() == 3);

	Point p2(4, 0);
	assert(p1.distanceFrom(p2) == 5);

	Point p4 = 9;
	assert(p4.getX() == 9);
	assert(p4.getY() == 0);

	Point * ptr = &p4;
	assert(ptr->getX() == 9);
}

Reading

  • Structs That Web page uses the term data structures to refer to the C/C++ struct feature for defining data types. In my opinion, they should not have used this term because data structures is more commonly used to describe the area in computer science that studies different organizations of data.
  • Classes I

Optional Videos

⚠️ **GitHub.com Fallback** ⚠️