Current Affairs updated daily
KalviGavaniKalviGavani

Classes & Objects Exercise Solutions | KalviGavani

TN Class 11 Computer Science Classes and Objects exercise solutions — class definition, objects, access specifiers, constructors with worked examples.

Updated 15 June 202616 min read

Exercise Solutions Available

Step-by-step answers for all textbook questions in this chapter

View Solutions →

1. How to Use This Page

1. Solve every exercise on your own first. Attempt each question before reading the solution. 2. Compare your method, not just the final answer. The process matters in the board exam. 3. Pay attention to the explanations — they clarify why an answer is correct, which helps with similar questions. 4. Revisit the "Common Mistakes" section before every test to avoid repeat errors. 5. Use the Exam Checklist on the night before the exam for a quick final review.


2. Key Concepts (Quick Recap)

Class vs Object

FeatureClassObject
What is it?Blueprint / templateInstance of a class
MemoryNo memory until objects createdOccupies memory
Created byclass keywordDeclaration of variable
Exampleclass Student { ... };Student s1;

Defining a Class and Creating Objects

class Student {
private:
    int rollNo;
    char name[20];
    float marks;
public:
    void getDetails() {
        cout << "Enter roll number: ";
        cin >> rollNo;
        cout << "Enter name: ";
        cin >> name;
        cout << "Enter marks: ";
        cin >> marks;
    }
    void display() {
        cout << "Roll No: " << rollNo << endl;
        cout << "Name: " << name << endl;
        cout << "Marks: " << marks << endl;
    }
};

// Creating objects
Student s1;        // Object s1 of class Student
Student s2;        // Object s2 of class Student
s1.getDetails();   // Calling member function
s1.display();

Access Specifiers

SpecifierAccessible fromUsage
privateOnly within the classData members (for encapsulation)
protectedWithin the class and derived classesUsed in inheritance
publicAnywhere (inside and outside the class)Member functions (interface)

By default, class members are private if no specifier is given.

Constructors

A constructor is a special member function that automatically initialises an object when it is created.

FeatureRule
NameSame as class name
Return typeNone (not even void)
CalledAutomatically when object is created
PurposeInitialise data members
OverloadingYes — multiple constructors with different parameters

Types of Constructors:

TypePurposeExample
DefaultNo parametersStudent() { rollNo = 0; }
ParameterisedTakes parametersStudent(int r) { rollNo = r; }
CopyCreates a copy of an existing objectStudent(Student &s) { rollNo = s.rollNo; }
class Sample {
    int x;
public:
    Sample() { x = 0; }               // Default constructor
    Sample(int a) { x = a; }          // Parameterised constructor
    Sample(Sample &s) { x = s.x; }    // Copy constructor
};
Sample obj1;           // Calls default constructor
Sample obj2(10);       // Calls parameterised constructor
Sample obj3(obj2);     // Calls copy constructor

Destructor

A destructor is a special member function called automatically when an object goes out of scope.

class Sample {
public:
    ~Sample() {
        cout << "Object destroyed";
    }
};
FeatureRule
NameSame as class name prefixed with ~
Return typeNone
ParametersNone
CalledAutomatically when object is destroyed
PurposeRelease resources (memory, files, etc.)

Inline Functions

An inline function expands its code at the call site instead of performing a function call, reducing overhead.

class Calculator {
public:
    inline int square(int x) {  // Inline function
        return x * x;
    }
};

When square(5) is called, the compiler replaces it with 5 * 5 directly.

this Pointer

The this pointer is an implicit pointer available in every non-static member function. It points to the object that called the function.

class Sample {
    int x;
public:
    void setX(int x) {
        this->x = x;  // 'this->x' refers to the member, 'x' refers to the parameter
    }
};

Static Data Members

A static data member is shared by all objects of the class. It exists even before any object is created.

class Counter {
public:
    static int count;  // Declaration
    Counter() { count++; }
};
int Counter::count = 0;  // Definition (mandatory)

3. I. Choose the Best Answer (MCQs)

1. Which access specifier makes members accessible only within the class?
Answer

(a) public (b) protected (c) private (d) global

