Point and Line Class in C++

Muhammad Adil Dec 11, 2023
  1. Basic Use Cases of Point and Line Class in C++
  2. Implement the Point and Line Class in C++
  3. Conclusion
Point and Line Class in C++

Understanding the Point and Line classes in C++ is fundamental for developing applications that involve geometrical calculations and graphics. These classes are essential in representing basic geometric entities like points and lines, providing a foundation for more complex structures.

The Point and Line classes in C++ are primary data types that can represent points and lines. It provides methods for manipulating points, bars, and vectors.

This article is about the Point and Line classes in C++. It will cover what it does, how to use it, and how to implement it in your program.

A point is represented by two coordinates, one for the x-coordinate and one for the y-coordinate. A line is represented by two points, one for the start point (or initial point) and one for the endpoint (or terminal point).

Basic Use Cases of Point and Line Class in C++

The Point and Line classes are a fundamental part of the C++ language. It is ubiquitous to use these classes when using the graphics library.

They can be used to create graphs, animations, games, and more. It comes with many benefits, such as:

  1. It is used to represent points and lines in 2D space.
  2. It can be used to determine the distance between two points.
  3. It can be used to check if two lines intersect.
  4. It can find the intersection point of two lines.

The Point and Line classes provide many functionalities that would not exist without them. Usually, the Line class is more complex than the Point because it represents the slope and direction of a line.

Point Class

The Point class represents a point in a 2D space, characterized by its x and y coordinates. To begin, let’s design the class structure:

class Point {
 private:
  double x;
  double y;

 public:
  Point();                          // Default constructor
  Point(double xVal, double yVal);  // Parameterized constructor
  double getX() const;              // Accessor for x coordinate
  double getY() const;              // Accessor for y coordinate
  void setX(double newX);           // Mutator for x coordinate
  void setY(double newY);           // Mutator for y coordinate
  double distanceTo(const Point& other)
      const;  // Method to calculate distance to another point
};

Implementation:

  • Constructors: The class includes both a default constructor and a parameterized constructor. The default constructor initializes a point at the origin (0,0), while the parameterized constructor allows specifying custom coordinates.
  • Accessors and Mutators: Accessor functions (getX and getY) retrieve the x and y coordinates, respectively, while mutator functions (setX and setY) modify these coordinates.
  • Distance Calculation: The distanceTo method calculates the distance between two points using the Euclidean distance formula.

Sample Usage:

#include <cmath>  // Include cmath for square root and pow functions
#include <iostream>
using namespace std;

class Point {
 private:
  double x;
  double y;

 public:
  Point()
      : x(0), y(0) {}  // Default constructor initializing coordinates to (0,0)
  Point(double xVal, double yVal)
      : x(xVal), y(yVal) {}  // Parameterized constructor

  double getX() const { return x; }  // Accessor for x coordinate
  double getY() const { return y; }  // Accessor for y coordinate

  void setY(double newY) { y = newY; }  // Mutator for y coordinate

  double distanceTo(const Point& other)
      const {  // Method to calculate distance to another point
    return sqrt(pow(x - other.x, 2) + pow(y - other.y, 2));
  }
};

int main() {
  Point p1;            // Creates a point at (0,0)
  Point p2(3.0, 4.0);  // Creates a point at (3,4)

  double xCoord = p2.getX();  // Retrieves x coordinate of p2
  p1.setY(2.5);               // Sets y coordinate of p1 to 2.5

  double distance = p1.distanceTo(p2);  // Calculates distance between p1 and p2

  // Displaying the results
  cout << "x coordinate of p2: " << xCoord << endl;
  cout << "New y coordinate of p1: " << p1.getY() << endl;
  cout << "Distance between p1 and p2: " << distance << endl;

  return 0;
}

Output:

x coordinate of p2: 3
New y coordinate of p1: 2.5
Distance between p1 and p2: 3.3541

This code snippet defines a Point class representing a 2D point and demonstrates the usage of its methods. The main function creates two points, p1 and p2, retrieves the x-coordinate of p2, sets a new y-coordinate for p1, and calculates the distance between the two points using the distanceTo method.

The output displays the x-coordinate of p2, the new y-coordinate of p1, and the distance between p1 and p2.

Line Class

The Line class represents a line segment defined by two endpoints (points). Here’s an outline of its structure:

class Line {
 private:
  Point startPoint;
  Point endPoint;

