Legacy C++ › 3. Classes and Object-Oriented Programming
Classes and Objects
Members, access control, struct vs class and member functions.
beginner #class#struct#access-control#member-functions#encapsulation#this
Explanation
A class bundles data (members) with the functions that operate on it (member functions). Access specifiers control visibility:
public: part of the interfaceprivate: implementation, only accessible by the class (and friends)protected: accessible by the class and derived classes
The only difference between struct and class is the default access: struct is public, class is private (and the same for default inheritance).
Inside a member function, this is a pointer to the object. Member functions defined inside the class body are implicitly inline.
Example
#include <iostream>
class Rectangle {
public:
Rectangle(double w, double h) : width_(w), height_(h) {}
double area() const { return width_ * height_; }
double perimeter() const { return 2 * (width_ + height_); }
void setWidth(double w) {
if (w > 0) width_ = w; // the class protects its invariant
}
Rectangle& scale(double f) { // returns *this to allow chaining
width_ *= f; height_ *= f;
return *this;
}
private:
double width_;
double height_;
};
int main() {
Rectangle r(3, 4);
std::cout << r.area() << " " << r.perimeter() << "\n"; // 12 14
r.scale(2).setWidth(10);
std::cout << r.area() << "\n"; // 10 * 8 = 80
Rectangle* p = new Rectangle(1, 1);
std::cout << p->area() << "\n"; // -> for pointers
delete p;
return 0;
}
Common pitfalls
- Public data members let any code break the class invariants. Keep data private and expose behavior.
- Forgetting the semicolon after the closing brace of a class:
class A { ... };. - Member functions are declared in the class, defined outside as
ReturnType Class::name(...); forgettingClass::defines an unrelated free function. - Objects are laid out by member declaration order, not the order in an initializer list.
- Empty classes still have
sizeofat least 1.
Legacy vs modern
C++11 adds in-class member initializers (int n = 0;), = default / = delete, and override/final. C++17 adds inline static members.
Exercises
1. What is the difference between struct and class in C++?
Only the default access (public vs private); otherwise they are identical.
2. Add a bool isSquare() const to Rectangle.
bool isSquare() const { return width_ == height_; }