Answer(c) private Private members can only be accessed by member functions of the same class. They are hidden from outside code, enforcing encapsulation.
2. A constructor is called when:
Answer

(a) The object is destroyed (b) The object is created (c) A member function is called (d) The program starts

Answer(b) The object is created A constructor is automatically invoked when an object is created. It initialises the object's data members. A destructor is called when the object is destroyed.
3. What is the return type of a constructor?
Answer

(a) int (b) void (c) Same as class name (d) No return type (not even void)

Answer(d) No return type (not even void) Constructors do not have a return type, not even void. They are called implicitly and cannot return values.
4. Which symbol is used to define a destructor?
Answer

(a) & (b) * (c) ~ (d) !

Answer(c) ~ A destructor has the same name as the class but is prefixed with a tilde (~). Example: ~Student().
5. A class is a:
Answer

(a) Physical entity (b) Logical entity / blueprint (c) Memory location (d) Function

Answer(b) Logical entity / blueprint A class is a template or blueprint that defines the structure and behaviour. An object is the physical instance created from the class. The class itself does not occupy memory for data.
6. The this pointer points to:
Answer

(a) The class itself (b) The current object that called the function (c) The previous object (d) The global object

Answer(b) The current object that called the function this is an implicit pointer available in every non-static member function. It holds the address of the object that invoked the function.

4. II. Fill in the Blanks

1. A class is a blueprint from which objects are created. 2. An object is an instance of a class. 3. The default access specifier in a C++ class is private. 4. A constructor is automatically called when an object is created. 5. A destructor is automatically called when an object is destroyed. 6. A constructor with no parameters is called a default constructor. 7. A constructor that takes parameters is called a parameterised constructor. 8. A copy constructor creates a new object as a copy of an existing object. 9. The this pointer refers to the current object that invoked the member function. 10. The inline keyword suggests the compiler to expand the function body at the call site. 11. A static data member is shared by all objects of the class. 12. The dot (.) operator is used to access public members of an object. 13. A destructor is prefixed with the ~ (tilde) symbol.


5. III. True or False (with corrections)

1. A class occupies memory for its data members even before any object is created.

False. A class is only a template or blueprint. Memory is allocated only when objects are created. Static data members are an exception — they are allocated even without objects.

2. A constructor can have a return type.

False. A constructor has no return type, not even void. It is called implicitly when an object is created and cannot return a value.

3. Private members of a class can be accessed from outside the class using the dot operator.

False. Private members can only be accessed by member functions of the same class. They are not accessible from outside, even with the dot operator.

4. A class can have multiple constructors with different parameters.

True. This is called constructor overloading. A class can have a default constructor, a parameterised constructor, and a copy constructor, all with different parameter lists.

5. A destructor can take parameters.

False. A destructor takes no parameters and has no return type. There can be only one destructor per class (no overloading).

6. The this pointer is available in static member functions.

False. The this pointer is not available in static member functions because static functions are not called through any specific object — they belong to the class.


6. IV. Match the Following

Column AColumn B
1. Classa. Instance of a class
2. Objectb. Blueprint/template
3. Constructorc. Called when object is created
4. Destructord. Called when object is destroyed
5. privatee. Accessible only within the class
6. publicf. Accessible from anywhere
7. thisg. Pointer to current object
8. statich. Shared by all objects
Answer1-b, 2-a, 3-c, 4-d, 5-e, 6-f, 7-g, 8-h

7. V. Answer Briefly (2-mark questions)

Q1. Differentiate between a class and an object.
Answer
FeatureClassObject
DefinitionBlueprint or templateInstance of a class
MemoryNo memory for dataOccupies memory
CreationDefined using class keywordCreated like a variable
Exampleclass Car { ... };Car myCar;
NatureLogical entityPhysical entity
Q2. What are access specifiers? List the three types.
Answer

Access specifiers define the visibility and accessibility of class members from different parts of the program.

SpecifierAccessible from
privateOnly within the class
protectedWithin the class and derived classes
publicFrom anywhere (inside and outside the class)

By default, members of a class are private.

Q3. What is a default constructor? Give an example.
Answer

