3 Classes Objects

Object Oriented Programming · Unit 3 · 8 hrs

Classes & Objects

Exam-focused notes for Classes & Objects (Object Oriented Programming, CSC166): what the TU syllabus asks and how it has actually been tested, with 12 solved past questions from this unit.

Classes & Objects in short

This unit is the heart of C++'s object model: how a class is declared and its members accessed, how constructors and destructors initialize and clean up objects, the different kinds of constructor, how objects are passed to and returned from functions, how a class compares with a C struct, how memory is allocated for objects and their member functions, and how static members and out of class member function definitions work.

Classes & Objects: notes

A Simple Class and Object

A class is declared with the keyword class followed by a body containing data members (variables) and member functions, grouped under the access labels private, protected and public; if no label is given, members default to private. A class only describes what its objects will contain; actually creating a variable of that type, called declaring an object, is written exactly like declaring a variable of any built in type.

#include <iostream>
using namespace std;

class Item {
    int number;      // private by default
    float cost;
public:
    void getData(int a, float b) {
        number = a;
        cost = b;
    }
    void putData() {
        cout << "Number: " << number << ", Cost: " << cost << endl;
    }
};

int main() {
    Item x;          // x is an object of class Item
    x.getData(100, 75.5f);
    x.putData();
    return 0;
}

Accessing members of class

Because number and cost are private, main() cannot touch them directly; it can only call the class's own public member functions on an object, using the dot operator, objectName.functionName(arguments). This is what forces all access to an object's data through the interface the class itself defines, and it is the practical form encapsulation takes in code.

Initialization of class objects: (Constructor, Destructor)

A constructor is a special member function that runs automatically the moment an object is created, and its job is to initialize that object's data members; it always has the exact same name as its class and has no return type at all, not even void. A destructor is the mirror image, a special member function that runs automatically when an object's lifetime ends, whether because the block it was declared in ends, the program ends, or delete is applied to a pointer to it; a destructor shares the class's name too but is prefixed with ~, takes no arguments and returns nothing, and a class can only ever have one destructor.

#include <iostream>
using namespace std;

class Logger {
public:
    Logger() { cout << "Logger created" << endl; }
    ~Logger() { cout << "Logger destroyed" << endl; }
};

int main() {
    Logger log;   // constructor runs here
    return 0;     // destructor runs here, when log goes out of scope
}

What this unit covers

  • A Simple Class and Object
  • Accessing members of class
  • Initialization of class objects: (Constructor, Destructor)
  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor
  • The Default Copy Constructor
  • Objects as Function Arguments
  • Returning Objects from Functions
  • Structures and Classes
  • Memory allocation for Objects
  • Static members
  • Member functions defined outside the class

Initialization of class objects

2080 · 10 marks

What is constructor? Why constructor is needed in a class? Illustrate the types of constructor with an example.[10]

Show solved answer

Constructor in C++

Definition of Constructor

A constructor is a special member function of a class that is automatically called when an object of that class is created. It has the same name as the class and is used to initialize the data members of the class.

Key Characteristics of a Constructor:

  • It has the same name as the class
  • It has no return type (not even void)
  • It is called automatically when an object is created
  • It cannot be inherited, but a derived class can call the base class constructor
  • It can be overloaded

Why is a Constructor Needed in a Class?

When an object is created, its data members may contain garbage values if not initialized. A constructor is needed because:

  1. Automatic Initialization: It automatically initializes data members when an object is created, avoiding garbage values.
  2. Memory Allocation: It can allocate dynamic memory using the new operator at the time of object creation.
  3. No Manual Call Required: Unlike regular functions, the programmer does not need to explicitly call it; it runs automatically.
  4. Ensures Valid State: It ensures that an object always starts in a valid, well-defined state.
  5. Resource Acquisition: It can open files, establish connections, or acquire any resources needed by the object.

As seen in the notes, a class like string uses a constructor string(char *c) to allocate memory using new and copy data, ensuring the object is properly set up from the moment it is created.


Types of Constructors

There are three main types of constructors in C++:

1. Default Constructor

A constructor that takes no arguments (or has all default arguments). It is called automatically when an object is created without any parameters.

#include <iostream>
using namespace std;

class Student {
private:
    int rollNo;
    float marks;

public:
    // Default Constructor
    Student() {
        rollNo = 0;
        marks = 0.0;
        cout << "Default Constructor called!" << endl;
    }

    void display() {
        cout << "Roll No: " << rollNo << ", Marks: " << marks << endl;
    }
};

