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.
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 answerHide 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:
- Automatic Initialization: It automatically initializes data members when an object is created, avoiding garbage values.
- Memory Allocation: It can allocate dynamic memory using the
newoperator at the time of object creation. - No Manual Call Required: Unlike regular functions, the programmer does not need to explicitly call it; it runs automatically.
- Ensures Valid State: It ensures that an object always starts in a valid, well-defined state.
- Resource Acquisition: It can open files, establish connections, or acquire any resources needed by the object.
As seen in the notes, a class like
stringuses a constructorstring(char *c)to allocate memory usingnewand 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
| Type | Arguments | Purpose |
|---|---|---|
| Default Constructor | None | Initializes members with default values |
| Parameterized Constructor | One or more | Initializes members with given values |
| Copy Constructor | Reference to same class object | Creates 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.
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 answerHide 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
Personobjects with defaultage = 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
deleteoperator 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 Type | When Called | Arguments |
|---|---|---|
| Default Constructor | Student s1; | None |
| Parameterized Constructor | Student s2(101, 85.5); | One or more |
| Copy Constructor | Student s3(s2); | Reference to same class object |
| Destructor | Object goes out of scope | None |
Note: Destructors are called in reverse order of object creation, as shown in the output above.
2076 · 5 marks
What is destructor? Write a program to show the destructor call such that it prints the message 'memory is released'. [5]
2080.1 · 10 marks
What is destructor? List its characteristics. Explain the use of default copy constructor with an appropriate example.[10]
Show solved answerHide 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
deleteoperator is called on a dynamically allocated object
2. Characteristics of Destructor
| # | Characteristic |
|---|---|
| 1 | The destructor has the same name as the class, preceded by a tilde symbol (~) |
| 2 | Destructors do not take any arguments (cannot be overloaded) |
| 3 | Destructors do not return any value (not even void) |
| 4 | There can be only one destructor in a class |
| 5 | It is called automatically when the object goes out of scope or is deleted |
| 6 | It is typically used to free dynamically allocated memory and release resources |
| 7 | It 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?
- When an object is initialized with another object of the same class
- When an object is passed by value to a function
- 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
| Step | What Happens |
|---|---|
Student s1(101, 85.5) | Parameterized constructor is called; s1.rollNo = 101, s1.marks = 85.5 |
Student s2 = s1 | Default copy constructor is invoked; copies rollNo and marks from s1 to s2 |
Both s1 and s2 display the same values | Member-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
| Feature | Destructor | Default Copy Constructor |
|---|---|---|
| Purpose | Cleans up / frees resources | Creates a copy of an object |
| Symbol | ~ClassName() | ClassName(const ClassName &obj) |
| Arguments | None | Reference to same class object |
| Return type | None | None |
| Count per class | Only one | Only one (default) |
| Called automatically | Yes, on scope exit | Yes, on object copy/pass by value |
Static members
2080 · 5 marks
Write a C++ program to display the number of objects created using static member. [5]
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]
2075 · 5 marks
Create a real scenario where static data members are useful. Explain with suitable program. [5]
A Simple Class and Object
2079 · 5 marks
Define class and object with suitable examples. How members of class can be accessed? [5]
2080.1 · 10 marks
Write a program to realize the above hierarchy. Create necessary member functions (constructor) to initialize and display necessary information.[10]
Default Constructor
2078 · 5 marks
What is constructor? Explain the concept of default and default copy with suitable example. [5]
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]
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]
Make Unit 3 stick
Practice CSC166 with flashcards & quizzes