A default constructor is a constructor that takes no parameters. It initialises data members to default values and is automatically called when an object is created without arguments.

class Sample {
    int x;
public:
    Sample() {   // Default constructor
        x = 0;
    }
};
Sample obj;  // Default constructor called automatically
Q4. What is the difference between a constructor and a destructor?
Answer
FeatureConstructorDestructor
PurposeInitialises an objectDestroys an object
Called whenObject is createdObject goes out of scope
SyntaxClassName()~ClassName()
ParametersCan have parametersNo parameters
Return typeNoneNone
OverloadingYes (multiple constructors)No (only one destructor)
Q5. What is an inline function? When should it be used?
Answer

An inline function is a function whose body is inserted directly at the call site by the compiler, avoiding the overhead of a function call.

class Circle {
public:
    inline double area(double r) {
        return 3.14 * r * r;
    }
};

Use inline functions when:

  • The function body is small (1-2 lines).
  • The function is called frequently (performance matters).
  • Avoid inline for large functions or functions with loops/recursion.

8. VI. Answer in Detail (5-mark questions)

Q1. Define a class. Explain the structure of a class with access specifiers and a complete example.
Answer

A class is a user-defined data type that binds data members (variables) and member functions (methods) together into a single unit. It serves as a blueprint for creating objects.

Structure of a Class:

class ClassName {
private:
    // Private data members — accessible only within the class
    int dataMember1;
    float dataMember2;

protected:
    // Protected members — accessible within class and derived classes
    int protectedMember;

public:
    // Public member functions — accessible from anywhere
    // Constructor
    ClassName() {
        dataMember1 = 0;
        dataMember2 = 0.0;
    }

    // Member function to set data
    void setData(int d1, float d2) {
        dataMember1 = d1;
        dataMember2 = d2;
    }

    // Member function to display data
    void display() {
        cout << "Data1: " << dataMember1 << endl;
        cout << "Data2: " << dataMember2 << endl;
    }
};

int main() {
    ClassName obj;        // Object created, default constructor called
    obj.setData(10, 3.5); // Accessing public member function
    obj.display();
    // obj.dataMember1 = 5;  // ERROR: private member not accessible
    return 0;
}

Key points:

  • private members are hidden from outside — this is encapsulation.
  • public member functions provide controlled access to private data.
  • The class definition ends with a semicolon };.
  • Objects access members using the dot operator (.).
Q2. Explain the types of constructors with examples.
Answer

1. Default Constructor: A constructor with no parameters. Initialises members to default values.

class Rectangle {
    int length, breadth;
public:
    Rectangle() {        // Default constructor
        length = 0;
        breadth = 0;
    }
    void display() {
        cout << "Area = " << length * breadth << endl;
    }
};
Rectangle r1;  // Default constructor called
r1.display();  // Area = 0

2. Parameterised Constructor: A constructor that takes parameters to initialise members with user-provided values.

class Rectangle {
    int length, breadth;
public:
    Rectangle(int l, int b) {  // Parameterised constructor
        length = l;
        breadth = b;
    }
    void display() {
        cout << "Area = " << length * breadth << endl;
    }
};
Rectangle r2(5, 4);  // Parameterised constructor called
r2.display();         // Area = 20

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 a parameter.

class Rectangle {
    int length, breadth;
public:
    Rectangle(int l, int b) {  // Parameterised constructor
        length = l;
        breadth = b;
    }
    Rectangle(Rectangle &r) {  // Copy constructor
        length = r.length;
        breadth = r.breadth;
    }
    void display() {
        cout << "Area = " << length * breadth << endl;
    }
};
Rectangle r3(5, 4);    // Parameterised constructor
Rectangle r4(r3);       // Copy constructor — r4 is a copy of r3
r4.display();           // Area = 20

Comparison:

TypeParametersPurposeExample
DefaultNoneInitialise to default valuesRectangle()
ParameterisedHas parametersInitialise with specific valuesRectangle(int l, int b)
CopyReference to same classCopy an existing objectRectangle(Rectangle &r)
Q3. Write a complete C++ program using classes and objects to create a BankAccount class with deposit, withdrawal, and balance display functionality.
#include <iostream>
using namespace std;