int main() {
    Student s1;   // Default constructor is called automatically
    s1.display();
    return 0;
}

Output:

Default Constructor called!
Roll No: 0, Marks: 0.0

2. Parameterized Constructor

A constructor that accepts one or more arguments to initialize data members with specific values at the time of object creation.

#include <iostream>
using namespace std;

class Student {
private:
    int rollNo;
    float marks;

public:
    // Parameterized Constructor
    Student(int r, float m) {
        rollNo = r;
        marks = m;
        cout << "Parameterized Constructor called!" << endl;
    }

    void display() {
        cout << "Roll No: " << rollNo << ", Marks: " << marks << endl;
    }
};

int main() {
    Student s1(101, 85.5);   // Parameterized constructor called
    Student s2(102, 90.0);
    s1.display();
    s2.display();
    return 0;
}

Output:

Parameterized Constructor called!
Parameterized Constructor called!
Roll No: 101, Marks: 85.5
Roll No: 102, Marks: 90.0

3. Copy Constructor

A constructor that creates a new object as a copy of an existing object. It takes a reference to an object of the same class as its argument.

#include <iostream>
using namespace std;

class Student {
private:
    int rollNo;
    float marks;

public:
    // Parameterized Constructor
    Student(int r, float m) {
        rollNo = r;
        marks = m;
    }

    // Copy Constructor
    Student(const Student &s) {
        rollNo = s.rollNo;
        marks = s.marks;
        cout << "Copy Constructor called!" << endl;
    }

    void display() {
        cout << "Roll No: " << rollNo << ", Marks: " << marks << endl;
    }
};

int main() {
    Student s1(101, 85.5);      // Parameterized constructor
    Student s2(s1);             // Copy constructor called
    s1.display();
    s2.display();
    return 0;
}

Output:

Copy Constructor called!
Roll No: 101, Marks: 85.5
Roll No: 101, Marks: 85.5

Summary Table

TypeArgumentsPurpose
Default ConstructorNoneInitializes members with default values
Parameterized ConstructorOne or moreInitializes members with given values
Copy ConstructorReference to same class objectCreates a copy of an existing object

Note on Constructor vs Destructor

A class can have both a constructor and a destructor (~classname()). While the constructor initializes/creates the object, the destructor cleans up (e.g., frees memory allocated by new) when the object goes out of scope. Together they manage the full lifecycle of an object.

Open this answer on its own page →

2079 · 10 marks

What is the use of constructor and destructor? Write a program for illustrating default constructor, parameterized constructor and copy constructor.[10]

Show solved answer

Constructor and Destructor in C++


Use of Constructor

A constructor is a special member function of a class that is automatically called when an object is created. Its main uses are:

  • Automatic initialization of data members when an object is created
  • Eliminates the need to manually initialize each object
  • Useful when handling arrays of objects (e.g., initializing 100s of Person objects with default age = 0)
  • Executes code immediately after an object is created
  • Has the same name as the class, no return type, and can be overloaded

Use of Destructor

A destructor is a member function that destructs or deletes an object and frees resources. Its main uses are:

  • Automatically releases memory or resources when an object goes out of scope
  • Called automatically when:
    • A function ends
    • The program ends
    • A block containing local variables ends
    • The delete operator is called
  • Has the same name as the class preceded by ~
  • Takes no arguments and returns nothing
  • There can be only one destructor in a class

Program: Illustrating Default, Parameterized, and Copy Constructor

#include<iostream.h>
#include<conio.h>

class Student {
    private:
        int rollNo;
        float marks;

    public:
        // 1. Default Constructor
        // Called automatically when no arguments are passed
        Student() {
            rollNo = 0;
            marks  = 0.0;
            cout << "Default Constructor called" << endl;
        }

        // 2. Parameterized Constructor
        // Called when arguments are passed during object creation
        Student(int r, float m) {
            rollNo = r;
            marks  = m;
            cout << "Parameterized Constructor called" << endl;
        }

        // 3. Copy Constructor
        // Called when one object is initialized with another object
        Student(Student &s) {
            rollNo = s.rollNo;
            marks  = s.marks;
            cout << "Copy Constructor called" << endl;
        }

        // Destructor
        ~Student() {
            cout << "Destructor called for Roll No: " << rollNo << endl;
        }

        // Display function
        void display() {
            cout << "Roll No : " << rollNo << endl;
            cout << "Marks   : " << marks  << endl;
        }
};