 public:
  Line();                                      // Default constructor
  Line(const Point& start, const Point& end);  // Parameterized constructor
  Point getStartPoint() const;                 // Accessor for start point
  Point getEndPoint() const;                   // Accessor for end point
  void setStartPoint(const Point& newStart);   // Mutator for start point
  void setEndPoint(const Point& newEnd);       // Mutator for end point
  double length() const;  // Method to calculate the length of the line segment
};

Implementation:

  • Constructors: Similar to the Point class, Line has a default constructor and a parameterized constructor that initializes the line segment using specified points.
  • Accessors and Mutators: Accessor functions (getStartPoint and getEndPoint) retrieve the start and end points, respectively, while mutator functions (setStartPoint and setEndPoint) modify these points.
  • Length Calculation: The length method computes the length of the line segment using the distance formula between its endpoints.

Sample Usage:

#include <cmath>
#include <iostream>

// Define the Point class
class Point {
 private:
  double x, y;

 public:
  Point(double xCoord, double yCoord) : x(xCoord), y(yCoord) {}

  double getX() const { return x; }

  double getY() const { return y; }

  // You might have other methods like setX, setY, etc.
};

// Define the Line class
class Line {
 private:
  Point start, end;

 public:
  Line(Point startPoint, Point endPoint) : start(startPoint), end(endPoint) {}

  void setStartPoint(Point newStart) { start = newStart; }

  double length() const {
    // Calculate the length using the distance formula
    double dx = end.getX() - start.getX();
    double dy = end.getY() - start.getY();
    return sqrt(dx * dx + dy * dy);
  }
};

int main() {
  Point startPoint(1.0, 1.0);
  Point endPoint(4.0, 5.0);
  Line line(startPoint, endPoint);  // Creates a line segment

  Point newStart(2.0, 2.0);
  line.setStartPoint(newStart);  // Changes the start point of the line

  double lineLength =
      line.length();  // Calculates the length of the line segment

  std::cout << "Length of the line segment: " << lineLength << std::endl;

  return 0;
}

Output:

Length of the line segment: 3.60555

The code snippet defines two points, startPoint at coordinates (1.0, 1.0) and endPoint at (4.0, 5.0). Using these points, a Line object named line is created, representing a line segment between these two points.

Subsequently, a new point, newStart at (2.0, 2.0), is created and assigned as the updated start point of the line using the setStartPoint method. Finally, the length method is called on the line object, calculating and storing the length of the line segment in the variable lineLength.

This sequence demonstrates the creation of a line segment, modification of its start point, and computation of its length using the defined classes and methods in the code.

Implement the Point and Line Class in C++

This section will see the steps required to implement the Point and Line classes in C++.

  • Start with a header file that includes all the necessary declarations.
  • Create a Point class that contains two data members, x and y.
  • Create a Line class that contains two data members, startPoint and endPoint.
  • Define the constructor for both classes. In the constructor, set the coordinates of a point or line to specific values.
  • Define member functions for both classes.
  • Define the destructor for both classes.

Example of Point and Line Class in C++

Let’s discuss an example to better understand the Point and Line classes:

#include <iostream>
using namespace std;
class point {
 private:
  int X, Y;

 public:
  point() {
    X = 0;
    Y = 0;
  }
  void setPoint(int a, int b) {
    X = a;
    Y = b;
  }
  int getX(void) { return X; }
  int getY(void) { return Y; }
};
int main() {
  point p1, p2;
  p1.setPoint(6, 8);
  cout << "p1: " << p1.getX() << " , " << p1.getY() << endl;
  return 0;
}

Output:

p1: 6 , 8

This code defines a point class representing a 2D point with x and y coordinates. The class contains private member variables X and Y for the coordinates, a default constructor initializing coordinates to (0,0), a setPoint method to assign specific coordinates, and accessor methods getX and getY to retrieve the x and y values respectively.

In the main function, two point objects, p1 and p2 are created. p1’s coordinates are set to (6, 8) using the setPoint method, and then the x and y values of p1 are printed using getX and getY.

This code demonstrates the basic usage of a simple point class to create and manipulate 2D points in C++.

Click here to check the working of the code as mentioned above.

Conclusion

The Point and Line classes in C++ encapsulate geometric entities, providing methods to manipulate and retrieve information about points and line segments. By employing these classes, you can organize and manage geometric data effectively within your programs.

Implementing these classes involves defining appropriate member variables, constructors, accessor and mutator methods, and functionalities specific to the entity being modeled. Understanding such class designs in C++ lays a solid foundation for handling geometric concepts and can be extended to more complex applications involving shapes, polygons, and more.

Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook

Related Article - C++ Class