BIT153 · Exam intelligence
Object Oriented Programming important questions
From 7 past TU papers: which questions keep coming back, how much they carry, and what is most likely to show up next. Every question links to a model answer.
Most likely in the next examStatistical
Ranked by how often a topic is asked, its marks weight, and whether it is due after skipping the 2082 paper. No guarantees; study the whole syllabus.
1asked 5xavg 5 marks · Exception handling definition and purposeAnswerHideWrite a program to handle division by zero exception using try, catch, and throw. [5]
Write a program to handle division by zero exception using try, catch, and throw. [5]
Handling Division by Zero Exception Using try, catch, and throw
Concept
In C++, exception handling uses three keywords:
- try - block of code that may throw an exception
- throw - used to throw/raise an exception when an error occurs
- catch - block that handles the thrown exception
Program
#include <iostream>
using namespace std;
// Function to perform division
double divide(int numerator, int denominator) {
if (denominator == 0) {
throw "Division by zero is not allowed!"; // throw exception
}
return (double)numerator / denominator;
}
int main() {
int a, b;
cout << "Enter numerator: ";
cin >> a;
cout << "Enter denominator: ";
cin >> b;
try {
// Code that may cause exception
double result = divide(a, b);
cout << "Result: " << a << " / " << b << " = " << result << endl;
}
catch (const char* msg) {
// Handle the exception
cout << "Exception caught: " << msg << endl;
}
cout << "Program continues after exception handling." << endl;
return 0;
}
Sample Output
Case 1: Normal Division
Enter numerator: 10
Enter denominator: 2
Result: 10 / 2 = 5
Program continues after exception handling.
Case 2: Division by Zero
Enter numerator: 10
Enter denominator: 0
Exception caught: Division by zero is not allowed!
Program continues after exception handling.
Explanation
| Keyword | Role in Program |
|---|---|
throw | Throws a string message when denominator is 0 |
try | Wraps the call to divide() that may fail |
catch | Catches the thrown string and displays the error |
- When denominator is not zero, the division executes normally.
- When denominator is zero,
throwtransfers control directly to thecatchblock, skipping the remainingtryblock. - After the
catchblock executes, the program continues normally, demonstrating graceful error handling.
2asked 3xavg 10 marks · due (skipped 2082) · Constructor definition and purposeAnswerHideWhat is constructor? Explain its types with suitable example.How is the constructor called in a derived class in C++?[6+4]
What is constructor? Explain its types with suitable example.How is the constructor called in a derived class in C++?[6+4]
Constructor in C++
What is a Constructor?
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 when an object is created
- Can be overloaded
Types of Constructors
1. Default Constructor
A constructor that takes no arguments. If no constructor is defined, the compiler provides one automatically.
#include<iostream>
using namespace std;
class Student {
int roll;
string name;
public:
// Default Constructor
Student() {
roll = 0;
name = "Unknown";
cout << "Default Constructor called" << endl;
}
void display() {
cout << "Roll: " << roll << ", Name: " << name << endl;
}
};
int main() {
Student s1; // Default constructor called automatically
s1.display();
return 0;
}
Output:
Default Constructor called
Roll: 0, Name: Unknown
2. Parameterized Constructor
A constructor that accepts one or more arguments to initialize objects with specific values.
#include<iostream>
using namespace std;
class Student {
int roll;
string name;
public:
// Parameterized Constructor
Student(int r, string n) {
roll = r;
name = n;
cout << "Parameterized Constructor called" << endl;
}
void display() {
cout << "Roll: " << roll << ", Name: " << name << endl;
}
};
int main() {
Student s1(101, "Ram"); // Parameterized constructor called
s1.display();
return 0;
}
Output:
Parameterized Constructor called
Roll: 101, Name: Ram
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 {
int roll;
string name;
public:
Student(int r, string n) {
roll = r;
name = n;
}
// Copy Constructor
Student(const Student &s) {
roll = s.roll;
name = s.name;
cout << "Copy Constructor called" << endl;
}
void display() {
cout << "Roll: " << roll << ", Name: " << name << endl;
}
};
int main() {
Student s1(101, "Ram");
Student s2(s1); // Copy constructor called
s2.display();
return 0;
}
Output:
Copy Constructor called
Roll: 101, Name: Ram
4. Constructor Overloading
Multiple constructors with different parameter lists in the same class.
#include<iostream>
using namespace std;
class Rectangle {
float length, breadth;
public:
Rectangle() { // Default
length = breadth = 0;
}
Rectangle(float l, float b) { // Parameterized
length = l;
breadth = b;
}
void area() {
cout << "Area = " << length * breadth << endl;
}
};
int main() {
Rectangle r1; // calls default constructor
Rectangle r2(5.0, 3.0); // calls parameterized constructor
r1.area();
r2.area();
return 0;
}
Calling Constructor in a Derived Class
When a derived class object is created, both the base class constructor and the derived class constructor are called. The base class constructor is called first, then the derived class constructor.
To explicitly pass arguments to the base class constructor, we use an initializer list with the colon (:) syntax.
Syntax:
DerivedClass(parameters) : BaseClass(arguments) {
// derived class constructor body
}
Order of Execution:
- Base class constructor executes first
- Derived class constructor executes next
Example:
#include<iostream>
using namespace std;
// Base Class
class Animal {
string name;
public:
Animal(string n) {
name = n;
cout << "Animal Constructor: " << name << endl;
}
};
// Derived Class
class Dog : public Animal {
string breed;
public:
// Calling base class constructor using initializer list
Dog(string n, string b) : Animal(n) {
breed = b;
cout << "Dog Constructor: Breed = " << breed << endl;
}
};
int main() {
Dog d1("Tommy", "Labrador");
return 0;
}
Output:
Animal Constructor: Tommy
Dog Constructor: Breed = Labrador
Key Points:
| Aspect | Detail |
|---|---|
| Base constructor call | Always called before derived constructor |
| Syntax | Derived(params) : Base(args) { } |
| Default base constructor | Called automatically if not specified |
| Destructor order | Reverse of constructor order |
Note: If the base class has only a parameterized constructor (no default constructor), the derived class must explicitly call it using the initializer list, otherwise a compile-time error occurs.
3asked 3xavg 5 marks · due (skipped 2082) · Type conversionAnswerHideHow do you convert basic data type to user defined data type? Explain. [5]
How do you convert basic data type to user defined data type? Explain. [5]
In C++, converting a basic (built-in) data type (such as int, float, double, char) to a user-defined data type (such as a class or struct) is achieved using a special constructor called a conversion constructor. --- A conversion construc...
4asked 4xavg 8 marks · Operator overloading definition and purposesAnswerHideExplain operator overloading with example?Write a C++ class Number to store an integer. Overload addition (+) and comparison (==) operators, and show conversion between int and Number. Write a program to perform these operations.[2+8]
Explain operator overloading with example?Write a C++ class Number to store an integer. Overload addition (+) and comparison (==) operators, and show conversion between int and Number. Write a program to perform these operations.[2+8]
Operator Overloading in C++
(a) Explanation of Operator Overloading
Operator overloading is a feature of C++ that allows existing operators (such as +, -, ==, <<, etc.) to be given additional meaning when applied to user-defined types (classes/objects). It enables objects of a class to be used with operators in a natural, intuitive way, just like built-in data types.
Key Points:
- The keyword
operatorfollowed by the operator symbol is used to define the overloaded function. - Syntax:
return_type operator symbol (parameter list) - It does not change the precedence or associativity of operators.
- At least one operand must be a user-defined type.
(b) C++ Program
#include <iostream>
using namespace std;
class Number {
private:
int value;
public:
// Default constructor
Number() {
value = 0;
}
// Parameterized constructor
Number(int v) {
value = v;
}
// -----------------------------------------------
// Conversion: int to Number (done via constructor)
// Conversion: Number to int (conversion operator)
// -----------------------------------------------
operator int() {
return value;
}
// -----------------------------------------------
// Overload addition operator (+)
// Number + Number
// -----------------------------------------------
Number operator+(const Number& obj) {
Number temp;
temp.value = this->value + obj.value;
return temp;
}
// -----------------------------------------------
// Overload comparison operator (==)
// -----------------------------------------------
bool operator==(const Number& obj) {
if (this->value == obj.value)
return true;
else
return false;
}
// Display function
void display() {
cout << "Value = " << value << endl;
}
};
// -----------------------------------------------
// Main function to demonstrate operations
// -----------------------------------------------
int main() {
// int to Number conversion (via constructor)
int x = 10;
Number n1 = x; // implicit conversion: int -> Number
Number n2(20); // direct initialization
Number n3 = 10; // implicit conversion: int -> Number
cout << "n1: "; n1.display();
cout << "n2: "; n2.display();
cout << "n3: "; n3.display();
// Addition operator overloading
Number n4 = n1 + n2; // calls operator+
cout << "\nAfter n4 = n1 + n2:" << endl;
cout << "n4: "; n4.display();
// Comparison operator overloading
cout << "\nComparing n1 and n3 (both have value 10):" << endl;
if (n1 == n3)
cout << "n1 == n3: TRUE" << endl;
else
cout << "n1 == n3: FALSE" << endl;
cout << "\nComparing n1 and n2:" << endl;
if (n1 == n2)
cout << "n1 == n2: TRUE" << endl;
else
cout << "n1 == n2: FALSE" << endl;
// Number to int conversion (via conversion operator)
int result = n4; // implicit conversion: Number -> int
cout << "\nNumber to int conversion (n4 -> int): " << result << endl;
return 0;
}
Output
n1: Value = 10
n2: Value = 20
n3: Value = 10
After n4 = n1 + n2:
n4: Value = 30
Comparing n1 and n3 (both have value 10):
n1 == n3: TRUE
Comparing n1 and n2:
n1 == n2: FALSE
Number to int conversion (n4 -> int): 30
Explanation of Key Concepts Used
| Feature | How it is done |
|---|---|
int to Number | Via constructor Number(int v) - implicit conversion |
Number to int | Via conversion operator operator int() |
+ overloading | Number operator+(const Number& obj) |
== overloading | bool operator==(const Number& obj) |
Number n1 = x;calls the constructorNumber(int v), convertinginttoNumber.int result = n4;callsoperator int(), convertingNumbertoint.n1 + n2callsoperator+, returning a newNumberobject with the sum.n1 == n3callsoperator==, returningtrueif values are equal.
5asked 4xavg 5 marks · Text file reading and writingAnswerHideWrite a C++ program to read a text file named data.txt and display its contents on the screen. Also, count the number of lines, words, and characters in the file and display these counts after showing the file content. [5]
Write a C++ program to read a text file named data.txt and display its contents on the screen. Also, count the number of lines, words, and characters in the file and display these counts after showing the file content. [5]
Suppose data.txt contains: Program Output: Concept Description ------ ifstream Used to open and read from a file getline() Reads one complete line at a time inFile check Verifies file was opened successfully line.length() Returns number ...
Most repeated questions
Topics asked at least twice, most-asked first.
asked 5xavg 5 marks · 2082, 2081, 2080, 2078, 0AnswerHideWrite a program to handle division by zero exception using try, catch, and throw. [5]
Write a program to handle division by zero exception using try, catch, and throw. [5]
Handling Division by Zero Exception Using try, catch, and throw
Concept
In C++, exception handling uses three keywords:
- try - block of code that may throw an exception
- throw - used to throw/raise an exception when an error occurs
- catch - block that handles the thrown exception
Program
#include <iostream>
using namespace std;
// Function to perform division
double divide(int numerator, int denominator) {
if (denominator == 0) {
throw "Division by zero is not allowed!"; // throw exception
}
return (double)numerator / denominator;
}
int main() {
int a, b;
cout << "Enter numerator: ";
cin >> a;
cout << "Enter denominator: ";
cin >> b;
try {
// Code that may cause exception
double result = divide(a, b);
cout << "Result: " << a << " / " << b << " = " << result << endl;
}
catch (const char* msg) {
// Handle the exception
cout << "Exception caught: " << msg << endl;
}
cout << "Program continues after exception handling." << endl;
return 0;
}
Sample Output
Case 1: Normal Division
Enter numerator: 10
Enter denominator: 2
Result: 10 / 2 = 5
Program continues after exception handling.
Case 2: Division by Zero
Enter numerator: 10
Enter denominator: 0
Exception caught: Division by zero is not allowed!
Program continues after exception handling.
Explanation
| Keyword | Role in Program |
|---|---|
throw | Throws a string message when denominator is 0 |
try | Wraps the call to divide() that may fail |
catch | Catches the thrown string and displays the error |
- When denominator is not zero, the division executes normally.
- When denominator is zero,
throwtransfers control directly to thecatchblock, skipping the remainingtryblock. - After the
catchblock executes, the program continues normally, demonstrating graceful error handling.
asked 4xavg 8 marks · 2082, 2081, 2080.1, 2080AnswerHideExplain operator overloading with example?Write a C++ class Number to store an integer. Overload addition (+) and comparison (==) operators, and show conversion between int and Number. Write a program to perform these operations.[2+8]
Explain operator overloading with example?Write a C++ class Number to store an integer. Overload addition (+) and comparison (==) operators, and show conversion between int and Number. Write a program to perform these operations.[2+8]
Operator Overloading in C++
(a) Explanation of Operator Overloading
Operator overloading is a feature of C++ that allows existing operators (such as +, -, ==, <<, etc.) to be given additional meaning when applied to user-defined types (classes/objects). It enables objects of a class to be used with operators in a natural, intuitive way, just like built-in data types.
Key Points:
- The keyword
operatorfollowed by the operator symbol is used to define the overloaded function. - Syntax:
return_type operator symbol (parameter list) - It does not change the precedence or associativity of operators.
- At least one operand must be a user-defined type.
(b) C++ Program
#include <iostream>
using namespace std;
class Number {
private:
int value;
public:
// Default constructor
Number() {
value = 0;
}
// Parameterized constructor
Number(int v) {
value = v;
}
// -----------------------------------------------
// Conversion: int to Number (done via constructor)
// Conversion: Number to int (conversion operator)
// -----------------------------------------------
operator int() {
return value;
}
// -----------------------------------------------
// Overload addition operator (+)
// Number + Number
// -----------------------------------------------
Number operator+(const Number& obj) {
Number temp;
temp.value = this->value + obj.value;
return temp;
}
// -----------------------------------------------
// Overload comparison operator (==)
// -----------------------------------------------
bool operator==(const Number& obj) {
if (this->value == obj.value)
return true;
else
return false;
}
// Display function
void display() {
cout << "Value = " << value << endl;
}
};
// -----------------------------------------------
// Main function to demonstrate operations
// -----------------------------------------------
int main() {
// int to Number conversion (via constructor)
int x = 10;
Number n1 = x; // implicit conversion: int -> Number
Number n2(20); // direct initialization
Number n3 = 10; // implicit conversion: int -> Number
cout << "n1: "; n1.display();
cout << "n2: "; n2.display();
cout << "n3: "; n3.display();
// Addition operator overloading
Number n4 = n1 + n2; // calls operator+
cout << "\nAfter n4 = n1 + n2:" << endl;
cout << "n4: "; n4.display();
// Comparison operator overloading
cout << "\nComparing n1 and n3 (both have value 10):" << endl;
if (n1 == n3)
cout << "n1 == n3: TRUE" << endl;
else
cout << "n1 == n3: FALSE" << endl;
cout << "\nComparing n1 and n2:" << endl;
if (n1 == n2)
cout << "n1 == n2: TRUE" << endl;
else
cout << "n1 == n2: FALSE" << endl;
// Number to int conversion (via conversion operator)
int result = n4; // implicit conversion: Number -> int
cout << "\nNumber to int conversion (n4 -> int): " << result << endl;
return 0;
}
Output
n1: Value = 10
n2: Value = 20
n3: Value = 10
After n4 = n1 + n2:
n4: Value = 30
Comparing n1 and n3 (both have value 10):
n1 == n3: TRUE
Comparing n1 and n2:
n1 == n2: FALSE
Number to int conversion (n4 -> int): 30
Explanation of Key Concepts Used
| Feature | How it is done |
|---|---|
int to Number | Via constructor Number(int v) - implicit conversion |
Number to int | Via conversion operator operator int() |
+ overloading | Number operator+(const Number& obj) |
== overloading | bool operator==(const Number& obj) |
Number n1 = x;calls the constructorNumber(int v), convertinginttoNumber.int result = n4;callsoperator int(), convertingNumbertoint.n1 + n2callsoperator+, returning a newNumberobject with the sum.n1 == n3callsoperator==, returningtrueif values are equal.
asked 4xavg 5 marks · 2082, 2079, 2078, 0AnswerHideWrite a C++ program to read a text file named data.txt and display its contents on the screen. Also, count the number of lines, words, and characters in the file and display these counts after showing the file content. [5]
Write a C++ program to read a text file named data.txt and display its contents on the screen. Also, count the number of lines, words, and characters in the file and display these counts after showing the file content. [5]
Suppose data.txt contains: Program Output: Concept Description ------ ifstream Used to open and read from a file getline() Reads one complete line at a time inFile check Verifies file was opened successfully line.length() Returns number ...
asked 3xavg 10 marks · 2080, 2078, 0AnswerHideWhat is constructor? Explain its types with suitable example.How is the constructor called in a derived class in C++?[6+4]
What is constructor? Explain its types with suitable example.How is the constructor called in a derived class in C++?[6+4]
Constructor in C++
What is a Constructor?
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 when an object is created
- Can be overloaded
Types of Constructors
1. Default Constructor
A constructor that takes no arguments. If no constructor is defined, the compiler provides one automatically.
#include<iostream>
using namespace std;
class Student {
int roll;
string name;
public:
// Default Constructor
Student() {
roll = 0;
name = "Unknown";
cout << "Default Constructor called" << endl;
}
void display() {
cout << "Roll: " << roll << ", Name: " << name << endl;
}
};
int main() {
Student s1; // Default constructor called automatically
s1.display();
return 0;
}
Output:
Default Constructor called
Roll: 0, Name: Unknown
2. Parameterized Constructor
A constructor that accepts one or more arguments to initialize objects with specific values.
#include<iostream>
using namespace std;
class Student {
int roll;
string name;
public:
// Parameterized Constructor
Student(int r, string n) {
roll = r;
name = n;
cout << "Parameterized Constructor called" << endl;
}
void display() {
cout << "Roll: " << roll << ", Name: " << name << endl;
}
};
int main() {
Student s1(101, "Ram"); // Parameterized constructor called
s1.display();
return 0;
}
Output:
Parameterized Constructor called
Roll: 101, Name: Ram
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 {
int roll;
string name;
public:
Student(int r, string n) {
roll = r;
name = n;
}
// Copy Constructor
Student(const Student &s) {
roll = s.roll;
name = s.name;
cout << "Copy Constructor called" << endl;
}
void display() {
cout << "Roll: " << roll << ", Name: " << name << endl;
}
};
int main() {
Student s1(101, "Ram");
Student s2(s1); // Copy constructor called
s2.display();
return 0;
}
Output:
Copy Constructor called
Roll: 101, Name: Ram
4. Constructor Overloading
Multiple constructors with different parameter lists in the same class.
#include<iostream>
using namespace std;
class Rectangle {
float length, breadth;
public:
Rectangle() { // Default
length = breadth = 0;
}
Rectangle(float l, float b) { // Parameterized
length = l;
breadth = b;
}
void area() {
cout << "Area = " << length * breadth << endl;
}
};
int main() {
Rectangle r1; // calls default constructor
Rectangle r2(5.0, 3.0); // calls parameterized constructor
r1.area();
r2.area();
return 0;
}
Calling Constructor in a Derived Class
When a derived class object is created, both the base class constructor and the derived class constructor are called. The base class constructor is called first, then the derived class constructor.
To explicitly pass arguments to the base class constructor, we use an initializer list with the colon (:) syntax.
Syntax:
DerivedClass(parameters) : BaseClass(arguments) {
// derived class constructor body
}
Order of Execution:
- Base class constructor executes first
- Derived class constructor executes next
Example:
#include<iostream>
using namespace std;
// Base Class
class Animal {
string name;
public:
Animal(string n) {
name = n;
cout << "Animal Constructor: " << name << endl;
}
};
// Derived Class
class Dog : public Animal {
string breed;
public:
// Calling base class constructor using initializer list
Dog(string n, string b) : Animal(n) {
breed = b;
cout << "Dog Constructor: Breed = " << breed << endl;
}
};
int main() {
Dog d1("Tommy", "Labrador");
return 0;
}
Output:
Animal Constructor: Tommy
Dog Constructor: Breed = Labrador
Key Points:
| Aspect | Detail |
|---|---|
| Base constructor call | Always called before derived constructor |
| Syntax | Derived(params) : Base(args) { } |
| Default base constructor | Called automatically if not specified |
| Destructor order | Reverse of constructor order |
Note: If the base class has only a parameterized constructor (no default constructor), the derived class must explicitly call it using the initializer list, otherwise a compile-time error occurs.
asked 3xavg 5 marks · 2081, 2078, 0AnswerHideHow do you convert basic data type to user defined data type? Explain. [5]
How do you convert basic data type to user defined data type? Explain. [5]
In C++, converting a basic (built-in) data type (such as int, float, double, char) to a user-defined data type (such as a class or struct) is achieved using a special constructor called a conversion constructor. --- A conversion construc...
asked 3xavg 7 marks · 2082, 2081, 2079AnswerHideWhat is the difference between abstract class and concrete class? Explain with example. [5]
What is the difference between abstract class and concrete class? Explain with example. [5]
Abstract Class and Concrete Class in C++
What makes a class abstract in C++
C++ has no abstract keyword. A class becomes abstract the moment it declares at least one pure virtual function, written by putting = 0 after a virtual member function instead of a body:
virtual double area() const = 0; // pure virtual, so the class is abstract
An abstract class cannot be instantiated. The compiler refuses Shape s; with "cannot declare variable of abstract type". It can still be used as a base type: pointers and references of the abstract type are perfectly legal, and they are exactly how runtime polymorphism is obtained.
Because objects are usually deleted through a base pointer, an abstract base class should also declare a virtual destructor, otherwise the derived part of the object is never destroyed.
Key characteristics:
- At least one member function is declared pure virtual with
= 0. - No object of the class can be created, though base pointers and references are allowed.
- It may also contain ordinary data members and fully implemented member functions.
- A derived class stays abstract until it overrides every pure virtual it inherits.
What a concrete class is
A concrete class supplies a body for every function it declares or inherits, so nothing is left unimplemented. It can be instantiated directly, and it is the only kind of class from which real objects are made. A concrete class is very often a class derived from an abstract base that has filled in the missing implementations.
Key characteristics:
- Every inherited pure virtual function has been overridden.
- Objects can be created on the stack, with
new, or inside a container. - It may be a standalone class or the leaf of an inheritance hierarchy.
Comparison
| Feature | Abstract class | Concrete class |
|---|---|---|
| Instantiation | Not possible, only pointers and references | Objects can be created directly |
| Functions | Has at least one pure virtual (= 0) | Every function has a body |
| How it is declared | No keyword, the = 0 on a virtual marks it | Nothing special is written |
| Purpose | Defines an interface or a common template | Provides a usable, complete type |
| Destructor | Should be declared virtual | Virtual only if it is itself a base |
In Java the same idea is written with the abstract keyword on the class and on the method; in C++ the = 0 on a virtual function carries that meaning by itself.
Worked example
#include <iostream>
#include <string>
// Abstract class: it declares a pure virtual function, so no Shape object can exist.
class Shape {
protected:
std::string color;
public:
explicit Shape(const std::string& c) : color(c) {}
virtual ~Shape() = default; // virtual destructor for safe deletion via a base pointer
virtual double area() const = 0; // pure virtual: this is what makes Shape abstract
void displayColor() const { // an ordinary member, already implemented
std::cout << "Color: " << color << "\n";
}
};
// Concrete class: it gives a body to the inherited pure virtual function.
class Circle : public Shape {
double radius;
public:
Circle(double r, const std::string& c) : Shape(c), radius(r) {}
double area() const override { return 3.14159 * radius * radius; }
};
// Another concrete class from the same abstract base.
class Rectangle : public Shape {
double length, width;
public:
Rectangle(double l, double w, const std::string& c)
: Shape(c), length(l), width(w) {}
double area() const override { return length * width; }
};
int main() {
// Shape s("Red"); // compile error: cannot declare variable of abstract type Shape
Circle c(5.0, "Red");
c.displayColor();
std::cout << "Circle area: " << c.area() << "\n";
Rectangle r(4.0, 6.0, "Blue");
r.displayColor();
std::cout << "Rectangle area: " << r.area() << "\n";
const Shape& s = c; // a reference to the abstract type is legal and dispatches virtually
std::cout << "Through base reference: " << s.area() << "\n";
return 0;
}
Output:
Color: Red
Circle area: 78.5398
Color: Blue
Rectangle area: 24
Through base reference: 78.5398
Here Shape is the abstract class. It fixes the interface every shape must offer, area(), without deciding how any particular shape computes it, and it supplies one ready made service, displayColor(). Circle and Rectangle are the concrete classes: each overrides area(), so each can be instantiated. The commented out line shows the practical difference, since only the concrete types produce objects while the abstract type produces the common contract they all obey.
asked 3xavg 5 marks · 2082, 2079, 0AnswerHideExplain default arguments and inline functions in C++ with suitable examples. [5]
Explain default arguments and inline functions in C++ with suitable examples. [5]
--- Definition: Default arguments are values provided in a function declaration that are automatically used when the caller does not supply a corresponding argument. They allow a function to be called with fewer arguments than it is defi...
asked 3xavg 5 marks · 2082, 2080.1, 2080AnswerHideExplain friend function and friend class with example. [5]
Explain friend function and friend class with example. [5]
Friend Function and Friend Class in C++
Friend Function
A friend function is a function that is not a member of a class but has access to the private and protected members of that class. It is declared inside the class using the keyword friend.
Key Points:
- It is defined outside the class scope
- It is not called using an object (no
thispointer) - It can access private data of the class directly
Example of Friend Function
#include <iostream>
using namespace std;
class Rectangle {
private:
float length, breadth;
public:
Rectangle(float l, float b) {
length = l;
breadth = b;
}
// Declaring friend function
friend float calculateArea(Rectangle r);
};
// Definition of friend function (outside the class)
float calculateArea(Rectangle r) {
// Accessing private members directly
return r.length * r.breadth;
}
int main() {
Rectangle rect(5.0, 3.0);
cout << "Area = " << calculateArea(rect) << endl;
return 0;
}
Output:
Area = 15
Friend Class
A friend class is a class that is granted access to the private and protected members of another class. When a class is declared as a friend, all member functions of that friend class can access private data of the other class.
Key Points:
- Declared using
friend class ClassName;inside the class - Friendship is not mutual (if A is friend of B, B is not automatically friend of A)
- Friendship is not inherited
Example of Friend Class
#include <iostream>
using namespace std;
class Engine {
private:
int horsepower;
public:
Engine(int hp) {
horsepower = hp;
}
// Declaring Car as a friend class
friend class Car;
};
class Car {
public:
void showEngineDetails(Engine e) {
// Accessing private member of Engine class
cout << "Engine Horsepower: " << e.horsepower << endl;
}
};
int main() {
Engine eng(150);
Car car;
car.showEngineDetails(eng);
return 0;
}
Output:
Engine Horsepower: 150
Summary Table
| Feature | Friend Function | Friend Class |
|---|---|---|
| Type | A standalone function | A complete class |
| Declaration | friend returnType funcName(); | friend class ClassName; |
| Access | Private members of one class | Private members of another class |
| Membership | Not a member of the class | Not a member of the class |
Note: Use of friend functions and classes should be minimized as they break the principle of data encapsulation in Object-Oriented Programming.
asked 3xavg 5 marks · 2082, 2078, 0AnswerHideDifferentiate between early binding and late binding. Write a program to show dynamic polymorphism using virtual function. [2+3]
Differentiate between early binding and late binding. Write a program to show dynamic polymorphism using virtual function. [2+3]
--- Feature Early Binding (Static Binding) Late Binding (Dynamic Binding) --------- Time of Resolution Resolved at compile time Resolved at run time Mechanism Uses normal functions / function overloading Uses virtual functions Flexibilit...
asked 3xavg 5 marks · 2082, 2080.1, 0AnswerHideWhat are function templates? Also, write a program that swaps two values using function templates. [1+4]
What are function templates? Also, write a program that swaps two values using function templates. [1+4]
Function Templates
What are Function Templates?
A function template is a blueprint or formula for creating a family of related functions. It allows a single function definition to work with different data types, where the actual data type is determined at compile time when the function is called.
Key Points:
- Defined using the keyword
templatefollowed by template parameter list - Enables generic programming in C++
- The compiler automatically generates the appropriate function for each data type used
- Avoids code duplication for functions that perform the same operation on different types
Syntax:
template <typename T>
return_type function_name(T param1, T param2, ...) {
// function body
}
Here,
Tis a type parameter (placeholder for an actual data type likeint,float,char, etc.)
Program: Swapping Two Values Using Function Templates
#include <iostream>
using namespace std;
// Function template for swapping two values
template <typename T>
void swapValues(T &a, T &b) {
T temp;
temp = a;
a = b;
b = temp;
}
int main() {
// Swapping two integers
int x = 10, y = 20;
cout << "Before swap (int): x = " << x << ", y = " << y << endl;
swapValues(x, y);
cout << "After swap (int): x = " << x << ", y = " << y << endl;
cout << endl;
// Swapping two floats
float p = 3.14, q = 7.77;
cout << "Before swap (float): p = " << p << ", q = " << q << endl;
swapValues(p, q);
cout << "After swap (float): p = " << p << ", q = " << q << endl;
cout << endl;
// Swapping two characters
char c1 = 'A', c2 = 'Z';
cout << "Before swap (char): c1 = " << c1 << ", c2 = " << c2 << endl;
swapValues(c1, c2);
cout << "After swap (char): c1 = " << c1 << ", c2 = " << c2 << endl;
return 0;
}
Output
Before swap (int): x = 10, y = 20
After swap (int): x = 20, y = 10
Before swap (float): p = 3.14, q = 7.77
After swap (float): p = 7.77, q = 3.14
Before swap (char): c1 = A, c2 = Z
After swap (char): c1 = Z, c2 = A
Explanation
| Aspect | Detail |
|---|---|
template <typename T> | Declares T as a generic type parameter |
T &a, T &b | Pass by reference so original values are modified |
T temp | Temporary variable of the same generic type |
| Compiler behavior | Generates separate swapValues<int>, swapValues<float>, swapValues<char> automatically |
Advantage: Without templates, we would need to write three separate
swapfunctions forint,float, andchar. The function template handles all types with a single definition.
asked 2xavg 8 marks · 2081, 2080.1AnswerHideDefine stream.How do you read and write binary files?Write a program to read an integer from the user and if the integer is less than 100 then write it in file named "SMALL.TXT" otherwise write in file named "LARGE.TXT".[2+3+5]
Define stream.How do you read and write binary files?Write a program to read an integer from the user and if the integer is less than 100 then write it in file named "SMALL.TXT" otherwise write in file named "LARGE.TXT".[2+3+5]
Streams, Binary File I/O, and File Writing Program
1. Definition of Stream (2 marks)
A stream is an abstraction that represents a flow of data between a program and an input/output device (such as a keyboard, monitor, disk file, etc.).
- A stream acts as a logical interface between the program and the actual I/O device.
- In C++, streams are implemented through a hierarchy of classes defined in headers like
<iostream>and<fstream>. - There are two main types:
- Input Stream: Data flows into the program (e.g., reading from a file or keyboard).
- Output Stream: Data flows out of the program (e.g., writing to a file or screen).
Key stream classes:
ifstream(input file stream),ofstream(output file stream),fstream(both input and output).
2. Reading and Writing Binary Files (3 marks)
Binary files store data in the same format as it is stored in memory (raw bytes), unlike text files which store data as readable characters.
Opening a Binary File
Use the ios::binary flag along with the file mode:
ifstream fin("file.dat", ios::in | ios::binary); // reading
ofstream fout("file.dat", ios::out | ios::binary); // writing
Writing to a Binary File
Use the write() member function:
fout.write((char*) &variable, sizeof(variable));
- The first argument is a pointer to the data cast to
char*. - The second argument is the number of bytes to write.
Reading from a Binary File
Use the read() member function:
fin.read((char*) &variable, sizeof(variable));
Example
#include <fstream>
using namespace std;
int main() {
int num = 42;
// Write binary
ofstream fout("data.bin", ios::out | ios::binary);
fout.write((char*) &num, sizeof(num));
fout.close();
// Read binary
int readNum;
ifstream fin("data.bin", ios::in | ios::binary);
fin.read((char*) &readNum, sizeof(readNum));
fin.close();
return 0;
}
3. Program: Write Integer to SMALL.TXT or LARGE.TXT (5 marks)
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int num;
// Read integer from user
cout << "Enter an integer: ";
cin >> num;
if (num < 100) {
// Write to SMALL.TXT
ofstream fout("SMALL.TXT", ios::app); // ios::app to append
if (!fout) {
cout << "Error opening SMALL.TXT!" << endl;
return 1;
}
fout << num << endl;
fout.close();
cout << num << " has been written to SMALL.TXT" << endl;
} else {
// Write to LARGE.TXT
ofstream fout("LARGE.TXT", ios::app); // ios::app to append
if (!fout) {
cout << "Error opening LARGE.TXT!" << endl;
return 1;
}
fout << num << endl;
fout.close();
cout << num << " has been written to LARGE.TXT" << endl;
}
return 0;
}
Sample Output
Enter an integer: 45
45 has been written to SMALL.TXT
Enter an integer: 250
250 has been written to LARGE.TXT
Explanation of Key Steps
| Step | Description |
|---|---|
cin >> num | Reads integer from the user |
if (num < 100) | Checks the condition |
ofstream fout("SMALL.TXT", ios::app) | Opens SMALL.TXT in append mode |
ofstream fout("LARGE.TXT", ios::app) | Opens LARGE.TXT in append mode |
if (!fout) | Checks if file opened successfully |
fout << num | Writes the integer to the file |
fout.close() | Closes the file after writing |
Note:
ios::app(append mode) is used so that previously written values are not overwritten each time the program runs. You may also useios::outif overwriting is acceptable.
asked 2xavg 8 marks · 2081, 2079AnswerHideHow does structure differ with class?What are the uses of friend function and friend class?Explain the types of constructors.[1+3+6]
How does structure differ with class?What are the uses of friend function and friend class?Explain the types of constructors.[1+3+6]
Structure vs Class, Friend Functions/Classes, and Types of Constructors
1. How does Structure differ with Class?
In C++, struct and class are almost identical, with one key difference:
| Feature | Structure (struct) | Class (class) |
|---|---|---|
| Default access specifier | Public | Private |
| Default inheritance | Public | Private |
| General use | Simple data grouping | Full OOP with data hiding |
Example:
struct S { int x; }; // x is public by default
class C { int x; }; // x is private by default
In C++, a
structcan also have member functions, constructors, and inheritance, just like a class.
2. Uses of Friend Function and Friend Class
Friend Function
A friend function is a non-member function that is granted access to the private and protected members of a class by declaring it with the keyword friend inside the class.
Uses:
- To allow an external function to access private data of a class
- Useful for operator overloading (e.g.,
<<,>>) - To allow two classes to share data without making members public
Syntax:
class Box {
private:
int length;
public:
Box(int l) { length = l; }
friend void showLength(Box b); // friend declaration
};
void showLength(Box b) {
cout << "Length: " << b.length; // accesses private member
}
Friend Class
A friend class is a class that is granted access to the private and protected members of another class.
Uses:
- When two closely related classes need to share private data
- Useful in implementing container and iterator relationships
Syntax:
class Engine {
private:
int horsepower;
public:
Engine(int hp) { horsepower = hp; }
friend class Car; // Car is a friend of Engine
};
class Car {
public:
void show(Engine e) {
cout << "HP: " << e.horsepower; // accesses private member
}
};
Note: Friendship is not inherited and not mutual (if A is a friend of B, B is not automatically a friend of A).
3. Types of Constructors
A constructor is a special member function that has the same name as the class, has no return type, and is automatically called when an object is created. It is used to initialize objects.
Type 1: Default Constructor
A constructor that takes no arguments (or all arguments have default values).
- Automatically provided by the compiler if no constructor is defined
- Called when an object is created without any arguments
class Student {
public:
int roll;
string name;
Student() { // Default constructor
roll = 0;
name = "Unknown";
}
};
int main() {
Student s; // Default constructor called
}
Type 2: Parameterized Constructor
A constructor that accepts one or more arguments to initialize an object with specific values.
- Allows different objects to be initialized with different values
- Supports constructor overloading
class Student {
public:
int roll;
string name;
Student(int r, string n) { // Parameterized constructor
roll = r;
name = n;
}
};
int main() {
Student s1(1, "Ram");
Student s2(2, "Sita");
}
Type 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 parameter.
- Called when an object is initialized from another object
- Called when an object is passed by value to a function
- Called when an object is returned by value from a function
class Student {
public:
int roll;
string name;
Student(int r, string n) {
roll = r;
name = n;
}
Student(const Student &s) { // Copy constructor
roll = s.roll;
name = s.name;
}
};
int main() {
Student s1(1, "Ram");
Student s2(s1); // Copy constructor called
Student s3 = s1; // Copy constructor called
}
Summary Table
| Type | Arguments | Purpose |
|---|---|---|
| Default Constructor | None | Initializes object with default values |
| Parameterized Constructor | One or more | Initializes object with given values |
| Copy Constructor | Reference to same class object | Creates a copy of an existing object |
Key Points:
- A class can have multiple constructors (overloading)
- Constructors cannot be inherited but a derived class can call the base class constructor
- If any constructor is defined, the compiler does not provide a default constructor automatically
asked 2xavg 8 marks · 2080.1, 2080AnswerHideDifferentiate between virtual function and pure virtual function with an example. [5]
Differentiate between virtual function and pure virtual function with an example. [5]
A virtual function is a member function declared in a base class using the virtual keyword that can be overridden in derived classes. It has a definition (body) in the base class, so objects of the base class can still be instantiated an...
asked 2xavg 5 marks · 2081, 2079AnswerHideDescribe the features of object oriented programming. [5]
Describe the features of object oriented programming. [5]
Note: No specific reference notes were found for this topic. The following answer is based on standard, well-established OOP concepts as taught in BSc CSIT curriculum. --- Object Oriented Programming (OOP) is a programming paradigm that ...
asked 2xavg 5 marks · 2081, 2080AnswerHideHow do you return object in function? Describe with an example. [5]
How do you return object in function? Describe with an example. [5]
In C++, a function can return an object of a class just like it returns any other data type. The return type of the function is specified as the class name, and the return statement returns an object of that class. Syntax: --- - The retu...
Study every one of these with model answers, flashcards, and MCQs.
Open BIT153 study modes