Classes and Objects in C\u002b\u002b: Data Members, Methods and a Worked State Trace
Build a precise model of C++ classes and objects, then follow two WaterTank instances through valid, rejected, and independent state changes.
KnowledgeGate Team
Exam prep & CS education

Calling a class a “blueprint” and an object an “instance” is easy to memorise, but those labels do not show which values belong to each object or how a method call changes them. A WaterTank program with two objects makes the model concrete: hostel moves through 120 -> 370 -> 280 -> rejected 530, while lab keeps its own state and changes independently. The example ties class anatomy to member access, valid construction and receiver-specific behaviour.
Classes and objects in C++: type versus instance
A class is a user-defined type. It specifies a representation and the operations allowed on that representation. An object is one concrete instance of that type, with its own identity and values for every non-static data member.
Both hostel and lab have type WaterTank. The hostel object starts with 120 litres inside a 500-litre capacity, while lab starts with 80 litres inside a 300-litre capacity. They share a type, not their stored levels.
Here, state means label_, capacity_ and current_. Behaviour means the constructor and the functions fill, drain, current, capacity, percentFull and label. Each object carries separate state, while the class makes the same operations available to every valid instance.
C++ Encapsulation and Class Invariants: Build Objects That Stay Valid owns constructor contracts, BankAccount invariants and representation-leak prevention. The class/object treatment centres on per-object state, receiver binding and member access.
Read a C++ class from boundary to member list
In a class, members before an explicit access label are private by default. A struct defaults to public. Access controls source-level use, not whether the bytes exist. The trailing semicolon closes the class definition.
Member | Kind | Belongs to | Purpose |
|---|---|---|---|
| Non-static data member | Each object separately | Stores that tank's current litres |
| Non-static member function | The calling object | Validates and increases its level |
| Constructor | A new object | Establishes a valid initial state |
| Static data member | The class | Stores one class-wide count |
Private data comes before the public interface. Its accessors are const, and label() returns const string&.
A separate example, struct ObjectCounter { inline static int created = 0; ObjectCounter() { ++created; } }; ObjectCounter a; ObjectCounter b;, produces 0 -> 1 -> 2. That counter is shared, unlike current_. Ordinary member-function machine code is not copied into every object. Explore more programming and DSA routes through Placement Preparation & Coding.
Construct two valid objects and map their independent state
The constructor uses an initializer list and rejects a non-positive capacity, a negative initial level, or an initial level above capacity.
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;
class WaterTank {
private:
string label_;
int capacity_;
int current_;
public:
WaterTank(string label, int capacity, int initial)
: label_(label), capacity_(capacity), current_(initial) {
if (capacity <= 0 || initial < 0 || initial > capacity)
throw invalid_argument("invalid tank state");
}
bool fill(int litres) {
if (litres <= 0 || litres > capacity_ - current_) return false;
current_ += litres;
return true;
}
bool drain(int litres) {
if (litres <= 0 || litres > current_) return false;
current_ -= litres;
return true;
}
int current() const { return current_; }
int capacity() const { return capacity_; }
double percentFull() const { return 100.0 * current_ / capacity_; }
const string& label() const { return label_; }
};
int main() {
WaterTank hostel("Hostel", 500, 120);
WaterTank lab("Lab", 300, 80);
hostel.fill(250);
hostel.drain(90);
hostel.fill(250);
lab.drain(30);
cout << fixed << setprecision(1);
cout << hostel.label() << ": " << hostel.current() << "/"
<< hostel.capacity() << " L, " << hostel.percentFull() << "%\n";
cout << lab.label() << ": " << lab.current() << "/"
<< lab.capacity() << " L, " << lab.percentFull() << "%\n";
}Immediately after construction, hostel stores ("Hostel", 500, 120) and lab stores ("Lab", 300, 80). Their current_ values are independently 120 and 80. ObjectCounter::created belongs to a separate class-wide example.

