C++ Lecture 3

[Previous Lecture] [Lecture Index] [Next Lecture]

point.h

#ifndef POINT_H
# define POINT_H

class Point {
  public:
    Point(int x, int y);
    int getX() const;
    int getY() const;
    void setX(int nx);
    void setY(int ny);
    void move(int dx, int dy);
    double distanceTo(const Point &p) const;
    /* ... */
  private:
    int x, y;
};

#endif /* POINT_H */

point.cc

#include <math.h>
#include "point.h"

Point::Point(int x, int y)
{
    Point::x = x;
    this->y = y;
}

double
Point::distanceTo(const Point &p) const
{
    double dx = x - p.getX();
    double dy = y - p.getY();
    return sqrt(dx * dx + dy * dy);
}

int
Point::getX() const
{
    return x;
}

int
Point::getY() const
{
    return y;
}

void
Point::setY(int y)
{
    this->y = y;
}

void
Point::setX(int x)
{
    this->x = x;
}

void
Point::move(int dx, int dy)
{
    x += dx;
    y += dy;
}

rect.h

#ifndef RECT_H
# define RECT_H
# include "point.h"

class Rect {
  public:
    Rect(int x, int y, int width, int height);
    void move(int dx, int dy);
    bool pointInside(const Point &p) const;

    // bad: exposes implementation details...
    const Point &getUpperLeft() const {
        return upperleft;
    }

    /* ... */
  private:
    Point upperleft;
    int width, height;
};

#endif /* RECT_H */

rect.cc

#include "point.h"
#include "rect.h"

Rect::Rect(int x, int y, int width, int height)
    : upperleft(x, y)
{
    this->width = width;
    this->height = height;
}

void
Rect::move(int dx, int dy)
{
    upperleft.move(dx, dy);
}

bool
Rect::pointInside(const Point &p) const
{
    if (upperleft.getX() <= p.getX()
        && p.getX() <= upperleft.getX() + width
        && upperleft.getY() <= p.getY()
        && p.getY() <= upperleft.getY() + height)
            return true;
    return false;
}

Misc Notes on Classes


Basic Object Oriented Concepts


How to do OO design


What makes a `good object'?


[Previous Lecture] [Lecture Index] [Next Lecture]