Objects and Classes
Open in the Padhaiko app3.1 C++ classes
A class is a user-defined data type that binds data members (attributes) and member functions (methods) together under explicit access control.
Access Specifiers in a C++ Class
private:Accessible only to member functions andfriends of the same class. This is the default access level in aclass.public:Accessible from any code where the object is visible (forms the class's external interface).protected:Accessible within the class, itsfriends, and its derived classes (used in inheritance).
class Student {
private:
int roll;
double gpa;
public:
void setData(int r, double g) {
roll = r;
gpa = g;
}
void display() const;
}; // Semicolon is mandatory after class body3.2 Objects and the member access
Declaring a class only creates a type. Memory for instance data is allocated when objects are instantiated:
Student s1, s2;creates two independentStudentobjects.- Dot operator (
.): Accesses public members on an object or reference (s1.setData(10, 3.75);,s1.display();). - Arrow operator (
->): Accesses public members through a pointer to an object (Student *ptr = &s1; ptr->display();, equivalent to(*ptr).display();).
3.3 Relation of object, class and memory
Understanding how C++ lays out classes and objects in memory is a frequent Institute of Engineering exam topic:
- Class Definition Uses Zero Instance Memory: Defining
class Box { int l, b, h; };tells the compiler the layout; no object storage is allocated until an object is created. - Per-Object Data Members: Every object receives its own separate copy of all non-static data members (
s1.rollands2.rolloccupy distinct addresses). - Shared Member Functions: Member functions are compiled once and stored in the program's code segment—they are not duplicated per object. When
s1.display()executes, the compiler passes&s1secretly via thethispointer so the shared code operates ons1's data. - Shared
staticData Members: Declared inside the class withstatic, a single copy exists in static/global memory shared across all objects of the class.
3.4 Defining member function
Member functions can be defined in two ways:
- Inside the Class Body: Written directly within
class { ... };. Functions defined inside the class are implicitly treated asinlineby the compiler—best kept for short 1–3 line methods. - Outside the Class Body: Declared inside the class as a prototype, and defined outside using the scope resolution operator (
::) (ReturnType ClassName::funcName(params)):
#include <iostream>
using namespace std;
class Box {
private:
double length, width, height;
public:
void set(double l, double w, double h);
double volume() const;
};
void Box::set(double l, double w, double h) {
length = l; width = w; height = h;
}
double Box::volume() const {
return length * width * height;
}3.5 Defining outer function inline
An out-of-line member function is not inline by default. To request inline expansion while keeping the class interface clean, prefix the outer definition (or its declaration inside the class) with the inline keyword:
class Circle {
double r;
public:
void setRadius(double rad) { r = rad; } // Implicitly inline
double area() const; // Prototype
};
inline double Circle::area() const { // Explicitly inline outside class
return 3.14159 * r * r;
}3.6 Objects as member
A class can contain objects of another class as data members. This is called composition (or aggregation / container class) and models a has-a relationship (e.g., a Car has an Engine; an Employee has a Date of joining).
- Construction Order: Member objects are constructed before the enclosing class's constructor body runs, in the order they are declared inside the class (not the order listed in the initializer list).
- Initialization: Use a member initializer list (
Employee(int id, int d, int m, int y) : empId(id), doj(d, m, y) {}) to pass arguments to member-object constructors. - Destruction Order: Exactly the reverse—the enclosing class's destructor runs first, followed by member objects in reverse declaration order.
3.7 Constructors and destructors
Constructor and Destructor
- Constructor: A special member function with the same name as the class and no return type (not even
void). It runs automatically whenever an object is created to initialize its data members. - Destructor: A special member function named
~ClassName()with no return type and no parameters (cannot be overloaded). It runs automatically when an object goes out of scope or is deleted, releasing acquired resources (heap memory, file handles).
Types of Constructors
- Default Constructor: Takes no arguments (or all arguments have defaults). If you declare no constructors, the compiler generates a trivial default constructor; once you define any constructor, the compiler stops generating the default one unless you explicitly write it or use
= default. - Parameterized Constructor: Accepts arguments to initialize objects with custom values (
Complex(double r, double i)). - Copy Constructor: Initializes a new object as a copy of an existing object of the same class:
ClassName(const ClassName &other). Called when:- Initializing an object from another (
Complex c2 = c1;orComplex c2(c1);), - Passing an object by value to a function, or
- Returning an object by value (when not elided).
- Initializing an object from another (
3.8 Object as function arguments
Objects can be passed to functions in three ways:
- Pass by Value (
void f(Complex c)): Creates a copy via the copy constructor. Changes insidefdo not affect the caller's object, but copying large objects is expensive. - Pass by Reference (
void f(Complex &c)orvoid f(const Complex &c)): Passes no copy; operates directly on the caller's object.const Complex &is the standard idiom for read-only object parameters. - Pass by Pointer (
void f(Complex *c)): Passes the object's address; insidef, members are accessed viac->....
3.9 Returning objects from functions
Functions can return objects by value or by reference:
- Return by Value (
Complex add(const Complex &a, const Complex &b)): Constructs a result object inside the function and returns it (modern compilers apply Return Value Optimization to avoid extra copies). - Return by Reference (
Complex &maxMag(Complex &a, Complex &b)): Returns an alias to an existing object (such as*thisor a reference parameter) without copying. Never return a reference to a local object created inside the function.
3.10 Array of objects
An array of objects allocates contiguous storage for multiple instances of a class:
Student list[3]; // Calls default constructor 3 times
for (int i = 0; i < 3; ++i) {
list[i].display();
}If a class defines only parameterized constructors and no default constructor, declaring Student list[3]; fails to compile unless elements are explicitly initialized (e.g., Box b[2] = {Box(1, 2, 3), Box(4, 5, 6)};).
3.11 Pointer to objects
A pointer of type ClassName * stores the memory address of an object and accesses its public members using ->:
Box b1(2, 3, 4);
Box *p = &b1;
cout << p->volume() << endl; // Arrow operator
Box arr[2] = { Box(1, 1, 1), Box(2, 2, 2) };
Box *q = arr;
cout << (q + 1)->volume() << endl; // Accesses arr[1]3.12 Dynamic memory allocation for objects
Using new and delete with classes allocates objects on the heap and automatically invokes constructors and destructors:
Box *p = new Box(3, 4, 5);allocates memory on the heap and invokesBox(3, 4, 5).delete p;invokes~Box()first, then frees the heap block.Box *arr = new Box[5];invokes the default constructor 5 times;delete[] arr;invokes~Box()5 times in reverse order and frees the array.
3.13 Dynamic constructors
Dynamic Constructor
A dynamic constructor allocates memory dynamically at run time (using new / new[]) inside the constructor so each object allocates only as much memory as it needs (for example, a variable-length String or Matrix).
Any class with a dynamic constructor must also define:
- A destructor (
delete[] ptr;) to prevent memory leaks, - A deep copy constructor (
ClassName(const ClassName &)), and - A copy assignment operator (
operator=) to prevent double-free bugs (the Rule of Three).
3.14 Pointer
Inside every non-static member function, C++ provides an implicit constant pointer called this, whose type in class T is T * const (or const T * const inside a const member function). It holds the memory address of the calling object.
Uses of the this Pointer
- Disambiguating Shadowed Names: When a parameter has the same name as a data member (
this->x = x;). - Method Chaining (Fluent Interface): Returning
*thisby reference (Box &setL(double l) { this->l = l; return *this; }) enablesb.setL(4).setW(5).setH(6);. - Self-Assignment Check: Comparing
if (this == &other) return *this;insideoperator=. - Passing the Current Object to Another Function: Passing
*thisorthis.
3.15 Static data member and static member function
staticData Member: Shared by all objects of the class (exists even if zero objects are instantiated). Declared inside the class withstaticand defined/initialized once outside the class (int Counter::count = 0;). (C++17 also allowsinline static int count = 0;inside the class.)staticMember Function: Belongs to the class rather than any individual object, so it has nothispointer. Therefore:- It can access only
staticdata members and otherstaticmember functions directly. - It can be called via the class name (
Counter::getCount()) without creating an object.
- It can access only
3.16 Constant member functions and constant objects
constMember Function: Declared withconstafter the parameter list (int getX() const;, included in both declaration and out-of-line definition). It promises not to modify any non-mutabledata member of the invoking object (thethispointer becomesconst T * const).constObject: Declared asconst Point origin(0, 0);. Its data members cannot be modified after construction, and the compiler allows calling onlyconstmember functions on it—calling a non-constmethod on aconstobject is a compile error.
3.17 Friend functions and friend classes
Normally, non-member functions cannot access private or protected members of a class. The friend keyword grants an explicit exception:
- Friend Function: A non-member function (or a member function of another class) declared with
friendinside a class can access allprivateandprotectedmembers of that class using an object parameter (obj.secret). - Friend Class:
friend class B;placed inside classAgrants all member functions ofBaccess toA's private and protected members.
Worked Examples
1
Write a C++ class DynString that uses a dynamic constructor, a deep copy constructor, a destructor, and a static counter tracking how many DynString objects currently exist in memory. Trace the output of main().
Designing DynString with Dynamic Memory and static Counter: Each object allocates strlen(s) + 1 bytes on the heap with new char[len + 1] and increments liveCount. Both the destructor (delete[] buf) and the deep copy constructor maintain valid independent buffers:
#include <iostream>
#include <cstring>
using namespace std;
class DynString {
private:
char *buf;
static int liveCount;
public:
DynString(const char *s = "") {
buf = new char[strlen(s) + 1];
strcpy(buf, s);
++liveCount;
}
DynString(const DynString &other) {
buf = new char[strlen(other.buf) + 1];
strcpy(buf, other.buf);
++liveCount;
}
~DynString() {
delete[] buf;
--liveCount;
}
void show() const { cout << buf << " (live=" << liveCount << ")" << endl; }
static int getLiveCount() { return liveCount; }
};
int DynString::liveCount = 0;
int main() {
DynString s1("Institute of Engineering");
{
DynString s2 = s1; // Invokes deep copy constructor
s2.show();
} // s2 destroyed here -> liveCount drops back to 1
s1.show();
cout << "Static check: " << DynString::getLiveCount() << endl;
return 0;
}Tracing Object Lifetimes:
s1("Institute of Engineering")constructss1:liveCountbecomes1.- Inside the inner block
{ ... },DynString s2 = s1;calls the copy constructor:liveCountbecomes2.s2.show()printsInstitute of Engineering (live=2). - Leaving the inner block destroys
s2(~DynString()):s2.bufis freed,liveCountdecrements to1, ands1.bufremains intact because it was deep-copied. s1.show()printsInstitute of Engineering (live=1), andDynString::getLiveCount()prints1.
Output:
Institute of Engineering (live=2)Institute of Engineering (live=1)Static check: 1
2
Demonstrate how a friend function bridges two separate classes Meter and Feet by writing compareLength(const Meter &, const Feet &) to return the larger distance in centimetres (1 m = 100 cm, 1 ft = 30.48 cm), and verify the result for 2.5 m and 8.0 ft.
Forward Declaration and friend Prototype: Because Meter mentions Feet in the friend declaration before Feet is defined, class Feet; must be forward-declared first:
#include <iostream>
using namespace std;
class Feet; // Forward declaration
class Meter {
double m;
public:
Meter(double val) : m(val) {}
friend double maxInCm(const Meter &a, const Feet &b);
};
class Feet {
double ft;
public:
Feet(double val) : ft(val) {}
friend double maxInCm(const Meter &a, const Feet &b);
};
double maxInCm(const Meter &a, const Feet &b) {
double cmA = a.m * 100.0;
double cmB = b.ft * 30.48;
return (cmA >= cmB) ? cmA : cmB;
}
int main() {
Meter d1(2.5);
Feet d2(8.0);
cout << "Larger (cm): " << maxInCm(d1, d2) << endl;
return 0;
}Numeric Evaluation:
d1in centimetres:2.5 * 100.0 = 250.0 cm.d2in centimetres:8.0 * 30.48 = 243.84 cm.- Since
250.0 >= 243.84,maxInCm(d1, d2)returns250.
Output: Larger (cm): 250 (2.5 m = 250 cm > 8.0 ft = 243.84 cm).
Exercises
Exercises — Objects and Classes
Explain the relationship between a class, its objects, and memory in C++. How does the compiler know which object's data to modify inside a shared member function?
Memory Allocation for Classes vs. Objects:
- A class definition only describes the blueprint; it reserves zero bytes for non-static data members.
- Each object instantiated from the class receives its own separate block of memory for its non-static data members.
- Member functions are stored once in the code segment and shared across all objects.
staticdata members are stored once in static memory and shared by all objects.
Role of the this Pointer: When obj.method(arg) is called, the compiler implicitly passes the address &obj as a hidden argument (this pointer). Inside the shared member function, accessing a data member x is translated to this->x, ensuring the function reads and writes only obj's memory.
A class allocates no instance memory; each object holds its own non-static data members while sharing one copy of member functions and static data members. The hidden this pointer passes the calling object's address to the shared member function.
What is a copy constructor? When is it invoked automatically, and why must a class that allocates heap memory in its constructor define its own copy constructor?
Definition and Automatic Invocation: A copy constructor has signature ClassName(const ClassName &other) and initializes a new object from an existing one. It is invoked automatically when:
- An object is initialized from another (
T b = a;orT b(a);). - An object is passed by value into a function.
- An object is returned by value from a function (subject to copy elision).
Why Custom Copy Constructor Is Needed for Heap Members: The compiler-generated copy constructor performs a shallow (member-wise) copy, copying raw pointer addresses rather than the heap buffers they point to. Both objects then share one heap block, causing one object's changes to corrupt the other and triggering a double-free crash when both destructors run. A user-defined copy constructor allocates a new buffer and copies the data (deep copy).
A copy constructor (T(const T &)) creates an object as a copy of another during copy initialization, pass-by-value, or return-by-value. Classes managing heap memory must define a deep copy constructor so each object owns an independent heap block and avoids double-free errors.
Trace the construction and destruction order for the following C++ program using composition (object as member) and static counters, and write its exact output.
#include <iostream>
using namespace std;
class Engine {
int cc;
public:
Engine(int c) : cc(c) { cout << "Engine(" << cc << ") "; }
~Engine() { cout << "~Engine(" << cc << ") "; }
};
class Car {
Engine eng;
int id;
public:
Car(int i, int c) : eng(c), id(i) { cout << "Car(" << id << ") "; }
~Car() { cout << "~Car(" << id << ") "; }
};
int main() {
Car c1(1, 1500);
return 0;
}Construction Sequence: When Car c1(1, 1500); is created, member objects are constructed before the enclosing class constructor body executes. Thus Engine(1500) runs first, followed by Car(1)'s body.
Destruction Sequence: When c1 goes out of scope at the end of main(), destruction occurs in exact reverse order: first ~Car(1) runs its body, and then member eng is destroyed via ~Engine(1500).
Output: Engine(1500) Car(1) ~Car(1) ~Engine(1500)
Differentiate between const member functions and static member functions in terms of their this pointer, what members they can access, and how they are invoked.
this Pointer and Member Access:
constMember Function (void f() const): Receives aconst ClassName * const thispointer. It can read all data members (and call otherconstmember functions) of that specific object, but cannot modify non-mutabledata members.staticMember Function (static void g()): Has nothispointer at all because it is not tied to any object instance. It can access onlystaticdata members and otherstaticfunctions directly.
Invocation Rules:
- A
constmember function must be called on an object (obj.f()orconstObj.f())—in fact,constobjects can call onlyconstmember functions. - A
staticmember function can be called directly via the class name (ClassName::g()) even when no objects exist (or viaobj.g()).
A const member function has a const this pointer, is invoked on an object (including const objects), and reads instance data without modifying it. A static member function has no this pointer, can be called via ClassName::func(), and accesses only static members.
State the rules of friend functions and friend classes in C++, and write a short C++ program using method chaining with the this pointer on a Box class (setL, setW, setH, volume) for dimensions 4, 5, 6.
Rules of friend:
- Friendship is explicitly granted inside the class (
friend void fn(A &);orfriend class B;), not requested from outside. - It is not symmetric (
AtrustingBdoes not meanBtrustsA), not transitive, and not inherited by derived classes. - A
friendfunction is not a member of the class, has nothispointer, and is called normally with object arguments.
Method Chaining with *this: Returning Box & (return *this;) from each setter lets calls chain on the same object:
#include <iostream>
using namespace std;
class Box {
int l, w, h;
public:
Box &setL(int l) { this->l = l; return *this; }
Box &setW(int w) { this->w = w; return *this; }
Box &setH(int h) { this->h = h; return *this; }
int volume() const { return l * w * h; }
};
int main() {
Box b;
cout << b.setL(4).setW(5).setH(6).volume() << endl;
return 0;
}With l = 4, w = 5, h = 6, volume() returns 4 * 5 * 6 = 120.
Friendship is one-way (not symmetric, transitive, or inherited) and grants non-members access to private/protected data. Returning *this by reference (Box &) enables chaining b.setL(4).setW(5).setH(6).volume(), which prints 120.