Systems CourseC/C++ · Linux · Memory
C++ CoreLesson 07 of 441 min read6 questions

How to Write a Class

Split private data vs public interface; mind inline, headers, and const.

Test yourself ↓

Concept core idea Watch out easy to get wrong

Concept

Key concepts

  1. Decide what's private (data) vs public (interface); outsiders touch data only through methods.
  2. Method defined inside the class body = implicitly inline; defined outside needs Class::method. Forgetting Class:: → treated as an unrelated global → linker 'undefined reference'.
  3. Header/source split: declarations in .h, definitions in .cpp (ODR — a non-inline body in a header included by multiple TUs = duplicate-symbol error).
  4. const-correctness: a method that doesn't modify the object should be const (int GetX() const).

ODR — One Definition Rule

A non-inline function may be DEFINED only once across the whole program. A full function body in a header included by two .cpp files = two definitions → duplicate-symbol link error. Declarations in headers; definitions in one .cpp.

Watch out

Easily confused

declaration vs definition
A declaration says 'this exists' (goes in .h); a definition provides the body/storage (goes in one .cpp).
inline member vs Class::
Defined inside the class body → implicitly inline. Defined outside → must qualify with Class:: or it's an unrelated global.

Test yourself

6 questions on this lesson. Write your answers from memory, then compare them with the model answers side by side.