class BankAccount {
private:
    int accountNo;
    char name[30];
    float balance;
public:
    // Constructor to initialise account
    BankAccount() {
        accountNo = 0;
        balance = 0.0;
    }

    // Member function to open account
    void openAccount() {
        cout << "Enter account number: ";
        cin >> accountNo;
        cout << "Enter account holder name: ";
        cin >> name;
        cout << "Enter initial deposit: ";
        cin >> balance;
    }

    // Member function to deposit money
    void deposit() {
        float amount;
        cout << "Enter amount to deposit: ";
        cin >> amount;
        balance = balance + amount;
        cout << "Deposit successful. New balance: " << balance << endl;
    }

    // Member function to withdraw money
    void withdraw() {
        float amount;
        cout << "Enter amount to withdraw: ";
        cin >> amount;
        if (amount > balance) {
            cout << "Insufficient balance!" << endl;
        } else {
            balance = balance - amount;
            cout << "Withdrawal successful. New balance: " << balance << endl;
        }
    }

    // Member function to display balance
    void displayBalance() {
        cout << "Account No: " << accountNo << endl;
        cout << "Name: " << name << endl;
        cout << "Balance: Rs. " << balance << endl;
    }
};

int main() {
    BankAccount account;
    int choice;

    account.openAccount();

    do {
        cout << "\n--- Bank Menu ---" << endl;
        cout << "1. Deposit" << endl;
        cout << "2. Withdraw" << endl;
        cout << "3. Display Balance" << endl;
        cout << "4. Exit" << endl;
        cout << "Enter your choice: ";
        cin >> choice;

        switch (choice) {
            case 1: account.deposit(); break;
            case 2: account.withdraw(); break;
            case 3: account.displayBalance(); break;
            case 4: cout << "Thank you!"; break;
            default: cout << "Invalid choice!";
        }
    } while (choice != 4);

    return 0;
}
Answer

Key points demonstrated:

  • Encapsulation: accountNo, name, balance are private; accessible only through public member functions.
  • Constructor: BankAccount() initialises members when the object is created.
  • Member functions: deposit(), withdraw(), and displayBalance() operate on private data through the public interface.
  • Input validation: withdraw() checks for insufficient balance before processing.

9. Common Mistakes to Avoid

1. Forgetting the semicolon after the class definition — class Student { ... }; must end with };. Missing this causes compilation errors.

2. Accessing private members from outside the class — Private members cannot be accessed using the dot operator from main() or other functions. Use public member functions (getters/setters) to access them.

3. Confusing class and object — A class is a template; an object is a specific instance. class Student is the template; Student s1 creates an object.

4. Constructor with return type — Constructors have no return type, not even void. Adding void before the constructor name makes it a regular member function, not a constructor.

5. Destructor with parameters — A destructor takes no parameters and cannot be overloaded. There is exactly one destructor per class.

6. Not defining static data members outside the class — A static data member declared inside the class must be defined outside: int Counter::count = 0;. Forgetting this causes a linker error.

7. Using this pointer in static functions — Static member functions do not have a this pointer because they are not called through an object.

8. Calling a constructor explicitly like a normal function — Constructors are called automatically when objects are created, not invoked like obj.Constructor().


10. Exam Checklist

  • [ ] I can define a class with private, protected, and public sections
  • [ ] I can create objects and access members using the dot operator
  • [ ] I can explain the three access specifiers and their scope
  • [ ] I can write default, parameterised, and copy constructors
  • [ ] I can write a destructor and explain when it is called
  • [ ] I can differentiate between constructor and destructor
  • [ ] I can explain the this pointer and its use
  • [ ] I can explain inline functions and when to use them
  • [ ] I can explain static data members and their properties
  • [ ] I can write complete programs using classes and objects
  • [ ] I understand encapsulation — why data is private and functions are public

Frequently Asked Questions

A class is a blueprint or template that defines the structure and behaviour (data members and member functions). An object is an instance of a class — a concrete entity created from the class blueprint.