Worked object trace: calls change one receiver at a time
fill(litres) returns false without changing state when litres <= 0 or the candidate exceeds capacity. Otherwise it adds the amount. drain(litres) similarly rejects a non-positive amount or an amount above current_; otherwise it subtracts and returns true.
Call | Receiver before | Candidate calculation | Return | Receiver after | Other object |
|---|---|---|---|---|---|
|
|
|
|
| lab stays |
|
|
|
|
| lab stays |
|
|
|
|
| lab stays |
|
|
|
|
| hostel stays |
The final calculations are hostel.percentFull() = 100.0 * 280 / 500 = 56.0 and lab.percentFull() = 100.0 * 50 / 300 = 16.666.... With fixed << setprecision(1), the output is exactly:
Hostel: 280/500 L, 56.0%
Lab: 50/300 L, 16.7%
How member functions know the calling object
In hostel.fill(250), the implicit receiver is hostel. In lab.drain(30), it is lab. Inside fill, current_ += litres is conceptually this->current_ += litres. You normally omit this-> when the name is unambiguous.
A const member function promises not to modify the object through that call. After the trace, hostel.current() reads 280, and hostel.percentFull() computes 56.0, without changing hostel. For const WaterTank reserve("Reserve", 200, 50);, reserve.current() is valid and returns 50. reserve.fill(10) is rejected by the compiler because fill is not const.
The expression hostel.current() uses . and returns 280. With WaterTank* p = &hostel;, p->current() also returns 280. The dot accesses a member through an object; the arrow dereferences a pointer before member access.
Class and object traps: what goes wrong and how to repair it
Mistake | What goes wrong | Correction |
|---|---|---|
Treating the class definition as an object at level | A type has no current level | Construct an object first |
Making state public and writing | Callers can break the capacity invariant | Keep state private and use checked methods |
Forgetting that | Intended public calls become inaccessible | Add an explicit |
Writing |
| Write |
Marking | The function promises not to change | Leave mutating operations non-const |
Hand-summing fields to predict | Padding and | Use |
After the trace, WaterTank backup = hostel; copies current value 280. Calling backup.drain(20) gives 280 - 20 = 260, while hostel remains 280. This value-like result follows here. Resource-owning classes may need deliberate copy or move design.
hostel.current_ = 900 fails at compile time because current_ is private. hostel.fill(250) compiles but returns false at runtime because 280 + 250 = 530 > 500.
How exams and interviews test classes, objects and members
Typical questions ask you to identify a class versus an object, classify data, function and static members, recover ObjectCounter::created = 2, locate a private-access error, choose . or ->, decide whether a method may be const, or trace independent states after interleaved calls.
Use five checks on each trace:
Write every object's starting state.
Mark shared static state separately.
Evaluate the called method's guard.
Update only the receiver when the guard passes.
Compute the requested output last.
Here, those checks recover hostel 280, lab 50, percentages 56.0% and 16.7%, and ObjectCounter::created = 2 in the isolated micro-example. Once an ordinary concrete class is clear, Abstract Classes in C++: Pure Virtual Functions, Examples and Errors is the next advanced step for pure virtual functions and runtime dispatch.
Classes and objects in C++: the short version and next step
Keep five rules: a class defines a type; each object holds its own non-static state; a constructor establishes a valid start; a member call acts on one receiver; access and const rules limit what code may do. Replay 120 -> 370 -> 280 -> rejected 530, then explain why lab can still move independently from 80 to 50.
For the broader sequence, continue with the C++ Tutorial: The Complete Learning Path from First Program to STL. For a structured route whose listing includes C++, Coding For Placements is optional.
Keep learning
C++ Classes and Objects MCQs: 11 Solved Questions on Members, Pointers and Inheritance
Work through 11 C++ classes and objects MCQs, then use the fresh explanations and fixed examples to repair mistakes in access, lifetime and inheritance rules.
Classes and Objects in Java: Build and Trace Two Objects Step by Step
Build a Java Student class, create two independent objects, and trace fields, methods, aliases, null references, output, and common errors step by step.
Methods in Java MCQs: 12 Solved Questions on Defining and Invoking Behaviors
Solve 12 Java method questions covering declarations, constructor chains, overloads, overrides, runtime binding, and recursive call traces.
Classes and Objects in OOP: Blueprint, Instance and Worked Example
See exactly what a class defines, what new creates, and how two references can reach one object. Follow two Java traces with object counts and final values.





