The Analogy: The Blueprint and the Houses
A class is an architect's blueprint. It says a house has three bedrooms, a front door and a boiler, and it describes what the boiler does when you turn it on. But you cannot live in a blueprint.
An object is a house built from that blueprint. Build twenty and you get twenty houses: same layout, but each with its own front door key, its own boiler temperature, its own address. Change the temperature in number 12 and number 14 is unaffected.
That is the whole distinction. The class exists once, at compile time, and occupies no memory of its own. Objects are created at runtime, and each carries its own copy of the data the blueprint described.
Syntax or Core Structure
#include <iostream>
#include <string>
class Rectangle {
public: // visible from outside
double width;
double height;
double area() const { // a member function
return width * height; // 'width' means 'this->width'
}
void scale(double factor) { // no 'const': it modifies the object
width *= factor;
height *= factor;
}
}; // note the semicolon
int main() {
Rectangle a; // an object -- members are UNINITIALISED
a.width = 3.0;
a.height = 4.0;
Rectangle b{5.0, 2.0}; // brace initialisation, in declaration order
std::cout << a.area() << "\n"; // 12
std::cout << b.area() << "\n"; // 10
a.scale(2.0);
std::cout << a.area() << "\n"; // 48 -- 'a' changed, 'b' did not
std::cout << b.area() << "\n"; // 10
return 0;
}
Three details that trip people up. The closing brace needs a semicolon. Members are not zero-initialised by default, so Rectangle a; followed by reading a.area() is undefined behaviour. And const after the parameter list is a promise that the function will not modify the object — area keeps it, scale cannot.
Technical Depth: What an Object Really Is
An object is its data members, and nothing else
Member functions are not stored per object. They are compiled once and shared, with the object's address passed invisibly as this. So:
class Counter {
public:
int count{0}; // 4 bytes
void bump() { ++count; } // 0 bytes per object
void reset() { count = 0; } // 0 bytes per object
};
std::cout << sizeof(Counter); // 4, not 4 + two function pointers
Add ten more member functions and sizeof(Counter) stays 4. (Virtual functions are the exception — they add one hidden pointer, covered in the polymorphism lesson.)
this
Inside any non-static member function, this is a pointer to the object the call was made on. You rarely write it, because unqualified names resolve to members automatically, but two situations call for it:
class Box {
int size;
public:
void setSize(int size) {
this->size = size; // disambiguate member from parameter
}
Box& grow(int by) {
size += by;
return *this; // return the object for chaining
}
};
Box b;
b.grow(2).grow(3).grow(4); // chaining works because grow returns Box&
Default member initialisers
Give members a value where they are declared and every object starts in a valid state, whichever way it was created:
class Session {
public:
std::string user{"guest"};
int timeoutSeconds{300};
bool active{false};
};
Session s; // all three are set -- nothing undefined
This is the cheapest reliability win in the language. Prefer it to remembering to assign every member after construction.
class versus struct
The only language difference is the default access level: class members are private unless you say otherwise, struct members are public.
class | struct | |
|---|---|---|
| Default member access | private | public |
| Default inheritance | private | public |
| Can have methods, constructors | Yes | Yes |
| Conventional use | Invariants to protect | Plain grouped data |
Both can do everything the other can. The convention is worth following: reach for struct when the type is a bag of fields with no rules to enforce, and class when the data must stay consistent.
Objects are values
A C++ object is a value, not a reference to one. Assignment copies:
Rectangle x{2.0, 3.0};
Rectangle y = x; // a full, independent copy
y.width = 99.0;
std::cout << x.width; // 2 -- x is untouched
This differs from Java, C# and Python, where y = x would make both names refer to one object. In C++ you must ask for sharing explicitly, with a reference or a pointer.
Where to put the code
Small member functions are usually defined inside the class. Larger ones are declared inside and defined outside, using ClassName:::
class Account {
double balance{0.0};
public:
void deposit(double amount); // declaration
double getBalance() const { return balance; }
};
void Account::deposit(double amount) { // definition
if (amount > 0.0) { balance += amount; }
}
In a real project the declaration lives in a header and the definition in a .cpp file, so callers recompile only when the interface changes.
Real World Example: A Library Book
One class, several objects, each keeping its own state consistent.
#include <iostream>
#include <string>
#include <vector>
class Book {
public:
// Default member initialisers: no object can start out garbage.
std::string title{"Untitled"};
std::string author{"Unknown"};
int totalCopies{0};
int onLoan{0};
// const: asks a question, changes nothing.
int available() const {
return totalCopies - onLoan;
}
bool isAvailable() const {
return available() > 0;
}
// Not const: this is a state change, and it refuses invalid moves.
bool borrow() {
if (!isAvailable()) { return false; }
++onLoan;
return true;
}
bool returnCopy() {
if (onLoan == 0) { return false; } // nobody has it out
--onLoan;
return true;
}
// Returns *this so calls can be chained.
Book& addCopies(int n) {
if (n > 0) { totalCopies += n; }
return *this;
}
std::string label() const {
return title + " by " + author +
" (" + std::to_string(available()) + "/" +
std::to_string(totalCopies) + " available)";
}
};
int main() {
Book emma{"Emma", "Jane Austen", 3, 0};
Book dune{"Dune", "Frank Herbert", 1, 0};
Book blank; // valid, thanks to the initialisers
std::cout << blank.label() << "\n"; // Untitled by Unknown (0/0 available)
blank.addCopies(2).addCopies(3); // chaining -> 5 copies
std::cout << blank.totalCopies << "\n"; // 5
std::cout << emma.borrow() << "\n"; // 1 -- succeeded
std::cout << dune.borrow() << "\n"; // 1 -- succeeded
std::cout << dune.borrow() << "\n"; // 0 -- only one copy exists
std::cout << emma.label() << "\n"; // Emma ... (2/3 available)
std::cout << dune.label() << "\n"; // Dune ... (0/1 available)
// Objects are values: copying makes an independent book.
Book emmaCopy = emma;
emmaCopy.borrow();
std::cout << emma.available() << " "
<< emmaCopy.available() << "\n"; // 2 1 -- separate state
// A container of objects behaves the same way.
std::vector<Book> shelf{emma, dune, blank};
for (Book& b : shelf) { b.addCopies(1); } // '&' or the copies are discarded
std::cout << shelf[1].totalCopies << "\n"; // 2
return 0;
}
Every choice here is about keeping each object's state coherent on its own. The default member initialisers mean Book blank; produces a printable, usable object rather than four fields of garbage — blank.label() works immediately, which is why the class needs no "did you remember to fill it in" checks anywhere else. available(), isAvailable() and label() are all const because they only ask questions; that is not decoration, it is what lets them be called on a const Book& parameter later, and the compiler enforces it. borrow() and returnCopy() deliberately return bool instead of silently doing nothing, so a caller can distinguish "borrowed" from "none left" — the alternative, letting onLoan exceed totalCopies, would make available() return a negative number and quietly poison every later calculation. addCopies returns Book& so that blank.addCopies(2).addCopies(3) reads as one thought. The two copies of Emma demonstrate C++ value semantics: emmaCopy.borrow() moves one object's counter and leaves the other's alone, which would surprise anyone arriving from Java. And the loop over shelf needs Book&: with a bare Book b it would add a copy to a temporary that dies at the end of each iteration, changing nothing at all.
Common Mistakes
- Forgetting the semicolon after the closing brace.
}alone produces a wall of confusing errors on the next declaration. - Reading uninitialised members.
Rectangle a; std::cout << a.area();is undefined behaviour. Use default member initialisers. - Confusing the class with an object.
Rectangle.area()is not valid; you need an object:a.area(). - Omitting
conston query functions. They then cannot be called on aconstobject or through aconst¶meter, which spreads pain outwards. - Expecting reference semantics on assignment.
Book b = a;copies. If you wanted to share, writeBook& b = a;. - Forgetting
&in a loop over a container of objects. Modifications go to a temporary copy and vanish. - Making everything public because it is quicker. It is, until an invariant like
onLoan <= totalCopiesgets broken from outside. - Defining large member functions inside the class in a header. Every including file recompiles when the body changes.
Best Practices
- Give every data member a default initialiser so no object can exist in an invalid state.
- Mark every member function that does not modify the object
const. Do it as you write it, not later. - Name the class for the thing, and its functions for the actions —
Book::borrow(), notBook::doBook1(). - Use
structfor plain data andclasswhen there are rules to enforce. - Return
*thisasClassName&from functions meant to be chained. - Keep members private once a class has an invariant; expose the operations, not the fields.
- Declare in the header, define non-trivial bodies in the
.cpp. - Prefer
const ClassName¶meters so no caller pays for a copy.
Practice Exercises
- Build the blueprint: Write a
Circleclass with aradiusmember, aconstarea()andcircumference(), and ascale(double)that is notconst. Create three circles, print all three areas, scale one, and confirm the other two are unchanged. - Prove objects are values: Create a
Book, copy it into a second variable, change a member on the copy, and print both. Then repeat withBook& alias = original;and print both again. Explain the difference in a comment. - Break const: Try to modify a member inside a function marked
const, and try calling a non-constmember function on aconst Book. Paste both compiler errors into comments and describe what each is protecting. - Chain it: Add a
Book& setAuthor(const std::string&)and aBook& setTitle(const std::string&)that both return*this, then configure a blank book in a single chained statement.