Trace the Counter program from Section 3 (static count, constructor prints create id, destructor prints destroy id, objects a and b in main and c in an inner block). Write the exact output.
A class bundles data and functions into a new type; objects are its instances. Covers the C++ class toolkit — scope resolution, inline, static and friend members, this, const and mutable — and the Java counterparts: static blocks, final fields, new and garbage collection.
this is each form saying 'me' — the particular copy being processed right now.};. Members are private by default in a class and public in a struct; otherwise the two are identical in C++.void Box::show() { … }. Functions defined inside the class are implicitly inline.inline is only a request — compilers may ignore it for recursion, loops, static locals or large bodies. Inline functions are type-checked; macros are not.int A::n = 0;); zero-initialised; exists before any object is created.this pointer, uses only static members, called as ClassName::f(); it cannot be const or virtual.this points to the invoking object (absent in static functions). A const member function cannot modify data members — except those declared mutable.new); a static block runs once at class initialisation; final fields are assigned once; unreachable objects are garbage-collected.A C++ class declaration has a name, a body in braces containing data members and member functions, access labels (private:, protected:, public:) that divide the body into sections, and — easy to forget — a semicolon after the closing brace. Each label applies to every member until the next label.
#include <iostream>
using namespace std;
class Box {
double length, width; // data members (private by default)
public:
void set(double l, double w) { // member function defined inside the class
length = l;
width = w;
}
double area() const { return length * width; }
}; // note the semicolon
int main() {
Box b1, b2; // two objects, each with its own length and width
b1.set(4, 3);
b2.set(2.5, 2);
Box* p = &b2; // pointer to an object
cout << b1.area() << " " << p->area() << " " << sizeof(Box) << "\n";
}Each object receives its own copy of the data members — b1.length and b2.length are different variables. The member functions are stored once and shared by all objects; an object does not carry its code around. That is why sizeof(Box) is 16 (two 8-byte doubles) and why the function knows which object to work on only through the hidden this pointer (Section 5).
An empty class still has sizeof equal to 1, so that two distinct objects always have distinct addresses. Members are reached with the dot operator on objects (b1.area()) and the arrow operator on pointers (p->area(), which means (*p).area()).
| Feature | C struct | C++ struct | C++ class |
|---|---|---|---|
| Member functions | Not allowed | Allowed | Allowed |
| Default member access | No access control | public | private |
| Default inheritance mode | No inheritance | public | private |
| Constructors, destructors, virtual functions | No | Yes | Yes |
| Conventional use | Plain records | Simple data aggregates | Types with rules and behaviour |
class, public for struct (and, following from it, the default inheritance mode).A member function can be defined inside the class body (it is then implicitly inline) or declared inside and defined outside. Outside definitions use the scope resolution operator :: to say which class the function belongs to — that is what gives it access to the private members.
#include <iostream>
#include <string>
using namespace std;
class Student {
string name;
int marks;
public:
void setData(string n, int m); // declared inside, defined outside
void show() const { cout << name << ":" << marks << " "; } // implicitly inline
int getMarks() const { return marks; }
};
inline void Student::setData(string n, int m) { // :: ties it to Student
name = n;
marks = m;
}
int main() {
Student s[3]; // array of objects
s[0].setData("Anu", 78);
s[1].setData("Biju", 91);
s[2].setData("Chitra", 85);
int best = 0;
for (int i = 0; i < 3; i++) {
s[i].show();
if (s[i].getMarks() > s[best].getMarks()) best = i;
}
cout << "\nTopper: ";
s[best].show();
cout << "\n";
}void Student::setData(...) — the function belongs to Student's scope.Counter::count, Counter::getCount().::x reaches the global x when a local x hides it.std::cout, Base::show() from a derived class.An inline function asks the compiler to paste the function body at each call site, removing the call overhead (pushing arguments, jumping, returning). It pays off for small, frequently called functions and costs code size for big ones. inline is only a request: compilers usually decline for functions containing loops, switch or goto, recursive functions, functions with static local variables, and large bodies.
SQUARE(i++)A static data member belongs to the class itself rather than to any one object: there is exactly one copy, shared by all objects. It is the C++ way to keep class-wide information such as how many objects exist or the current interest rate for every account.
static, but defined (storage created) outside it: int Counter::count = 0;. Without that line the program compiles but fails at link time.main starts (textbooks phrase this as 'initialised to zero when the first object is created') and lives until the program ends.Counter::count or through any object.inline static int count = 0; may be defined inside the class; static const int members of integral type could always be initialised in the class.#include <iostream>
using namespace std;
class Counter {
static int count; // declaration: one copy shared by all objects
int id;
public:
Counter() { id = ++count; cout << "create " << id << "\n"; }
~Counter() { --count; cout << "destroy " << id << "\n"; }
static int getCount() { return count; } // no 'this'; touches only static data
};
int Counter::count = 0; // definition (storage) outside the class
int main() {
cout << Counter::getCount() << "\n"; // 0: exists before any object
Counter a, b;
{
Counter c;
cout << Counter::getCount() << "\n"; // 3
} // c destroyed here
cout << a.getCount() << "\n"; // 2 (callable through an object too)
return 0;
}A static member function is called without any object — Counter::getCount() — so it receives no this pointer. Consequently it can use only static data members and other static functions directly, and it cannot be declared const (there is no object to protect) or virtual (there is no object whose type could decide).
| Non-static (instance) member | Static (class) member | |
|---|---|---|
| Number of copies | One per object | One per class |
| Lifetime | While its object lives | Whole program (C++) / from class loading (Java) |
| Typical access | obj.member | Class::member (C++), Class.member (Java) |
| this pointer (functions) | Yes | No |
| Can use directly | Static and non-static members | Static members only |
int Counter::count = 0; gives no compile error — the build fails at the link step with 'undefined reference to Counter::count' (or 'Undefined symbols').Sometimes a function that is not a member of a class needs its private data — typically a function that works on two classes at once, or an operator whose left operand is not an object of the class. C++ lets the class grant that access by declaring the function a friend.
#include <iostream>
using namespace std;
class Meters; // forward declaration: Feet's friend mentions Meters
class Feet {
double ft;
public:
Feet(double f) : ft(f) {}
friend double totalMeters(const Feet&, const Meters&);
};
class Meters {
double m;
public:
Meters(double v) : m(v) {}
friend double totalMeters(const Feet&, const Meters&);
};
// an ordinary function (no Feet:: prefix), yet it may read both private members
double totalMeters(const Feet& f, const Meters& x) {
return f.ft * 0.3048 + x.m;
}
int main() {
Feet f(10);
Meters m(2);
cout << totalMeters(f, m) << "\n"; // called like a normal function
}ClassName::, called like a normal function (totalMeters(f, m)), never as f.totalMeters().this pointer, so it must name members through an object: f.ft, not just ft.friend declaration may appear in the private or the public section — it makes no difference.#include <iostream>
class Vault {
int code = 4711;
friend class Auditor; // granted by Vault, not claimed by Auditor
};
class Auditor {
public:
int peek(const Vault& v) { return v.code; } // allowed
};
int main() { Vault v; Auditor a; std::cout << a.peek(v) << "\n"; }Friendship is granted, not taken, and it is deliberately narrow: it is not inherited (a class derived from Auditor is not Vault's friend), not transitive (a friend of Auditor is not Vault's friend) and not mutual (Vault gets no access to Auditor's privates). A single member function of another class can also be befriended: friend void Auditor::check(const Vault&);.
friend ostream& operator<<(ostream&, const Complex&), where the left operand is a stream, not your object. Java has no friends; package-private access and nested classes fill the same need.Every non-static member function receives a hidden argument called this — a pointer to the object on which the function was invoked. Inside p.setX(5), this equals &p; writing x = 5 in the body really means this->x = 5. Its type is Point* const (the pointer itself cannot be re-pointed); inside a const member function it is const Point* const.
this->x = x;.return *this;.registry.add(this);.operator=: if (this != &other) { … }.#include <iostream>
using namespace std;
class Point {
int x, y;
mutable int reads = 0; // may change even inside const functions
public:
Point(int x, int y) { this->x = x; this->y = y; } // this-> resolves the clash
Point& setX(int x) { this->x = x; return *this; } // return the invoking object
Point& setY(int y) { this->y = y; return *this; }
void show() const { // const: promises not to modify x or y
++reads; // allowed only because reads is mutable
cout << "(" << x << ", " << y << ") read " << reads << "\n";
}
};
int main() {
Point p(1, 2);
p.setX(5).setY(7).show(); // (5, 7) read 1
const Point q(3, 4);
q.show(); // (3, 4) read 1
q.show(); // (3, 4) read 2
// q.setX(9); // error: setX is not a const member function
}A const member function (void show() const) promises not to modify the object's data members; the compiler rejects any attempt. A const object — or a const reference such as const Point& — may call only const member functions. Mark every function that merely reads the object as const; otherwise it becomes unusable on const objects.
mutable exempts a data member from that promise. It is meant for internal bookkeeping that does not change the object's logical value: access counters, cached results, a mutex inside a thread-safe class.
int get() const; as 'get() treats *this as read-only'. And remember: static member functions have no this, so they can be neither const nor virtual.An array of objects (Student s[3];) calls the default constructor for each element and is used like any array: s[i].show(). Objects can be passed to functions by value (the function receives a copy, the caller's object is untouched), by reference (the function works on the caller's object) or by pointer; functions may also return objects.
#include <iostream>
using namespace std;
class Wallet {
public:
int cash = 100;
};
void spendCopy(Wallet w) { w.cash -= 30; } // works on a copy
void spendReal(Wallet& w) { w.cash -= 30; } // works on the caller's object
void spendPtr(Wallet* w) { w->cash -= 30; } // works through the address
int main() {
Wallet a;
spendCopy(a); cout << a.cash << " "; // 100
spendReal(a); cout << a.cash << " "; // 70
spendPtr(&a); cout << a.cash << "\n"; // 40
}A nested class is declared inside another class — for example a Node inside a LinkedList, or an iterator inside a container. Its name is in the enclosing class's scope (Outer::Inner). Since C++11 a nested class is a member and may use the enclosing class's private members (through an object); the enclosing class gets no special access to the nested class's private members.
A local class is defined inside a function and is visible only there. Its member functions must be defined inside the class body; it cannot have static data members; and it may use the function's static locals, global variables and types — but not the function's automatic (ordinary local) variables.
#include <iostream>
using namespace std;
class Outer {
int secret = 42;
public:
class Inner { // nested class: a member of Outer
public:
int peek(const Outer& o) { return o.secret; } // allowed since C++11
};
};
int main() {
Outer o;
Outer::Inner in;
cout << in.peek(o) << "\n";
static int calls = 0;
struct Local { // local class: exists only inside main
void hit() { ++calls; } // may use a static local of the function
};
Local l; l.hit(); l.hit();
cout << calls << "\n";
}In Java everything lives inside classes, and method bodies are always written inside the class — there is no :: and no separate definition. A source file may contain at most one public top-level class, and the file must carry that class's name (Account.java).
Box b; in Java declares only a reference; no object exists yet. b = new Box(); allocates the object on the heap, runs a constructor and returns the reference. Fields get default values (0, 0.0, false, '\u0000', null); local variables get none, and using one before assignment is a compile-time error.
public class Demo {
static int a = 10;
int b;
static { // runs once, when the class is initialised
System.out.println("static block, a = " + a);
}
{ // instance initializer: runs for every object,
b = 5; // before the constructor body
System.out.println("instance block, b = " + b);
}
Demo() { System.out.println("constructor"); }
public static void main(String[] args) {
System.out.println("main starts");
new Demo();
new Demo();
}
}
/* Output:
static block, a = 10
main starts
instance block, b = 5
constructor
instance block, b = 5
constructor */Static fields and methods belong to the class: Math.PI, Math.sqrt(), main(). A static method cannot use this or instance members directly. The static block of Demo ran before main starts because the JVM must initialise the class before calling its static main.
final marks something that cannot change: a final variable is assigned exactly once (a constant); a blank final field — declared without a value — must be definitely assigned exactly once, either in an instance initializer block or along every constructor path (a constructor that starts with this(…) leaves it to the constructor it calls); static final double RATE = 7.5; is a class constant. A final method cannot be overridden and a final class cannot be extended (String, Integer, Math).
There is no delete and no destructor. The garbage collector reclaims an object once no live reference can reach it — after its reference is set to null or reassigned, after the method that created it returns, or when a group of objects refer only to each other (an island of isolation). System.gc() (or Runtime.getRuntime().gc()) is only a request. The old finalize() hook was deprecated in Java 9 and marked for removal in Java 18; release files and sockets with try-with-resources instead.
| Feature | C++ | Java |
|---|---|---|
| Member function defined outside the class | Yes, with :: | No — bodies always inside the class |
| Default member access | private (class), public (struct) | package-private |
| Where objects live | Stack, static area or heap (new) | Always the heap (new); variables hold references |
| Object clean-up | Destructor; delete for heap objects | Garbage collector; no destructors |
| Class-wide data | static member, defined outside the class | static field; static initializer block |
| Constants | const, constexpr | final |
| Friend functions / classes | Yes | No (package access instead) |
| struct, union, sizeof | Yes | No |
| this | A pointer: this->x | A reference: this.x |
Try the problem first, then reveal the working one step at a time.
Trace the Counter program from Section 3 (static count, constructor prints create id, destructor prints destroy id, objects a and b in main and c in an inner block). Write the exact output.
In the Feet/Meters program, explain why class Meters; must appear before class Feet, why totalMeters is written without Feet::, and compute its result for Feet(10) and Meters(2).
Predict the output. class Ticket { static int issued; final int number; static { System.out.println("Ticket class loaded"); } Ticket() { number = ++issued; } } and, in the main method of a separate class Main: System.out.println("start"); Ticket t1 = new Ticket(); Ticket t2 = new Ticket(); Ticket t3 = t2; System.out.println(t1.number + " " + t2.number + " " + t3.number + " " + Ticket.issued);
What does this program print? class A { public: static int n; A() { n++; } }; int A::n; int main() { A a, b; A c[3]; A* p = new A; cout << A::n; delete p; }
Find sizeof(E) and sizeof(F) for class E {}; and class F { int a; static double d; void f(); }; on a typical compiler with 4-byte int, and justify each.
Why does this fail to compile, and what is the minimal fix? class Point { int x = 1; public: void show() { cout << x; } }; int main() { const Point p; p.show(); }
Java: after these statements, which objects are eligible for garbage collection? Box a = new Box(); Box b = new Box(); Box c = a; a = null; b = c; c = null; (call the objects #1 and #2 in order of creation).
Inside void f() { int n = 5; static int s = 1; class L { static int k; public: int g() { return s; } int h() { return n; } }; }, which of the three marked members are errors and why?
int A::n;) — omit it and you get a linker error, not a compiler error (C++17 inline static is the exception).this, not called with the dot operator, not inherited. Declaring it in the private section does not hide it.this — so they cannot be const or virtual and cannot touch non-static members directly.inline is a request the compiler may ignore; and every member function defined inside the class body is already inline without the keyword.System.gc() only suggests a collection; finalize() is deprecated and unreliable. In C++, objects in an array are destroyed in reverse order of construction.12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
struct isModelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.