Reading — step 1 of 7
Learn
Classes are how C++ bundles data and behavior. Stroustrup's PPPC++ treats classes as the central abstraction in C++. The basics:
Defining a class
class Point {
private:
double x, y; // member variables (state)
public:
Point(double x_, double y_) : x{x_}, y{y_} {} // constructor
double getX() const { return x; }
double getY() const { return y; }
double distanceTo(const Point& other) const {
double dx = x - other.x;
double dy = y - other.y;
return std::sqrt(dx*dx + dy*dy);
}
};
Point p{3.0, 4.0};
Point q{0.0, 0.0};
std::cout << p.distanceTo(q); // 5
public, private, protected
Access specifiers control visibility:
- private — only this class (the default for
class) - protected — this class and derived classes
- public — anyone
Keep data private. Expose public methods ("member functions") that maintain invariants.
struct vs class
In C++, struct and class are nearly identical — the ONLY difference is the default access specifier:
structdefaults to publicclassdefaults to private
Convention: use struct for plain data bundles (POD-like), class when you have invariants and behavior.
Constructors and the member initializer list
The : x{x_}, y{y_} part is the member initializer list — runs before the body, initializes members directly:
Point(double x_, double y_) : x{x_}, y{y_} {}
Is preferred over assignment in the body:
Point(double x_, double y_) {
x = x_; // x was default-constructed first, then assigned — wasteful
y = y_;
}
For const members and references, the initializer list is REQUIRED — you can't assign them later.
const member functions
Adding const after the parameter list of a method declares it doesn't modify the object:
double getX() const { return x; } // promise: doesn't modify *this
A const Point can ONLY call const methods. Always mark accessors const.
The default special members
If you don't define them, the compiler generates:
- Default constructor (only if you define no other constructors)
- Copy constructor:
Point(const Point& other) - Copy assignment:
Point& operator=(const Point& other) - Destructor:
~Point() - (Move ctor and move assignment if move-friendly)
The defaults do member-wise copy. For classes with raw owned pointers, you'll need to write your own — a topic for the C++ Intermediate course (Rule of Five, Move Semantics).
Common mistakes
- Default-constructing then assigning instead of using the member initializer list — wasteful and breaks for const/reference members.
- Forgetting
conston accessors — code that only has aconst Point&can't call them. - Public data members with no invariants protection — common in beginner code, awkward to refactor later.
- Defining a constructor and assuming the default still exists — once you write any constructor, the implicit default is suppressed.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…