void main() {
    clrscr();

    // Calls Default Constructor
    cout << "--- Object s1 (Default Constructor) ---" << endl;
    Student s1;
    s1.display();

    // Calls Parameterized Constructor
    cout << "\n--- Object s2 (Parameterized Constructor) ---" << endl;
    Student s2(101, 85.5);
    s2.display();

    // Calls Copy Constructor
    cout << "\n--- Object s3 (Copy Constructor) ---" << endl;
    Student s3(s2);
    s3.display();

    getch();
}

Output

--- Object s1 (Default Constructor) ---
Default Constructor called
Roll No : 0
Marks   : 0

--- Object s2 (Parameterized Constructor) ---
Parameterized Constructor called
Roll No : 101
Marks   : 85.5

--- Object s3 (Copy Constructor) ---
Copy Constructor called
Roll No : 101
Marks   : 85.5

Destructor called for Roll No: 101
Destructor called for Roll No: 101
Destructor called for Roll No: 0

Summary Table

Constructor TypeWhen CalledArguments
Default ConstructorStudent s1;None
Parameterized ConstructorStudent s2(101, 85.5);One or more
Copy ConstructorStudent s3(s2);Reference to same class object
DestructorObject goes out of scopeNone

Note: Destructors are called in reverse order of object creation, as shown in the output above.

Open this answer on its own page →

2076 · 5 marks

What is destructor? Write a program to show the destructor call such that it prints the message 'memory is released'. [5]

A destructor is a special member function of a class that is automatically called when an object goes out of scope or is explicitly deleted. It is used to release memory and other resources that were allocated to the object during its lifetime. Feature Description ------ Name Same as class name, ...

Open this answer on its own page →

2080.1 · 10 marks

What is destructor? List its characteristics. Explain the use of default copy constructor with an appropriate example.[10]

Show solved answer

Destructor, Its Characteristics, and Default Copy Constructor


1. Destructor (Definition)

A destructor is a special member function of a class that destructs or deletes an object and performs cleanup operations (such as releasing memory) when the object is no longer needed.

When is a Destructor Called?

A destructor is called automatically when:

  • The function ends (object goes out of scope of a function)
  • The program ends
  • A block containing local variables ends
  • The delete operator is called on a dynamically allocated object

2. Characteristics of Destructor

#Characteristic
1The destructor has the same name as the class, preceded by a tilde symbol (~)
2Destructors do not take any arguments (cannot be overloaded)
3Destructors do not return any value (not even void)
4There can be only one destructor in a class
5It is called automatically when the object goes out of scope or is deleted
6It is typically used to free dynamically allocated memory and release resources
7It should be declared in the public section of the class

3. Example of Destructor

#include <iostream>
#include <string.h>
using namespace std;

class String {
private:
    char *s;
    int size;

public:
    String(char *c) {           // Constructor
        size = strlen(c);
        s = new char[size + 1];
        strcpy(s, c);
        cout << "Constructor called. String: " << s << endl;
    }

    ~String() {                 // Destructor
        delete[] s;             // Free dynamically allocated memory
        cout << "Destructor called. Memory freed." << endl;
    }
};

int main() {
    String str("Hello");        // Constructor is called here
    // Destructor is called automatically when str goes out of scope
    return 0;
}

Output:

Constructor called. String: Hello
Destructor called. Memory freed.

4. Default Copy Constructor

Definition

A copy constructor is a special constructor that creates a new object as a copy of an existing object of the same class. When the programmer does not define a copy constructor explicitly, C++ automatically provides a default copy constructor.

The default copy constructor performs a member-wise (shallow) copy of all data members from one object to another.

Syntax

ClassName (const ClassName &old_object);

How the Default Copy Constructor Works

  • It copies each data member of the source object directly into the corresponding data member of the new object.
  • This is called a shallow copy because it copies values as-is, including pointer addresses (not the data pointed to).

When is the Copy Constructor Invoked?

  1. When an object is initialized with another object of the same class
  2. When an object is passed by value to a function
  3. When an object is returned by value from a function

5. Example: Default Copy Constructor

#include <iostream>
using namespace std;

class Student {
private:
    int rollNo;
    float marks;

public:
    // Parameterized Constructor
    Student(int r, float m) {
        rollNo = r;
        marks = m;
    }

    void display() {
        cout << "Roll No: " << rollNo
             << ", Marks: " << marks << endl;
    }
};

