PadhaikoAll subjects

Objects and Classes

Object Oriented Programming (ENCT 151)

Open in the Padhaiko app

3.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.

Definition

Access Specifiers in a C++ Class

Basic Class SyntaxC++
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 body

3.2 Objects and the member access

Declaring a class only creates a type. Memory for instance data is allocated when objects are instantiated:


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:

  1. 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.
  2. Per-Object Data Members: Every object receives its own separate copy of all non-static data members (s1.roll and s2.roll occupy distinct addresses).
  3. 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 &s1 secretly via the this pointer so the shared code operates on s1's data.
  4. Shared static Data Members: Declared inside the class with static, 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:

  1. Inside the Class Body: Written directly within class { ... };. Functions defined inside the class are implicitly treated as inline by the compiler—best kept for short 1–3 line methods.
  2. Outside the Class Body: Declared inside the class as a prototype, and defined outside using the scope resolution operator (::) (ReturnType ClassName::funcName(params)):
Out-of-Line Member Function DefinitionC++
#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:

Making an Out-of-Line Member Function InlineC++
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).


3.7 Constructors and destructors

Definition

Constructor and Destructor

Types of Constructors

  1. 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.
  2. Parameterized Constructor: Accepts arguments to initialize objects with custom values (Complex(double r, double i)).
  3. 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; or Complex c2(c1);),
    • Passing an object by value to a function, or
    • Returning an object by value (when not elided).

3.8 Object as function arguments

Objects can be passed to functions in three ways:

  1. Pass by Value (void f(Complex c)): Creates a copy via the copy constructor. Changes inside f do not affect the caller's object, but copying large objects is expensive.
  2. Pass by Reference (void f(Complex &c) or void 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.
  3. Pass by Pointer (void f(Complex *c)): Passes the object's address; inside f, members are accessed via c->....

3.9 Returning objects from functions

Functions can return objects by value or by reference:


3.10 Array of objects

An array of objects allocates contiguous storage for multiple instances of a class:

Array of ObjectsC++
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 ->:

Pointer to Single Object and Array of ObjectsC++
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:


3.13 Dynamic constructors

Definition

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:

  1. A destructor (delete[] ptr;) to prevent memory leaks,
  2. A deep copy constructor (ClassName(const ClassName &)), and
  3. 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

  1. Disambiguating Shadowed Names: When a parameter has the same name as a data member (this->x = x;).
  2. Method Chaining (Fluent Interface): Returning *this by reference (Box &setL(double l) { this->l = l; return *this; }) enables b.setL(4).setW(5).setH(6);.
  3. Self-Assignment Check: Comparing if (this == &other) return *this; inside operator=.
  4. Passing the Current Object to Another Function: Passing *this or this.

3.15 Static data member and static member function


3.16 Constant member functions and constant objects


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:


Worked Examples

Example 1

1 (6 marks)

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:

Dynamic Constructor, Deep Copy, Destructor, and Static CounterC++
#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") constructs s1: liveCount becomes 1.
  • Inside the inner block { ... }, DynString s2 = s1; calls the copy constructor: liveCount becomes 2. s2.show() prints Institute of Engineering (live=2).
  • Leaving the inner block destroys s2 (~DynString()): s2.buf is freed, liveCount decrements to 1, and s1.buf remains intact because it was deep-copied.
  • s1.show() prints Institute of Engineering (live=1), and DynString::getLiveCount() prints 1.
Answer:

Output:

  • Institute of Engineering (live=2)
  • Institute of Engineering (live=1)
  • Static check: 1
Example 2

2 (5 marks)

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:

Friend Function Accessing Private Data of Two ClassesC++
#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:

  • d1 in centimetres: 2.5 * 100.0 = 250.0 cm.
  • d2 in centimetres: 8.0 * 30.48 = 243.84 cm.
  • Since 250.0 >= 243.84, maxInCm(d1, d2) returns 250.
Answer:

Output: Larger (cm): 250 (2.5 m = 250 cm > 8.0 ft = 243.84 cm).


Exercises

Exercises — Objects and Classes

Question 1

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. static data 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.

Answer:

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.

Question 2

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:

  1. An object is initialized from another (T b = a; or T b(a);).
  2. An object is passed by value into a function.
  3. 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).

Answer:

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.

Question 3

Trace the construction and destruction order for the following C++ program using composition (object as member) and static counters, and write its exact output.

Composition Construction and Destruction OrderC++
#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).

Answer:

Output: Engine(1500) Car(1) ~Car(1) ~Engine(1500)

Question 4

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:

  • const Member Function (void f() const): Receives a const ClassName * const this pointer. It can read all data members (and call other const member functions) of that specific object, but cannot modify non-mutable data members.
  • static Member Function (static void g()): Has no this pointer at all because it is not tied to any object instance. It can access only static data members and other static functions directly.

Invocation Rules:

  • A const member function must be called on an object (obj.f() or constObj.f())—in fact, const objects can call only const member functions.
  • A static member function can be called directly via the class name (ClassName::g()) even when no objects exist (or via obj.g()).
Answer:

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.

Question 5

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:

  1. Friendship is explicitly granted inside the class (friend void fn(A &); or friend class B;), not requested from outside.
  2. It is not symmetric (A trusting B does not mean B trusts A), not transitive, and not inherited by derived classes.
  3. A friend function is not a member of the class, has no this pointer, 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:

Method Chaining Using this PointerC++
#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.

Answer:

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.

← Basics of C++ ProgrammingOperator Overloading →