BEU Patna B.Tech C++ PYQ – Semester 3 (Object Oriented Programming Using C++)
Download BEU Patna (Bihar Engineering University) B.Tech Semester 3 Previous Year Question Paper for Object Oriented Programming Using C++. Get solved answers, important questions, exam pattern, and preparation tips for scoring high in the BEU OOP C++ exam.

This examination paper for Bihar Engineering University, Patna evaluates the understanding of the subject Object Oriented Programming using C++ for Semester III students. The question pattern covers the core concepts of C++ such as classes, objects, inheritance, polymorphism, templates, operator overloading, constructors, destructors, exception handling, and memory management. The marks for each question are clearly mentioned, and students are required to attempt five questions in total, with Question 1 being compulsory. The duration of the exam is three hours, and the maximum marks are 70. This question paper aims to test both conceptual clarity and practical programming skills of students.
Bihar Engineering University, Patna
End Semester Examination - 2022
Semester: III
Course | B.Tech. | Time | 03 Hours |
|---|---|---|---|
Code | 100313 | Full Marks | 70 |
Subject | Object Oriented Programming using C++ |
Instructions:
The marks are indicated in the right-hand margin.
There are NINE questions in this paper.
Attempt FIVE questions in all.
Question No. 1 is compulsory.
Q.1 Choose the correct answer of the following (Any seven question only): [2 x 7 = 14]
(a) Which among the following best describes the inheritance?
copying the code already written
using the code already written once.
using already defined functions in programming language
using the data and functions into derived segment.
(b) Which of the following is not a type of class?
Abstract class
Final class
Start class
String class
(C) What is the default access specifier for data members or member functions declared within a class without any specifier in C++?
Private
Protected
Public
Depends on compiler
(d) Which of the following is not the member of class?
Static function
Friend function
Constant function
Virtual function
(e) Which constructor will be called from the object created in the code below?
Class A
{
int i;
A ( )
{
i=0;
}
A (int x = 0)
{
i=x;
}
};
A obj1;Default constructor
Parameterized constructor
Compile time error
Run-time error
(f) To prevent any method from overriding, we declare the method as
Static
const
final
None of the above
(g) In C++ dynamic memory allocation is accomplished with the operator:
new
this
malloc
delete
(h) When a class serves as base class for many derived classes, the situation is called
polymorphism
hierarchical inheritance
hybrid inheritance
multipath inheritance
(i) For a method to be an interface between the outside world and a class, it must be declared
private
protected
public
external
(j) Which of the following statement is correct?
Base class pointer cannot point to derived class
Derived class pointer cannot point to base class.
Pointer to derived class cannot be created
Pointer to base class cannot be created.
Q.2
(a) What are the advantages of using exception handling mechanism in a program? [7]
(b) Write a C++ program to find the sum of the series 1+3+5+… +n. [7]
Q.3
(a) What is inheritance? Discuss different types of inheritance with examples. [7]
(b) What is operator overloading? Write a program in C++ to overload unary minus operator. [7]
Q.4
(a) What is pure virtual function? Write a C++ program that prints ‘BEU Patna’ from inside a member function of a subclass overriding a pure virtual function. [7]
(b) Discuss why converting a base-class pointer to a derived-class pointer is considered dangerous by compiler. [7]
Q.5
(a) Differentiate between abstract class and interface with suitable examples. [7]
(b) What is access modifier in C++? Differentiate between each type. [7]
Q.6
(a) Differentiate between a class and an object. Write an example (syntax) to define a class in C++. [7]
(b) With an example, explain the terms constructor and destructor. [7]
Q.7
(a) What is a friend function and what are its advantages? What are the guidelines that should be followed while using friend function? [7]
(b) Explain dangling pointer with the help of an example. [7]
Q.8
(a) Explain how base class member functions can be involved in a derived class if the derived class also has a member function with the same name. [7]
(b) Create a class complex and implement the following: [7]
(i) Define suitable constructors and destructors
(ii) Overload the operators + and -
(iii) Write a friend function sum which adds the real and imaginary parts of a complex object.
Q.9
Write short notes on any two of the following: [7 x 2=14]
(a) Polymorphism
(b) Function Templates
(C) Container class
(d) Inline function
Answers
Q.1 Choose the correct answer of the following (Any seven question only): [2 x 7 = 14]
(a) Which among the following best describes the inheritance?
copying the code already written
using the code already written once.
using already defined functions in programming language
✔ using the data and functions into derived segment.
Explanation
Inheritance means one class (child/derived) can use the data and functions of another class (parent/base).
It helps reuse code without copying and pasting.
(b) Which of the following is not a type of class?
Abstract class
Final class
✔ Start class
String class
Explanation
In C++, there is no concept called “Start class.”
Abstract classes, final classes, and even string classes exist or are meaningful terms.
(c) Default access specifier in a class
✔ Private
Protected
Public
Depends on compiler
Explanation
If you write data members or functions inside a class in C++ without writing public/private/protected, C++ automatically treats them as private.
(d) Which of the following is not the member of a class?
Static function
✔ Friend function
Constant function
Virtual function
Explanation
A friend function is allowed to access the class, but it is not inside the class.
It is declared using the keyword friend, but it is not considered a member.
(e) Which constructor will be called?
Class A
{
int i;
A ( )
{
i=0;
}
A (int x = 0)
{
i=x;
}
};
A obj1;
Default constructor
Parameterized constructor
✔ Compile-time error
Run-time error
Explanation
You have two constructors:
A() {
i = 0;
}
A(int x = 0) {
i = x;
}
But the second one has a default argument, which means:
A(int x = 0) // can also act like a no-argument constructor
Now the problem is:
When you write:
A obj1;
Both constructors could match this call:
A()→ exact matchA(int x = 0)→ also matches because it can take zero arguments
But in C++, this situation becomes ambiguous. The compiler must choose one constructor, but both are valid, so it cannot decide.
❌ This leads to a compile-time error, not a valid call.
Correct Explanation
This situation is a compile-time decision, not run-time.
When you write:
A obj1;
The compiler must decide which constructor matches best.
Here you have:
A()A(int x = 0)// has a default argument
Both look like they could match a call with no arguments.
C++ rules say:
If two constructors can match equally, and one is “better”, the compiler tries to pick one.
But here they are ambiguous (both match perfectly).
👉 This causes a compile-time error — constructor call is ambiguous.
So the correct answer should be:
❌ Default constructor
❌ Parameterized constructor
✔ Compile-time error
❌ Run-time error
Reason:
Both constructors take zero arguments (because the second one can take 0). The compiler cannot decide, so it fails at compile time, before the program runs.
❌ It does not call the parameterized constructor.
❌ It does not call the default constructor.
✔ It gives a compile-time error due to ambiguity.
Because both constructors match A obj1;, the compiler sees two possible choices:
Zero-argument constructor
Parameterized constructor with default value
This creates ambiguity → compiler error.
So the correct output is Compile-time error
(f) To prevent any method from overriding, we declare the method as
Static
const
✔ final
None of the above
Explanation
When you write final with a method, it cannot be overridden in a derived class.
It is used in OOP languages including C++ (in modern C++ with final specifier).
(g) In C++ dynamic memory allocation is accomplished with:
✔ new
this
malloc
delete
Explanation
new is used to create memory dynamically in C++.
Example: int *p = new int;malloc is from C language.
(h) When a class serves as base class for many derived classes
polymorphism
✔ hierarchical inheritance
hybrid inheritance
multipath inheritance
Explanation
If one base class has many child classes, the structure is hierarchical inheritance.
(i) For a method to be an interface between outside world and a class, it must be
private
protected
✔ public
external
Explanation
Only public methods can be accessed from outside the class.
So they become the “interface” of the class.
(j) Which statement is correct?
Base class pointer cannot point to derived class
✔ Derived class pointer cannot point to base class.
Pointer to derived class cannot be created
Pointer to base class cannot be created
Explanation
A base class pointer can point to a derived object (polymorphism).
But a derived pointer cannot point to a base class object because the base does not contain extra features of derived.
Q.2(a) What are the advantages of using exception handling mechanism in a program? [7]
Answer:
Exception handling is a feature in C++ that allows a program to detect and handle errors during runtime without crashing. It separates normal program logic from error-handling logic so the code becomes cleaner and easier to manage.
Advantages of Exception Handling
1. Program does not crash unexpectedly
If an error happens (like division by zero or file not found), the program does not stop suddenly. Instead, it jumps to the catch block.
Example: If a user enters 0 in division, the program shows a message instead of stopping.
2. Easy to handle runtime errors
Runtime errors like invalid input, memory issues, or file errors can be caught safely.
You can handle different errors using different catch blocks.
3. Helps in separating error-handling code
Normal code is written in try block, error-handling code in catch block.
This makes the program easy to read and maintain.
4. Supports multiple error types
You can catch different types of errors using different exception types like int, char, string, or custom exception classes.
5. Helps in building robust and reliable programs
Exception handling ensures the program works smoothly even when unexpected situations occur. This improves overall program quality.
6. Avoids using many if-else statements
Without exception handling, programmers check each line using if-else.
Exception handling reduces this and makes code cleaner.
7. Allows programmer to define custom errors
Users can create their own exception classes and throw meaningful messages.
Small Example:
try {
int a, b;
cin >> a >> b;
if (b == 0)
throw "Division by zero not allowed!";
cout << a / b;
}
catch (const char* msg) {
cout << msg;
}
This code avoids a crash and handles division error safely.
Q.2(b) Write a C++ program to find the sum of the series 1 + 3 + 5 + … + n. [7]
Answer:
This series represents odd numbers starting from 1 up to n.
Example: If n = 9 → series = 1 + 3 + 5 + 7 + 9.
We can use a loop to add odd numbers one by one.
C++ Program
#include <iostream>
using namespace std;
int main() {
int n, sum = 0;
cout << "Enter the value of n: ";
cin >> n;
// Adding odd numbers from 1 to n
for (int i = 1; i <= n; i += 2) {
sum += i;
}
cout << "Sum of the series 1 + 3 + 5 + ... + " << n << " is: " << sum;
return 0;
}
Explanation:
The user enters the value of n (last number of the series).
We start a loop from 1 and increase by 2 every time (so that we get only odd numbers).
Each odd number is added to sum.
Finally, the program displays the total sum.
Example Output:
Enter the value of n: 9
Sum of the series 1 + 3 + 5 + ... + 9 is: 25
(1 + 3 + 5 + 7 + 9 = 25)
Q.3 (a) What is inheritance? Discuss different types of inheritance with examples. [7]
Answer:
Inheritance is an important feature of Object-Oriented Programming (OOP) that allows one class (called derived class or child class) to use the properties and functions of another class (called base class or parent class).
It helps in code reusability and reduces duplication.
Example:
If class Car has data like speed and functions like start(), then a class SportsCar can inherit these features from Car.
Types of Inheritance in C++
1. Single Inheritance
One base class → one derived class.
Example:
class A { };
class B : public A { };
2. Multilevel Inheritance
A derived class becomes a base class for another class.
Example:
class A { };
class B : public A { };
class C : public B { };
3. Multiple Inheritance
One derived class inherits from two or more base classes.
Example:
class A { };
class B { };
class C : public A, public B { };
4. Hierarchical Inheritance
One base class → multiple derived classes.
Example:
class A { };
class B : public A { };
class C : public A { };
5. Hybrid Inheritance
Combination of two or more inheritance types.
Example: mixture of hierarchical + multiple.
6. Multipath Inheritance (diamond problem)
A class is derived from two classes which have a common base class.
To solve ambiguity, virtual inheritance is used.
Q.3 (b) What is operator overloading? Write a program in C++ to overload unary minus operator. [7]
Answer: Operator overloading is a feature of C++ that allows a programmer to redefine how an operator (like +, -, *, ==, ++) should work when it is used with objects instead of basic data types.
It helps make object operations look natural and easy to understand.
Example:-obj → can reverse the sign of values inside an object.obj1 + obj2 → can add two objects in a meaningful way.
Important Points
1. Operators behave differently for objects
Normally, operators work only for built-in types like int, float, double.
With operator overloading, we can teach operators how to work with user-defined types (classes).
This makes code easy and readable.
Example:complex1 + complex2 looks natural for complex numbers.
2. Makes code more natural and readable
Instead of calling functions likeobj.add(obj2)
we can simply writeobj + obj2.
This looks cleaner and closer to real mathematics.
3. Only existing operators can be overloaded
We cannot create new symbols.
We can only redefine meaning of existing operators like +, -, *, /, ==, >>, [].
Example:operator+()operator-()operator==()
4. Operator overloading works through special functions
Each overloaded operator is implemented using a function written inside a class.
The function always starts with the keyword operator.
Example:
void operator -() {
// code
}
This runs automatically when we write -obj.
5. It does not change the original behavior of operators
Overloading only adds new behavior for objects.
The original behavior for int, float, etc. remains unchanged.
Example:5 + 3 works normally even if you overload + for your class.
6. Helps in working with abstract data types
If you create classes like Complex numbers, Matrix, Vector, Time, Fractions, etc.,
operator overloading makes them work naturally like numbers.
Example:time1 + time2vector1 - vector2matrix1 * matrix2
7. Unary and binary operators can be overloaded
There are two types:
Unary operators → work on one operand
Example:-obj,++objBinary operators → work on two operands
Example:obj1 + obj2
8. Some operators cannot be overloaded
A few operators cannot be overloaded:
sizeof.(dot operator)?:(ternary operator)::(scope resolution)
This is a rule of C++.
9. Supports both member and friend functions
Operator functions can be written as:
member functions
friend functions (if you want access to private data)
Short Example (Unary Minus)
-obj;
This calls:
void operator -() {
x = -x;
}
So operator overloading lets objects behave like basic data types.
Program to Overload Unary Minus Operator
#include <iostream>
using namespace std;
class Number {
int x;
public:
Number(int a) {
x = a;
}
// Overloading unary minus operator
void operator - () {
x = -x;
}
void display() {
cout << "Value = " << x << endl;
}
};
int main() {
Number n1(10);
cout << "Before overloading: ";
n1.display();
-n1; // calling overloaded operator
cout << "After overloading: ";
n1.display();
return 0;
}
Explanation:
The operator function
operator -()changes the value of x to its negative.When we write
-n1, it calls the overloaded unary minus function automatically.
Q.4 (a) What is pure virtual function? Write a C++ program that prints “BEU Patna”. [7]
A pure virtual function is a function declared in a base class that has no body and must be overridden in the derived class.
It makes the base class abstract, meaning objects of that class cannot be created.
Important Points :
A pure virtual function is declared using
= 0at the end of the function declaration.
Example:virtual void show() = 0;It forces every derived class to provide its own definition of the function.
Any class containing at least one pure virtual function becomes an abstract class.
You cannot create objects of an abstract class, but you can create pointers.
Pure virtual functions support runtime polymorphism.
They help in achieving interface-style programming in C++.
They ensure that derived classes follow a common structure.
Program (Overriding Pure Virtual Function):
#include <iostream>
using namespace std;
class Base {
public:
virtual void display() = 0; // pure virtual function
};
class Derived : public Base {
public:
void display() {
cout << "BEU Patna";
}
};
int main() {
Derived d;
d.display();
return 0;
}
Q.4 (b) Why converting a base-class pointer to a derived-class pointer is considered dangerous? [7]
Converting a base-class pointer to a derived-class pointer is unsafe because the derived class contains extra data members and functions that the base class does not have.
If we force this conversion, the program may try to access memory that does not belong to the base object.
Important Points :
A base-class object only has base-class members, but a derived class has additional members.
When a base-class pointer is forcefully converted to a derived-class pointer, the program assumes extra data exists, which it actually does not.
Accessing these non-existing members leads to undefined behavior or runtime crashes.
The compiler cannot guarantee memory layout compatibility between base and derived objects.
Such conversion breaks type safety, which is why the compiler warns against it.
It can lead to corrupted memory access, because derived-class functions may expect more memory.
Safe direction:
Base pointer ← Derived object (Allowed)
Dangerous direction:
Derived pointer ← Base object (Not allowed)
Discussion:
A derived class has more members (data and functions) than the base class.
A base-class object does not contain these extra members.When a base-class pointer is converted to a derived-class pointer, the program assumes the base object contains derived-class members, which is not true.
Accessing these non-existing members leads to undefined behavior, such as garbage values or program crash.
The memory layout of the base-class object is smaller than that of a derived-class object.
Converting upward tries to read memory beyond the valid object area.This violates type safety, because the compiler cannot guarantee that the base object can act like a derived object.
Virtual functions make the pointer even more unsafe, because the derived class may override methods that depend on extra data not present in the base object.
The compiler protects you from this conversion because it can lead to:
corrupted memory access
invalid function calls
wrong output
runtime crash
unpredictable behavior
The only safe direction is:
Base-class pointer ← Derived-class object (Allowed and safe)
But the opposite direction:
Derived-class pointer ← Base-class object (Dangerous)
is blocked by the compiler.
Q.5 (a) Differentiate between abstract class and interface with suitable examples. [7]
An abstract class is a class that contains at least one pure virtual function and may also contain data members, constructors, and normal member functions.
An interface is a structure where all functions are pure virtual and no data members are allowed.
(In C++, interface is created using a class with all pure virtual functions.)
Below is the best exam-style answer, with a neat comparison table first, and then full bullet-point explanations for each difference.
No extra wording — clean, simple, and ready to write in your copy.
Feature | Abstract Class | Interface (in C++: class with all pure virtual functions) |
|---|---|---|
Function Types | Can have normal + pure virtual functions | Only pure virtual functions |
Data Members | Can have data members | Cannot have normal data members |
Constructors | Allowed | Not allowed |
Multiple Inheritance | Difficult (single inheritance normally) | Supports multiple inheritance |
Usage | When you want to share common code | When you want to enforce rules only |
Flexibility | More flexible (can contain implemented methods) | Less flexible (only declarations) |
Object Creation | Cannot create objects | Cannot create objects |
Keyword for Pure Virtual |
| Same, but all functions must be pure virtual |
Full Explanation
1. Function types
Abstract Class:
Contains both implemented functions and pure virtual functions.Interface:
Contains only pure virtual functions; no function body allowed.
2. Data Members
Abstract Class:
Can include variables, constants, and other members.Interface:
Cannot contain normal variables; mainly pure function declarations.
3. Constructors
Abstract Class:
Can have constructors because it may contain implemented functions.Interface:
Cannot have constructors since no object of it can be created and it has no implementation.
4. Inheritance
Abstract Class:
A class generally inherits from one abstract class.Interface:
A class can inherit multiple interfaces at the same time (solving multiple-inheritance needs).
5. Purpose
Abstract Class:
Use when some common behavior/code must be shared across classes.Interface:
Use when you want to enforce that all derived classes follow the same method names.
6. Code sharing
Abstract Class:
Can provide shared methods and data for subclasses.Interface:
Cannot share code; only defines rules.
Simple Examples
Abstract Class Example
class Shape {
public:
int color;
virtual void draw() = 0; // pure virtual
void setColor(int c) { color = c; }
};
Interface Example (in C++)
class Printable {
public:
virtual void print() = 0; // pure virtual
};Q.5 (b) What is access modifier in C++? Differentiate between each type.
Access modifiers in C++ are keywords used to control the visibility and accessibility of class members (data and functions).
The three main access modifiers are private, protected, and public.
Comparison Table of Access Modifiers
Access Modifier | Access in Same Class | Access in Derived Class | Access Outside Class | Used For |
|---|---|---|---|---|
Private | Yes | No | No | Hiding sensitive data |
Protected | Yes | Yes | No | Allowing inheritance but blocking outside access |
Public | Yes | Yes | Yes | Interface / public functionality |
Full Explanation in Bullet Points
1. Private
Members are only accessible inside the class.
Not inherited in a usable way by derived classes (becomes private).
Cannot be accessed through objects.
Used to hide important data such as passwords, salary, marks.
Example:
private:
int salary;2. Protected
Accessible inside the class.
Accessible inside derived classes.
Not accessible outside the class or through objects.
Useful when child classes need some access but external users should not.
Example:
protected:
int roll;
3. Public
Accessible inside the class, derived classes, and outside the class.
Can be accessed using objects.
Used for public methods such as getters, setters, display(), etc.
Forms the interface of a class.
Example:
public:
void show();Q.6 (a) Differentiate between a Class and an Object. Write syntax of a class. [7]
Feature | Class | Object |
|---|---|---|
Meaning | A blueprint or template | A real instance created from the class |
Memory Allocation | No memory allocated | Memory is allocated |
Use | Defines data and functions | Uses the data and functions |
Type | Logical structure | Physical entity |
Creation | Created using | Created using class name |
Count | Only one class needed | Many objects can be created from a class |
Example | Class Car | Objects: Car c1, Car c2 |
Class
A class is like a design or blueprint.
It contains data members (variables) and member functions.
No memory is allocated when a class is defined.
Used to model real-world things like Student, Car, Laptop, etc.
Object
An object is a real instance of a class.
Memory is allocated when an object is created.
You can create many objects from the same class.
Each object has its own copy of data.
Syntax to Define a Class in C++
class ClassName {
private:
int data;
public:
void show() {
// code
}
};
Example object creation:
ClassName obj; // obj is an object
Q.6 (b) With an example, explain the terms constructor and destructor. [7]
Constructor
A constructor is a special member function of a class used to initialize objects.
Its name is the same as the class name and it has no return type.
Called automatically when an object is created.
Used to initialize variables.
Same name as class.
No return type (not even void).
Can be overloaded (multiple constructors allowed).
Destructor
A destructor is a special member function that is executed when an object is destroyed.
Its name is the same as the class name but starts with a tilde (~).
Used to free memory or close files.
Called automatically when the object goes out of scope or program ends.
Used for cleanup tasks (free memory, close files).
Same name as class but starts with
~.Cannot be overloaded (only one destructor allowed).
No parameters.
Example Program Demonstrating Constructor and Destructor
#include <iostream>
using namespace std;
class Demo {
public:
// Constructor
Demo() {
cout << "Constructor called: Object created" << endl;
}
// Destructor
~Demo() {
cout << "Destructor called: Object destroyed" << endl;
}
};
int main() {
Demo obj; // Constructor runs here
// When main ends, destructor runs automatically
return 0;
}
Output:
Constructor called: Object created
Destructor called: Object destroyed
Q.7 (a) What is a friend function? What are its advantages? What guidelines should be followed? [7]
A friend function is a normal function that is not a member of a class but is allowed to access the private and protected members of that class.
It is declared using the keyword friend inside the class.
Example:
friend void showData(MyClass obj);
Advantages of Friend Function (Bullet Points)
Access to private data:
Can access private and protected members of a class directly, which normal functions cannot do.Useful for operator overloading:
Many binary operators (+, -, ==) are easier to overload using friend functions.Improves flexibility:
Allows operations involving two different classes (like adding objects of two classes).Not called through objects:
Friend functions can be called like normal functions without needing an object.Helpful in debugging:
Can access hidden data, making testing and debugging easier.
Guidelines While Using Friend Functions
Use only when necessary:
Overuse of friend functions breaks the concept of data hiding (encapsulation).Keep the number of friend functions limited:
Only provide friend access to functions that really need inside access.Declare inside class but define outside:
The function is declared withfriendbut defined normally.Not in inheritance:
Friendship is not inherited — child classes do not get friend access automatically.Friendship is not mutual:
If class A declares class B as a friend, class B does NOT become a friend of class A automatically.Friendship is not transitive:
If A is friend of B, and B is friend of C, A is not friend of C automatically.
Q.7 (b) Explain dangling pointer with the help of an example. [7]
A dangling pointer is a pointer that points to memory which has already been freed, deleted, or is no longer valid.
Accessing a dangling pointer leads to unpredictable behavior or program crash.
A dangling pointer occurs when the memory pointed by a pointer gets deleted or goes out of scope.
The pointer still holds the old address, but that memory is no longer valid.
Accessing or modifying data through a dangling pointer gives garbage values or crashes.
Causes of dangling pointers:
Deleting memory using
deleteReturning pointer to a local variable
Scope ending for a local variable
Dangerous because program may read/write unknown memory.
Example of Dangling Pointer
#include <iostream>
using namespace std;
int main() {
int *ptr = new int(10); // dynamic memory allocated
delete ptr; // memory freed
cout << *ptr; // Dangling pointer (dangerous!)
return 0;
}
Explanation
ptrinitially points to valid memory.After
delete ptr;, the memory is freed.But
ptrstill stores the old address → dangling pointer.Accessing
*ptrnow is unsafe and produces garbage output.
Correct way
Set pointer to NULL after deletion:
delete ptr;
ptr = nullptr;
Q.8 (a)Explain how base class member functions can be invoked in a derived class if the derived class also has a member function with the same name. [7]
When a derived class has a function with the same name as a base class function, the derived class version overrides the base version.
In such cases, we can still access the base class function explicitly using the scope resolution operator BaseClassName::.
If both base and derived class have functions with the same name, the derived version hides the base version.
Even though the function is hidden, the base class function can still be called inside the derived class.
To call the base class version, we use:
BaseClassName::functionName()This resolves ambiguity and clearly tells the compiler to use the base class function.
It is commonly used in inheritance when you want to use both the old behavior (from base class) and the new overridden behavior (from derived class).
Useful when derived class extends functionality instead of replacing it entirely.
Works for both normal functions and constructors (with initialization list).
Example
class Base {
public:
void display() {
cout << "Base class display" << endl;
}
};
class Derived : public Base {
public:
void display() {
cout << "Derived class display" << endl;
Base::display(); // calling base version
}
};
Calling:
Derived d;
d.display();
Output:
Derived class display
Base class display
Q.8 (b)Create a class Complex and implement
(i) constructors & destructor
(ii) overload + and –
(iii) friend function sum() to add real & imaginary parts.
PROGRAM
#include <iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
// Constructor
Complex(int r = 0, int i = 0) {
real = r;
imag = i;
}
// Destructor
~Complex() {
// nothing extra, but for demonstration
}
// Operator overloading +
Complex operator + (Complex c) {
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
// Operator overloading -
Complex operator - (Complex c) {
Complex temp;
temp.real = real - c.real;
temp.imag = imag - c.imag;
return temp;
}
// Friend function to add real + imag together
friend int sum(Complex c);
void show() {
cout << real << " + " << imag << "i" << endl;
}
};
// Friend function definition
int sum(Complex c) {
return (c.real + c.imag);
}
int main() {
Complex c1(5, 3), c2(2, 4);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
cout << "Addition: ";
c3.show();
cout << "Subtraction: ";
c4.show();
cout << "Sum of real and imaginary of c1 = " << sum(c1);
return 0;
}
Summary of What This Program Does
Constructor initializes the real and imaginary values.
Destructor runs automatically when the object is destroyed.
operator+adds corresponding real and imaginary parts.operator-subtracts corresponding parts.friend int sum(Complex)adds real + imag of a complex number.The program demonstrates all required concepts cleanly.
Q.9 Write short notes on any two of the following: [7 x 2=14]
(a) Polymorphism
(b) Function Templates
(C) Container class
(d) Inline function
(a) Polymorphism
Polymorphism means one name and many forms.
It allows the same function or operator to behave differently depending on the situation or the type of object calling it.
Key Points
It is an important feature of Object-Oriented Programming.
Helps perform the same action in different ways.
Achieved in C++ in two major forms:
Compile-time polymorphism → function overloading, operator overloading
Runtime polymorphism → using virtual functions and pointers
Makes code flexible and easy to maintain.
Supports reusability because the same function name can handle different types of data.
Useful in applications like graphics, simulations, and real-time systems.
Implementation is based on the idea that derived classes can override base class functions.
Simple Example (Runtime Polymorphism)
class Base {
public:
virtual void show() { cout << "Base"; }
};
class Derived : public Base {
public:
void show() { cout << "Derived"; }
};
Base *b;
Derived d;
b = &d;
b->show(); // calls Derived version
(b) Function Templates
A function template allows the creation of a single function that can work with different data types.
It avoids writing multiple functions for int, float, double, etc.
Key Points
Introduced in C++ to support generic programming.
Reduces duplicate code because one function works for all types.
Created using the keyword template.
The data type is represented using typename T or class T.
The compiler automatically creates the required version of the function during compilation.
Increases code flexibility and decreases the chance of errors.
Commonly used in sorting, searching, and mathematical operations.
Simple Example
template <class T>
T add(T a, T b) {
return a + b;
}
cout << add(3, 5); // int
cout << add(3.2, 4.5); // double
(c) Container Class
A container class is a class that holds and manages a group of objects as a single unit.
It “contains” objects and provides functions to insert, remove, or access them.
Key Points (Bullet List)
Used for storing multiple elements together.
Provides methods like add, remove, count, display, search.
Offers encapsulation, where the data structure is hidden from the user.
Examples of container classes:
vector,list,stack,queue,array.Helps in organizing and managing large collections of data.
Supports iteration (looping through elements).
Part of Standard Template Library (STL), commonly used in C++ programming.
Simple Example (User-made container)
class Container {
int arr[10];
int size;
public:
void add(int x) { arr[size++] = x; }
int get(int i) { return arr[i]; }
};
(d) Inline Function
An inline function is a function in which the compiler replaces the function call with the actual function code, to save time.
Key Points (Bullet List)
Declared using
inlinekeyword.Helps remove the overhead of function calls.
Best suited for small and frequently used functions.
Avoids stack memory usage for call/return.
Not recommended for large functions because code size may increase.
Member functions defined inside a class are automatically treated as inline.
Inline functions improve performance in tight loops.
Simple Example
inline int square(int x) {
return x * x;
}
cout << square(5); // compiler replaces call with (5 * 5)
I have attempted all the required questions with clear explanations, proper definitions, and relevant examples based on the concepts of Object Oriented Programming in C++. Each answer is written neatly and to the point, following the marking scheme. I hope the solutions reflect my understanding of the subject and meet the expectations of the examiner.
Thank you.