int main() {
    Student s1(101, 85.5);      // Original object created using constructor

    Student s2 = s1;            // Default copy constructor is called here
                                // s2 is a copy of s1

    cout << "Object s1 -> ";
    s1.display();

    cout << "Object s2 -> ";
    s2.display();

    return 0;
}

Output:

Object s1 -> Roll No: 101, Marks: 85.5
Object s2 -> Roll No: 101, Marks: 85.5

Explanation

StepWhat Happens
Student s1(101, 85.5)Parameterized constructor is called; s1.rollNo = 101, s1.marks = 85.5
Student s2 = s1Default copy constructor is invoked; copies rollNo and marks from s1 to s2
Both s1 and s2 display the same valuesMember-wise copy was successful

6. Limitation of Default Copy Constructor (Shallow Copy Problem)

When a class contains pointer members, the default copy constructor copies only the address of the pointer, not the actual data. This means both objects point to the same memory location, which can cause problems (double deletion, data corruption). In such cases, a user-defined copy constructor performing a deep copy is required.

s1.ptr -----> [Memory Block]
s2.ptr -----> [Same Memory Block]   <-- Problem!

Summary Table

FeatureDestructorDefault Copy Constructor
PurposeCleans up / frees resourcesCreates a copy of an object
Symbol~ClassName()ClassName(const ClassName &obj)
ArgumentsNoneReference to same class object
Return typeNoneNone
Count per classOnly oneOnly one (default)
Called automaticallyYes, on scope exitYes, on object copy/pass by value
Open this answer on its own page →

Static members

2080 · 5 marks

Write a C++ program to display the number of objects created using static member. [5]

A static data member is shared by all objects of a class. It is initialized only once and retains its value throughout the program. It is used here to count how many objects have been created, because every time a constructor is called (i.e., an object is created), the static counter is increment...

Open this answer on its own page →

2078 · 10 marks

Write a program according to the specification given below: - Create a class Account with data members acc_no, balance, and min_balance(static) - Include methods for reading and displaying values of objects - Define static member function to display min_balance - Create array of objects to store data of 5 accounts and read and display values of each object[10]

--- --- - Declared inside the class with keyword static - Only one copy is shared among all objects of the class - Must be defined and initialized outside the class: - Declared with keyword static - Can be called without creating an object, using the class name: - Can only access static data memb...

Open this answer on its own page →

2075 · 5 marks

Create a real scenario where static data members are useful. Explain with suitable program. [5]

A static data member is a class member that is shared by all objects of that class. It is declared using the static keyword inside the class. Unlike regular data members (where each object has its own copy), a static data member has only one copy in memory, regardless of how many objects are crea...

Open this answer on its own page →

A Simple Class and Object

2079 · 5 marks

Define class and object with suitable examples. How members of class can be accessed? [5]

A class is a user-defined data type that contains data members and member functions together. It acts as a blueprint or template for creating objects. Like structures and unions in C, a class groups related data and functions, but adds the concept of access control (private, public, protected). I...

Open this answer on its own page →

2080.1 · 10 marks

Write a program to realize the above hierarchy. Create necessary member functions (constructor) to initialize and display necessary information.[10]

Based on the reference context, we need to create a hierarchy where a derived class inherits from a base class, and use constructors to initialize and display member variables of both classes. --- --- --- --- Concept Description ------ Base Class A Contains protected data members x and y with its...

Open this answer on its own page →

Default Constructor

2078 · 5 marks

What is constructor? Explain the concept of default and default copy with suitable example. [5]

A constructor is a special member function of a class that is automatically called when an object of that class is created. It is used to initialize the data members of the class. Key characteristics: - Has the same name as the class - Has no return type (not even void) - Called automatically at ...

Open this answer on its own page →

The Default Copy Constructor

2075 · 5 marks

Explain the default action of the copy constructor. Write a suitable program that demonstrates the technique of overloading the copy constructor. [5]

A copy constructor is a special constructor that creates a new object as a copy of an existing object of the same class. It is called automatically when: - An object is initialized with another object of the same class - An object is passed by value to a function - An object is returned by value ...

Open this answer on its own page →

Objects as Function Arguments

2080.1 · 5 marks

What is the benefit of passing object as arguments? Write a program to create a class named actor with data members name and rating. Initialize the data members and display those names whose rating is greater than 5 using the concept of constant object. [5]

As stated in the notes, passing objects as arguments to member functions is useful in the following ways: - Initialization of data members: When we want to initialize all data members of one object with another object, we can pass objects and assign the values of the supplied object to the curren...

Open this answer on its own page →