⚡ CCSU Meerut · BCA 3rd Semester · Exam Preparation
Object Oriented Programming with C++ BCA-301 Most Important Questions & Solved Exam Notebook
Master chapter-wise solved notebook of recurring CCSU examination questions (2017–2022) for Object Oriented Programming with C++ (BCA-301) with diamond problem virtual base class, vtable/vptr runtime polymorphism, operator overloading, file streams, templates, and vector SVG diagrams.
Very Short Answer Questions & Core OOP Concepts
CCSU Examination Blueprint: 5 Questions Compulsory • Total 15 Marks (75 Words Limit)
Q1. What is an Object and a Class? How do they relate to each other?
A Class is a user-defined blueprint or prototype that bundles data members (attributes) and member functions (behaviors) together into a single unit. It acts as a logical construct and consumes no physical memory when declared.
An Object is a real-world, concrete instance of a class. When an object is instantiated, the system allocates physical memory for all non-static data members defined in the class.
class Car is the architectural blueprint, then Car myCar; is the physical vehicle manufactured from that blueprint.
Q2. State the four fundamental pillars of Object-Oriented Programming (OOP).
- 1. Encapsulation: Binding data members and the functions that manipulate them into a single unit (class) while restricting direct outside access via private access specifiers.
- 2. Data Abstraction: Displaying only essential features and interface methods to the outside world while hiding underlying complex implementation details.
- 3. Inheritance: The mechanism by which a new class (derived class) inherits properties and behaviors from an existing class (base class), promoting code reusability and hierarchical classification.
- 4. Polymorphism: The ability of a message, function, or operator to take on multiple forms depending on the context (Compile-time via overloading; Run-time via virtual functions).
Q3. What is the Scope Resolution Operator (::)? State its three distinct uses in C++.
The Scope Resolution Operator (::) is used to explicitly qualify the scope of an identifier (variable, class, or namespace). Its three primary uses are:
- Accessing Global Variables: Accesses a hidden global variable when a local variable with the exact same identifier exists in current block:
cout << ::globalVar; - Defining Member Functions Outside Class: Connects a member function definition back to its enclosing class header:
void Student::display() { ... } - Resolving Namespace & Class Ambiguity: Accesses static members or nested classes:
std::coutorBaseClass::variable.
Q4. What is a Reference Variable in C++? Contrast it with a Pointer variable.
A Reference Variable provides an alternative alias (secondary name) for an existing variable. It is declared using the & symbol: int a = 10; int &ref = a;. Any operation performed on ref directly alters a because both share the exact same physical memory address.
| Feature | Reference Variable (&ref) |
Pointer Variable (*ptr) |
|---|---|---|
| Memory Address | Shares the same address as the target variable (no separate storage). | Holds the memory address of another variable in its own memory slot. |
| Initialization | Must be initialized at the time of declaration. Cannot be uninitialized. | Can be declared without initialization and initialized anytime later. |
| Reassignment & NULL | Cannot be reassigned to bind to another variable; cannot be NULL. |
Can point to different variables dynamically; can be NULL or nullptr. |
Q5. Differentiate between Dynamic Memory Allocation in C (malloc/free) and C++ (new/delete).
| Criteria | new / delete (C++) |
malloc() / free() (C) |
|---|---|---|
| Nature | Language operators (keywords). | Library runtime functions (<cstdlib>). |
| Constructor / Destructor | Automatically invokes class constructors on allocation and destructors on deallocation. | Allocates/frees raw uninitialized byte storage; never invokes constructors or destructors. |
| Return Type | Returns the exact typed pointer (e.g. int*, Node*). No typecasting required. |
Returns a generic void* pointer; explicit typecast is necessary in C++. |
| Size Calculation | Compiler automatically computes size: p = new int[10]; |
Programmer manually calculates bytes: p = (int*)malloc(10 * sizeof(int)); |
Q6. What is an Inline Function? Under what conditions does the C++ compiler ignore the inline request?
An Inline Function is defined using the inline keyword. When an inline function is invoked, the compiler replaces the function call with the actual body code of the function at compile-time, eliminating the runtime overhead of stack frame creation, parameter pushing, and return jumps.
Conditions where compiler ignores the inline request (treated as normal function):
- If the function contains loops (
for,while,do-while). - If the function contains
switchorgotostatements. - If the function is recursive (calls itself).
- If the function contains static local variables or its address is taken via a function pointer.
Q7. What are Default Arguments in C++? State the key rules for declaring them in function prototypes.
A Default Argument is a value assigned in the function prototype that is automatically used if the calling program omits the corresponding argument during the function invocation: float calcInterest(float p, int t, float r = 8.5);.
Fundamental Rules:
- Right-to-Left Trailing Rule: Default arguments must always be provided from right to left in the parameter list. A parameter cannot have a default value unless all parameters appearing to its right also have default values (e.g.
void func(int a, int b = 5, int c = 10);is valid, butvoid func(int a = 5, int b);is a syntax error). - Prototype Specification: Default values should be declared in the function declaration (prototype), not repeated in the definition.
Q8. Explain the visibility and access rules for private, protected, and public access specifiers.
private: Accessible only by member functions and declared friend functions of the same class. Completely hidden from derived classes and outside object access. (Default visibility in classes).protected: Inaccessible to outside object scopes (acts private to outside world), but accessible directly by derived/child classes during inheritance.public: Accessible from any part of the program where the object is in scope. Forms the public interface of the class.
Q9. What is a Destructor? State three essential characteristics of a destructor in C++.
A Destructor is a special member function that is automatically executed when an object goes out of scope or is explicitly deleted via delete. Its primary role is deallocating dynamic heap memory, closing file handles, and releasing system resources.
Three Key Characteristics:
- Its name is preceded by a tilde (
~) and matches the exact class name:~ClassName();. - It takes no arguments and returns no value (not even
void). - Because it accepts no arguments, a destructor cannot be overloaded; there can only be exactly one destructor per class.
Q10. What is a Copy Constructor? When is it implicitly invoked by the C++ compiler?
A Copy Constructor is an overloaded constructor used to initialize a new object using an existing object of the exact same class. Its declaration syntax uses a constant reference: ClassName(const ClassName &source);.
It is automatically invoked in three specific scenarios:
- When an object is initialized from another existing object at creation:
Student s2 = s1;orStudent s2(s1);. - When an object is passed to a function by value:
void process(Student s);. - When an object is returned from a function by value:
Student createStudent() { ... return s; }.
Q11. Explain the purpose and role of the this pointer in C++ with a short syntax example.
The this pointer is an implicit, hidden constant pointer automatically passed into all non-static member functions. It holds the physical memory address of the invoking object (the object upon which the member function was called).
Primary Use Cases:
- Resolving Identifier Shadowing: Differentiates between member variables and parameter variables sharing identical names:
void setDimensions(int length, int width) { this->length = length; // this->length is member, length is parameter this->width = width; } - Method Chaining: Returning the current object reference to allow chained calls:
return *this;.
Q12. Which operators cannot be overloaded in C++? State the technical reason why.
The following five operators cannot be overloaded in C++:
.(Class member access / dot operator).*(Pointer-to-member operator)::(Scope resolution operator)?:(Conditional / ternary operator)sizeof(Size-of operator)
.) could be overloaded, the compiler would lose the guaranteed syntactic mechanism to access members of an object, creating syntactic ambiguity in basic language operations.
Q13. What is a Pure Virtual Function and an Abstract Base Class? Give syntax.
A Pure Virtual Function is a virtual function that has no definition in the base class and is equated to zero in its declaration: virtual void draw() = 0;. It acts as a mandatory contract forcing derived classes to provide their own implementation.
An Abstract Base Class is any class containing at least one pure virtual function. Abstract classes cannot be instantiated directly (i.e. Shape s; produces a compiler error), but pointers and references of abstract class types can be created to achieve runtime polymorphism.
Q14. Differentiate between Early Binding (Static Binding) and Late Binding (Dynamic Binding).
| Feature | Early Binding (Static Binding) | Late Binding (Dynamic Binding) |
|---|---|---|
| Resolution Time | Resolved by the compiler at compile-time. | Resolved by the runtime engine during program execution. |
| Mechanism | Matches function name and parameters directly based on pointer/reference type. | Uses the Virtual Table (vtable) and Virtual Pointer (vptr) based on actual pointed-to object. |
| Speed | Extremely fast; zero runtime pointer indirection overhead. | Slight runtime overhead due to vtable lookup indirection. |
| Examples | Normal member functions, function overloading, operator overloading. | Virtual functions invoked via base class pointers or references. |
Q15. Why should a Base Class Destructor always be declared as virtual?
When a derived class object is deleted through a base class pointer (e.g. Base *b = new Derived(); delete b;):
- If Base destructor is NOT virtual: The compiler performs early binding and invokes only the Base destructor. The Derived class destructor is completely skipped, causing memory leaks if the derived class allocated dynamic heap memory.
- If Base destructor is declared
virtual ~Base();: Late binding ensures that the Derived destructor executes first, freeing derived resources, followed automatically by the Base destructor.
Q16. Differentiate between File Opening Modes ios::app (append) and ios::ate (at-end).
| Mode | Initial File Pointer Position | Repositioning Capability | Writing Behavior |
|---|---|---|---|
ios::app (Append) |
End of file (EOF). | Locked: File write pointer cannot be moved to any other location using seekp(). |
All output operations are strictly appended to the very end of the file. |
ios::ate (At End) |
End of file (EOF). | Flexible: File pointer can be freely repositioned anywhere (to beginning or middle) using seekg() or seekp(). |
Allows reading and writing anywhere in the file after moving the pointer. |
Q17. What are C++ Stream Manipulators? Explain setw() and setprecision() from <iomanip>.
Manipulators are special formatting helper functions used with the insertion (<<) and extraction (>>) operators to format data display on output streams. Defined in header <iomanip>.
setw(int n): Sets the field width for the immediately succeeding output value toncharacters (right-aligned by default). It affects only the next output item.cout << setw(10) << 123; // Displays " 123"setprecision(int n): Sets the floating-point precision tondigits. When combined withfixed, it fixes the exact number of decimal places:cout << fixed << setprecision(2) << 3.14159; // Displays "3.14"
Q18. Differentiate between Function Overloading (Compile-Time) and Function Overriding (Run-Time).
| Criteria | Function Overloading | Function Overriding |
|---|---|---|
| Scope | Occurs within the same class scope. | Occurs across base and derived classes in an inheritance hierarchy. |
| Signature | Function names are identical, but parameter list must differ (in count, types, or order). | Function name, parameters, and return type must be strictly identical. |
| Polymorphism Type | Compile-time (Static binding). | Run-time (Dynamic binding via virtual keyword). |
| Keyword Requirement | No special keyword required. | Requires virtual in the base class. |
Core Analytical Concepts, Working Programs & Design Patterns
CCSU Examination Blueprint: Attempt Any 2 of 3 Questions • Total 15 Marks (~200 Words + Working Code)
Q1. Differentiate between Procedure Oriented Programming (POP) and Object Oriented Programming (OOP) in detail with a structured comparison matrix.
In traditional Procedure Oriented Programming (POP), the problem is viewed as a sequence of procedural steps or functions that execute actions on data. In contrast, Object Oriented Programming (OOP) models programs around discrete real-world entities called objects that encapsulate both data and the operations that act upon that data.
| Comparison Parameter | Procedure Oriented Programming (POP) | Object Oriented Programming (OOP) |
|---|---|---|
| Primary Focus | Focuses on algorithms, step-by-step procedures, and doing things (functions). | Focuses on the data being operated upon and binding it to behaviors (objects). |
| Program Decomposition | Program is divided into small modular blocks called functions. | Program is divided into self-contained entities called classes and objects. |
| Design Approach | Top-Down Approach: High-level problem broken sequentially down into smaller functions. | Bottom-Up Approach: Lower-level objects designed first and assembled to form the application. |
| Data Security & Access | Global data flows freely between functions; data is vulnerable to unintended modification. | Data is hidden via private access specifiers; accessible only through member functions (Data Hiding). |
| Inheritance & Reuse | No built-in inheritance mechanism. Code reuse requires copying or library functions. | Robust Inheritance enables derived classes to reuse and extend base class code seamlessly. |
| Polymorphism | Not supported. Every function must possess a unique identifier name. | Supported via Function Overloading, Operator Overloading, and Virtual Functions. |
| Memory Management | Manual byte-based allocation via malloc() and free(). |
Typed allocation via new and delete with automated constructor/destructor lifecycle. |
| Standard Examples | C, Pascal, FORTRAN, BASIC. | C++, Java, C#, Python, Smalltalk. |
Q2. Explain Static Data Members and Static Member Functions with a complete C++ program demonstrating shared class-level state.
Normally, each object receives its own independent copy of all data members. However, a Static Data Member is shared among all objects of that class. Only a single copy exists in memory throughout the lifetime of the program.
Key Rules:
- Static data members are initialized to
0by default and must be defined outside the class using the scope resolution operator (::). - A Static Member Function can only access static data members and static functions of the class. It does not possess a
thispointer and can be invoked directly using the class name without creating an object:ClassName::staticFunction();.
#include <iostream>
using namespace std;
class UserTracker {
private:
int userId;
static int activeCount; // Static data member declaration
public:
UserTracker(int id) {
userId = id;
activeCount++;
cout << "User #" << userId << " created. Active: " << activeCount << endl;
}
~UserTracker() {
activeCount--;
cout << "User #" << userId << " destroyed. Active: " << activeCount << endl;
}
// Static member function
static void displayActiveUsers() {
cout << "--- Total Active Users Currently: " << activeCount << " ---" << endl;
}
};
// Definition and memory allocation outside class
int UserTracker::activeCount = 0;
int main() {
UserTracker::displayActiveUsers(); // Invocation without object
UserTracker u1(101);
UserTracker u2(102);
UserTracker::displayActiveUsers();
{
UserTracker u3(103); // Local block scope
UserTracker::displayActiveUsers();
} // u3 destroyed here
UserTracker::displayActiveUsers();
return 0;
}
Q3. What is a Friend Function? Write a complete C++ program to find the maximum of two private numbers belonging to two distinct classes.
A Friend Function is a non-member function granted special permission to access the private and protected members of a class. It is declared inside the class using the keyword friend.
Characteristics: It is not in the scope of the class, cannot be called using the member access dot operator (obj.friendFunc()), and usually accepts objects of the classes as value or reference arguments.
#include <iostream>
using namespace std;
// Forward declaration of class Beta
class Beta;
class Alpha {
private:
int valA;
public:
Alpha(int a) : valA(a) {}
// Declaring external function as friend
friend void findMax(Alpha a, Beta b);
};
class Beta {
private:
int valB;
public:
Beta(int b) : valB(b) {}
// Declaring the same function as friend
friend void findMax(Alpha a, Beta b);
};
// Non-member friend function definition bridging both classes
void findMax(Alpha a, Beta b) {
cout << "Alpha Value = " << a.valA << ", Beta Value = " << b.valB << endl;
if (a.valA > b.valB) {
cout << "Maximum Value is in Alpha: " << a.valA << endl;
} else if (b.valB > a.valA) {
cout << "Maximum Value is in Beta: " << b.valB << endl;
} else {
cout << "Both values are equal: " << a.valA << endl;
}
}
int main() {
Alpha objA(85);
Beta objB(120);
findMax(objA, objB); // Invoked like a standard global function
return 0;
}
Q4. Explain Constructor Overloading. Demonstrate Default, Parameterized, and Copy Constructors in a single class Rectangle.
Constructor Overloading is the concept of defining multiple constructors in the same class, each having the same name (the class name) but differing in the number, types, or order of their arguments. The compiler automatically resolves which constructor to invoke based on the arguments supplied at instantiation.
#include <iostream>
using namespace std;
class Rectangle {
private:
double length;
double breadth;
public:
// 1. Default Constructor: Initializes default state
Rectangle() {
length = 0.0;
breadth = 0.0;
cout << "Default Constructor Invoked (0x0)" << endl;
}
// 2. Parameterized Constructor: Custom dimensions
Rectangle(double l, double b) {
length = l;
breadth = b;
cout << "Parameterized Constructor Invoked (" << l << "x" << b << ")" << endl;
}
// 3. Copy Constructor: Initializes from an existing Rectangle
Rectangle(const Rectangle &r) {
length = r.length;
breadth = r.breadth;
cout << "Copy Constructor Invoked (Cloned)" << endl;
}
double calculateArea() const {
return length * breadth;
}
};
int main() {
Rectangle r1; // Calls Default Constructor
Rectangle r2(12.5, 8.0); // Calls Parameterized Constructor
Rectangle r3 = r2; // Calls Copy Constructor
cout << "Area of r1: " << r1.calculateArea() << endl;
cout << "Area of r2: " << r2.calculateArea() << endl;
cout << "Area of r3: " << r3.calculateArea() << endl;
return 0;
}
Q5. Explain Shallow Copy vs Deep Copy in C++ with dynamic memory allocation, illustrating why a custom copy constructor is necessary.
When an object contains raw pointers to dynamic heap memory, the difference between shallow and deep copy is critical:
- Shallow Copy (Default): The compiler copies member variables bit-by-bit. If the class has a pointer
int *ptr, both objects end up pointing to the exact same heap memory address. When the first object is destroyed, its destructor frees the memory. When the second object is later destroyed, it attempts to free the already-freed pointer, causing an undefined behavior double-free crash. - Deep Copy (Custom Copy Constructor): Allocates a brand-new, separate heap memory block for the new object and copies the actual values from the source buffer. Each object manages its own distinct memory.
#include <iostream>
using namespace std;
class DeepBuffer {
private:
int *data;
int size;
public:
DeepBuffer(int sz, int val) {
size = sz;
data = new int[size];
for (int i = 0; i < size; i++) data[i] = val;
}
// User-Defined Deep Copy Constructor
DeepBuffer(const DeepBuffer &src) {
size = src.size;
data = new int[size]; // Separate heap buffer allocation
for (int i = 0; i < size; i++) {
data[i] = src.data[i]; // Copy buffer values
}
}
~DeepBuffer() {
delete[] data; // Safe: each object deletes its own buffer
}
void modify(int index, int val) { data[index] = val; }
void print() const {
for (int i = 0; i < size; i++) cout << data[i] << " ";
cout << endl;
}
};
int main() {
DeepBuffer b1(3, 10);
DeepBuffer b2 = b1; // Deep copy executed safely
b2.modify(0, 99); // Only b2 changes; b1 remains unaffected
cout << "Buffer 1: "; b1.print(); // 10 10 10
cout << "Buffer 2: "; b2.print(); // 99 10 10
return 0;
}
Q6. Write a complete C++ program to overload the unary increment operator (++) in both prefix (++c) and postfix (c++) forms for a Counter class.
In C++, the compiler distinguishes between prefix and postfix unary operator overloading through the parameter signature:
- Prefix (
++obj): Declared asCounter operator++()with no arguments. Increments the state and returns the updated object. - Postfix (
obj++): Declared with a dummy integer parameter:Counter operator++(int). Stores the original state in a temporary object, increments the current object, and returns the temporary copy.
#include <iostream>
using namespace std;
class Counter {
private:
int count;
public:
Counter(int c = 0) : count(c) {}
// Overloading Prefix Increment (++c)
Counter operator++() {
++count; // Increment first
return *this; // Return updated object
}
// Overloading Postfix Increment (c++) with dummy int
Counter operator++(int) {
Counter temp = *this; // Save original state
count++; // Increment current object
return temp; // Return original state
}
void display() const {
cout << "Count = " << count << endl;
}
};
int main() {
Counter c1(5);
cout << "Initial: "; c1.display();
Counter c2 = ++c1; // Prefix: c1 increments to 6, c2 receives 6
cout << "After ++c1: "; c1.display();
cout << "Value in c2: "; c2.display();
Counter c3 = c1++; // Postfix: c3 receives 6, c1 increments to 7
cout << "After c1++: "; c1.display();
cout << "Value in c3: "; c3.display();
return 0;
}
Q7. Write a C++ program using an Array of Objects for an Employee class to accept records of 5 employees and display the details of the highest-paid employee.
An Array of Objects allows managing collections of complex structured instances where each element occupies contiguous memory and encapsulates its own data members and member functions.
#include <iostream>
#include <string>
using namespace std;
class Employee {
private:
int empId;
string name;
double salary;
public:
void inputData(int id, string n, double s) {
empId = id;
name = n;
salary = s;
}
double getSalary() const { return salary; }
void display() const {
cout << "ID: " << empId << " | Name: " << name << " | Salary: Rs. " << salary << endl;
}
};
int main() {
const int NUM = 5;
Employee staff[NUM];
// Populating array of objects
staff[0].inputData(101, "Vikram Sharma", 48000.0);
staff[1].inputData(102, "Pooja Verma", 72500.0);
staff[2].inputData(103, "Amit Malik", 54000.0);
staff[3].inputData(104, "Neha Gupta", 89000.0);
staff[4].inputData(105, "Rajesh Kumar", 61000.0);
cout << "=== All Employee Records ===" << endl;
for (int i = 0; i < NUM; i++) {
staff[i].display();
}
// Finding highest salaried employee
int maxIndex = 0;
for (int i = 1; i < NUM; i++) {
if (staff[i].getSalary() > staff[maxIndex].getSalary()) {
maxIndex = i;
}
}
cout << "\n*** Highest Salaried Employee ***" << endl;
staff[maxIndex].display();
return 0;
}
Q8. Explain Function Templates vs Preprocessor Macros. Write a function template to swap two variables of any data type (int, float, char).
A Function Template is a generic blueprint from which the C++ compiler automatically generates type-specific functions during compilation (template instantiation). Unlike preprocessor macros (#define), templates provide strict type-checking, adhere to proper scoping rules, and do not cause macro side-effects (such as double-evaluation of ++x).
#include <iostream>
using namespace std;
// Generic Swap Function Template
template <typename T>
void swapValues(T &a, T &b) {
T temp = a;
a = b;
b = temp;
}
int main() {
// 1. Swapping integers
int x = 10, y = 20;
cout << "Before int swap: x=" << x << ", y=" << y << endl;
swapValues(x, y); // Compiler instantiates swapValues<int>
cout << "After int swap: x=" << x << ", y=" << y << endl;
// 2. Swapping floats
float f1 = 3.14f, f2 = 9.81f;
swapValues(f1, f2); // Instantiates swapValues<float>
cout << "After float swap: f1=" << f1 << ", f2=" << f2 << endl;
// 3. Swapping characters
char c1 = 'A', c2 = 'Z';
swapValues(c1, c2); // Instantiates swapValues<char>
cout << "After char swap: c1=" << c1 << ", c2=" << c2 << endl;
return 0;
}
Q9. Write a complete C++ program demonstrating Exception Handling with try, catch, and throw blocks for divide-by-zero, including multiple catch handlers and a catch-all block.
C++ Exception handling transfers control from a point where an anomaly occurs to a designated handler using three keywords: try (monitored code), throw (raises exception), and catch (handles exception).
#include <iostream>
using namespace std;
void safeDivide(double num, double den) {
if (den == 0.0) {
throw "Arithmetic Error: Division by zero is undefined!"; // Throw const char*
} else if (den < 0.0) {
throw -1; // Throw int error code for negative denominator
}
cout << "Result: " << num << " / " << den << " = " << (num / den) << endl;
}
int main() {
double pairs[3][2] = { {50.0, 5.0}, {20.0, 0.0}, {40.0, -4.0} };
for (int i = 0; i < 3; i++) {
try {
cout << "\nEvaluating test case #" << (i + 1) << ":" << endl;
safeDivide(pairs[i][0], pairs[i][1]);
}
catch (const char* msg) { // Handler 1: String literal
cout << "[Caught String Exception] " << msg << endl;
}
catch (int code) { // Handler 2: Integer error code
cout << "[Caught Integer Exception] Error Code: " << code
<< " (Negative divisor rejected)" << endl;
}
catch (...) { // Handler 3: Catch-All fallback
cout << "[Caught Unknown Exception] Generic error caught!" << endl;
}
}
return 0;
}
Q10. Explain File Pointers and Random Access Functions (seekg(), seekp(), tellg(), tellp()) with stream seek offsets.
In C++ file handling, every file stream maintains two internal byte pointers: the Get Pointer (associated with input stream ifstream to track the next byte to read) and the Put Pointer (associated with output stream ofstream to track the next byte to write).
| Function | Stream Association | Operation |
|---|---|---|
tellg() |
Input Stream (ifstream) |
Returns the current byte position of the Get pointer. |
seekg(offset, dir) |
Input Stream (ifstream) |
Moves the Get pointer by offset bytes relative to dir. |
tellp() |
Output Stream (ofstream) |
Returns the current byte position of the Put pointer. |
seekp(offset, dir) |
Output Stream (ofstream) |
Moves the Put pointer by offset bytes relative to dir. |
Seek Direction Flags (dir):
ios::beg: Beginning of the file.ios::cur: Current position of the file pointer.ios::end: End of the file. (Example:file.seekg(0, ios::end); int size = file.tellg();computes the exact byte size of a file).
Master Long Answer Questions, Architectural Blueprints & SVG Diagrams
CCSU Examination Blueprint: Attempt Any 3 of 5 Questions • Total 45 Marks (~500+ Words + Working Code + Diagrams)
Q1. Explain the Object-Oriented Programming (OOP) paradigm in detail. Discuss its core principles (Encapsulation, Abstraction, Inheritance, and Polymorphism) and illustrate how OOP addresses the limitations of Procedural Programming.
1. Limitations of Procedure Oriented Programming (POP)
In procedural languages like C, programs are organized around linear functions operating on global and local data. Major limitations include:
- Data Insecurity: Global variables are freely accessible and modifiable by any function in the program, making debugging complex in large systems.
- Tight Coupling: Changes to data structures necessitate modifications to all functions interacting with that data.
- Poor Real-World Modeling: Real-world entities inherently possess state (data) and behavior (operations), which procedural decomposition separates unnaturally.
- Code Duplication: Lack of inheritance forces programmers to rewrite common logic repeatedly.
2. The Four Pillars of OOP Architecture
3. Dynamic Binding and Message Passing
- Dynamic Binding: Linking a procedure call to the specific code block to be executed at runtime (based on the real object type rather than the pointer type).
- Message Passing: Objects communicate by sending and receiving information via function invocations:
employee.calculateBonus(2024);whereemployeeis the object receiver,calculateBonusis the message, and2024is the argument data.
Q2. What is Operator Overloading? State the fundamental rules and limitations of operator overloading in C++. Write a complete C++ program to overload binary addition (+), subtraction (-), and stream operators (<< and >>) for a Complex number class.
1. Concept & Strict Rules of Operator Overloading
Operator Overloading is the compile-time polymorphism feature in C++ that allows existing built-in operators to be redefined to operate on user-defined types (classes), imparting natural mathematical syntax.
Universal Rules:
- Only existing C++ operators can be overloaded. New operators (such as
**or%%) cannot be invented. - The precedence, associativity, and arity (number of operands) of the operator cannot be changed.
- At least one of the operands must be a user-defined class type. Built-in types (e.g.
int + int) cannot be rewired. - Cannot overload:
.(member access),.*(pointer-to-member),::(scope resolution),?:(ternary conditional), andsizeof. - When overloading binary operators via member functions, the left operand implicitly becomes the calling object (
*this), requiring exactly 1 explicit argument. When overloaded via friend functions, 2 explicit arguments are required.
2. Complete Compilable C++ Implementation
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
// Constructors
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// Overloading Binary + using Member Function
Complex operator+(const Complex &c) const {
return Complex(real + c.real, imag + c.imag);
}
// Overloading Binary - using Member Function
Complex operator-(const Complex &c) const {
return Complex(real - c.real, imag - c.imag);
}
// Overloading Relational == Operator
bool operator==(const Complex &c) const {
return (real == c.real && imag == c.imag);
}
// Overloading Stream Insertion Operator (<<) via Friend Function
friend ostream& operator<<(ostream &out, const Complex &c) {
if (c.imag >= 0)
out << c.real << " + " << c.imag << "i";
else
out << c.real << " - " << (-c.imag) << "i";
return out; // Enables cascaded output: cout << c1 << c2;
}
// Overloading Stream Extraction Operator (>>) via Friend Function
friend istream& operator>>(istream &in, Complex &c) {
cout << "Enter Real Part: ";
in >> c.real;
cout << "Enter Imaginary Part: ";
in >> c.imag;
return in;
}
};
int main() {
Complex c1(4.5, 3.2);
Complex c2(1.5, -5.7);
cout << "c1 = " << c1 << endl;
cout << "c2 = " << c2 << endl;
Complex cSum = c1 + c2; // Invokes c1.operator+(c2)
cout << "c1 + c2 = " << cSum << endl;
Complex cDiff = c1 - c2; // Invokes c1.operator-(c2)
cout << "c1 - c2 = " << cDiff << endl;
if (c1 == c2) {
cout << "c1 and c2 are identical" << endl;
} else {
cout << "c1 and c2 are different complex numbers" << endl;
}
return 0;
}
Q3. Explain the five forms of inheritance supported in C++ with UML diagrams. Construct the complete Access Specifier Derivation Matrix (public, protected, private) and explain why protected inheritance is utilized.
1. Complete UML Inheritance Taxonomy
2. Access Specifier Derivation Matrix
| Base Class Member Access | public Derivation |
protected Derivation |
private Derivation |
|---|---|---|---|
private Members |
Inaccessible directly in Derived | Inaccessible directly in Derived | Inaccessible directly in Derived |
protected Members |
Remains protected |
Remains protected |
Becomes private in Derived |
public Members |
Remains public |
Becomes protected |
Becomes private in Derived |
Q4. What is the "Diamond Problem" (Multipath Inheritance) in C++? Why does it cause compilation errors? Explain how Virtual Base Classes solve this ambiguity and provide a complete working C++ program.
1. Nature of the Ambiguity
The Diamond Problem occurs in hybrid / multipath inheritance when a derived class D inherits from two intermediate classes B and C, both of which in turn inherit from a common ancestor base class A.
The Compilation Error: By default, class B receives one full copy of class A's data members, and class C receives another completely separate copy. When class D inherits from both B and C, it inherits two duplicate copies of class A's members. When code in D calls rollNumber or display(), the compiler halts with error: error: request for member 'rollNumber' is ambiguous.
2. Architectural Comparison: Duplication vs Virtual Base Class
3. Complete Compilable Solution Code
#include <iostream>
using namespace std;
// Base Ancestor Class
class Student {
protected:
int rollNumber;
public:
void setRoll(int r) { rollNumber = r; }
void printRoll() const { cout << "Roll Number: " << rollNumber << endl; }
};
// Intermediate Class 1: Virtual Inheritance
class Test : virtual public Student {
protected:
float part1, part2;
public:
void setMarks(float m1, float m2) { part1 = m1; part2 = m2; }
void printMarks() const {
cout << "Marks Obtained: Term1 = " << part1 << ", Term2 = " << part2 << endl;
}
};
// Intermediate Class 2: Virtual Inheritance
class Sports : virtual public Student {
protected:
float score;
public:
void setScore(float s) { score = s; }
void printScore() const { cout << "Sports Grace Score = " << score << endl; }
};
// Derived Leaf Class inheriting from both Test and Sports
class Result : public Test, public Sports {
private:
float grandTotal;
public:
void displayResult() {
grandTotal = part1 + part2 + score;
printRoll(); // Zero Ambiguity! Calls single shared Student subobject
printMarks();
printScore();
cout << "--------------------------------" << endl;
cout << "Grand Total Score = " << grandTotal << " / 200.0" << endl;
}
};
int main() {
Result studentResult;
studentResult.setRoll(210834); // Direct call without ambiguity
studentResult.setMarks(78.5f, 84.0f);
studentResult.setScore(15.0f);
cout << "=== Official CCSU Student Academic Record ===" << endl;
studentResult.displayResult();
return 0;
}
Q5. What are Virtual Functions and Pure Virtual Functions? Explain the concept of Dynamic Binding with a complete C++ program modeling an abstract base class Shape with derived classes Circle, Rectangle, and Triangle.
1. Pure Virtual Functions and Abstract Base Classes
A function declared with virtual in a base class and assigned = 0 is a Pure Virtual Function. It has no implementation in the base class and mandates every derived class to override it. A class containing at least one pure virtual function is an Abstract Class.
2. Dynamic Dispatch Architecture Diagram
3. Complete Compilable Program
#include <iostream>
#include <cmath>
using namespace std;
// Abstract Base Class
class Shape {
public:
virtual double area() const = 0; // Pure virtual function
virtual void display() const = 0; // Pure virtual function
virtual ~Shape() { cout << "Shape Base Destructor" << endl; }
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override { return 3.14159265 * radius * radius; }
void display() const override {
cout << "Circle (r=" << radius << ") -> Area = " << area() << endl;
}
~Circle() override { cout << "Circle Destructor" << endl; }
};
class Rectangle : public Shape {
private:
double length, breadth;
public:
Rectangle(double l, double b) : length(l), breadth(b) {}
double area() const override { return length * breadth; }
void display() const override {
cout << "Rectangle (" << length << "x" << breadth << ") -> Area = " << area() << endl;
}
~Rectangle() override { cout << "Rectangle Destructor" << endl; }
};
class Triangle : public Shape {
private:
double base, height;
public:
Triangle(double b, double h) : base(b), height(h) {}
double area() const override { return 0.5 * base * height; }
void display() const override {
cout << "Triangle (b=" << base << ", h=" << height << ") -> Area = " << area() << endl;
}
~Triangle() override { cout << "Triangle Destructor" << endl; }
};
int main() {
// Array of Base Class Pointers holding diverse derived objects
Shape* shapes[3];
shapes[0] = new Circle(7.0);
shapes[1] = new Rectangle(10.0, 5.0);
shapes[2] = new Triangle(8.0, 12.0);
cout << "=== Polymorphic Dynamic Dispatch Loop ===" << endl;
for (int i = 0; i < 3; i++) {
shapes[i]->display(); // Runtime Late Binding via vtable!
}
// Safe deletion triggering virtual destructors in reverse order
for (int i = 0; i < 3; i++) {
delete shapes[i];
}
return 0;
}
Q6. Explain the internal compiler mechanism of Virtual Functions using Virtual Table (vtable) and Virtual Pointer (vptr). Draw detailed memory layouts demonstrating how dynamic dispatch executes.
1. How the C++ Compiler Implements Dynamic Binding
Dynamic polymorphism does not happen by magic; the C++ compiler injects two low-level components into the program:
- 1. Virtual Table (
vtable): For every class that declares or inherits virtual functions, the compiler generates a static lookup table stored in the Read-Only Data Segment (.rodata). The table is an array of function pointers storing the addresses of the virtual functions belonging to that specific class. Exactly one vtable exists per class. - 2. Virtual Table Pointer (
vptr): For every object of a class containing virtual functions, the compiler injects an internal hidden pointer (usually at offset0). When the object constructor executes, it initializesvptrto point to its class's specificvtable.
2. Detailed Memory Architecture Diagram
3. Step-by-Step Execution Sequence for bPtr->functionOne()
- CPU dereferences
bPtrto fetch the object located in heap memory. - CPU extracts the
vptrstored at offset0of the object. - CPU indexes into the pointed-to
vtableat slot[0]. - CPU retrieves function pointer
&Derived::functionOneand jumps directly to that memory instruction address.
Q7. Explain the concept of Friend Functions and Friend Classes. Why does C++ support friend functions despite the principle of Data Encapsulation? Illustrate with an architectural SVG diagram and a complete program analyzing accounts across two distinct banking classes.
1. Purpose & Pragmatism of Friend Functions
While Data Encapsulation enforces that private data can only be manipulated by member functions of its own class, practical real-world operations frequently require coordinated actions across two unrelated classes (such as matrix multiplication between two different dimension classes, or joint financial auditing across distinct account types).
A Friend Function is an external non-member function granted authorized access to private and protected members of a class. The class maintains control because friendship is granted by the class itself through the friend keyword in its declaration.
- Friendship is NOT Mutual: If Class A is a friend of Class B, Class B is not automatically a friend of Class A.
- Friendship is NOT Inherited: A friend of a base class does not become a friend of its derived classes.
- Friendship is NOT Transitive: If A is a friend of B, and B is a friend of C, A is not a friend of C.
2. Friend Function Cross-Class Bridge Architecture
3. Complete Compilable Solution
#include <iostream>
#include <string>
using namespace std;
// Forward declaration of CurrentAccount
class CurrentAccount;
class SavingsAccount {
private:
string accountNo;
double balance;
public:
SavingsAccount(string acc, double bal) : accountNo(acc), balance(bal) {}
// Declaring friend function
friend void auditPortfolio(const SavingsAccount &sa, const CurrentAccount &ca);
};
class CurrentAccount {
private:
string accountNo;
double balance;
public:
CurrentAccount(string acc, double bal) : accountNo(acc), balance(bal) {}
// Declaring the exact same friend function
friend void auditPortfolio(const SavingsAccount &sa, const CurrentAccount &ca);
};
// Global friend function accessing private members of both classes
void auditPortfolio(const SavingsAccount &sa, const CurrentAccount &ca) {
cout << "--- Financial Audit Report ---" << endl;
cout << "Savings Account [" << sa.accountNo << "] Balance : Rs. " << sa.balance << endl;
cout << "Current Account [" << ca.accountNo << "] Balance : Rs. " << ca.balance << endl;
double combinedTotal = sa.balance + ca.balance;
cout << "Combined Net Liquidity : Rs. " << combinedTotal << endl;
if (combinedTotal >= 100000.0) {
cout << "Credit Assessment : APPROVED for Premium Commercial Credit Line" << endl;
} else {
cout << "Credit Assessment : Standard Banking Tier" << endl;
}
}
int main() {
SavingsAccount personal("SB-9921", 64500.0);
CurrentAccount business("CA-4108", 85000.0);
auditPortfolio(personal, business);
return 0;
}
Q8. Explain the order of Constructor and Destructor invocation in Multiple and Multilevel Inheritance. How are arguments passed to base class constructors from a derived class constructor? Provide full traceable code.
1. Universal Constructor & Destructor Order Rules
| Phase | Order of Execution | Underlying Reason |
|---|---|---|
| Constructor Phase (Initialization) | Top-Down (Base to Derived): 1. Virtual Base class constructors first. 2. Non-virtual base constructors in order of declaration: class D : public B1, public B2.3. Member object constructors. 4. Derived class constructor body last. |
A derived class depends on inherited state; hence the foundation (base) must exist before derived extensions can be initialized. |
| Destructor Phase (Destruction) | Bottom-Up (Exact Reverse): 1. Derived class destructor body first. 2. Member object destructors. 3. Non-virtual base destructors in reverse declaration order. 4. Virtual base destructors last. |
Prevents derived teardown code from referencing base resources after they have already been released. |
2. Complete Traceable Code
#include <iostream>
using namespace std;
class BaseOne {
protected:
int val1;
public:
BaseOne(int v1) : val1(v1) {
cout << "[1] BaseOne Parameterized Constructor (val1 = " << val1 << ")" << endl;
}
virtual ~BaseOne() {
cout << "[~1] BaseOne Destructor Executed" << endl;
}
};
class BaseTwo {
protected:
int val2;
public:
BaseTwo(int v2) : val2(v2) {
cout << "[2] BaseTwo Parameterized Constructor (val2 = " << val2 << ")" << endl;
}
virtual ~BaseTwo() {
cout << "[~2] BaseTwo Destructor Executed" << endl;
}
};
// Derived from BaseOne first, then BaseTwo
class DerivedComposite : public BaseOne, public BaseTwo {
private:
int derivedVal;
public:
// Base constructor initialization list passing arguments
DerivedComposite(int a, int b, int c) : BaseOne(a), BaseTwo(b), derivedVal(c) {
cout << "[3] DerivedComposite Constructor (derivedVal = " << derivedVal << ")" << endl;
}
~DerivedComposite() override {
cout << "[~3] DerivedComposite Destructor Executed" << endl;
}
void displayAll() const {
cout << "State: val1=" << val1 << ", val2=" << val2 << ", derivedVal=" << derivedVal << endl;
}
};
int main() {
cout << "--- Creating DerivedComposite Object ---" << endl;
DerivedComposite* obj = new DerivedComposite(10, 20, 30);
obj->displayAll();
cout << "\n--- Destroying DerivedComposite Object ---" << endl;
delete obj; // Notice the exact reverse sequence in console output
return 0;
}
Q9. Explain the C++ Stream Class Hierarchy with a clean architectural SVG diagram. Write a complete, compilable C++ program implementing a Bank Account binary file management system capable of adding records, displaying all records, searching by account number, and updating balances in-place.
1. C++ Stream Class Hierarchy Architecture
2. Complete Binary File Management Program
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
class BankAccount {
private:
int accountNo;
char holderName[30];
double balance;
public:
BankAccount() : accountNo(0), balance(0.0) { holderName[0] = '\0'; }
BankAccount(int acc, const char* name, double bal) {
accountNo = acc;
strncpy(holderName, name, 29);
holderName[29] = '\0';
balance = bal;
}
int getAccountNo() const { return accountNo; }
void updateBalance(double newBal) { balance = newBal; }
void display() const {
cout << "Acc #" << accountNo << " | Holder: " << holderName
<< " | Balance: Rs. " << balance << endl;
}
};
// 1. Add Record using write()
void addAccount(const char* filename, const BankAccount &acc) {
ofstream outFile(filename, ios::binary | ios::app);
outFile.write(reinterpret_cast<const char*>(&acc), sizeof(BankAccount));
outFile.close();
}
// 2. Read and Display All Records using read()
void displayAllAccounts(const char* filename) {
ifstream inFile(filename, ios::binary);
if (!inFile) {
cout << "File could not be opened!" << endl;
return;
}
BankAccount acc;
cout << "\n--- Registered Bank Accounts in Database ---" << endl;
while (inFile.read(reinterpret_cast<char*>(&acc), sizeof(BankAccount))) {
acc.display();
}
inFile.close();
}
// 3. Search and In-Place Modify Record using seekp()
bool modifyBalance(const char* filename, int searchAccNo, double newBalance) {
fstream file(filename, ios::binary | ios::in | ios::out);
if (!file) return false;
BankAccount acc;
bool found = false;
while (file.read(reinterpret_cast<char*>(&acc), sizeof(BankAccount))) {
if (acc.getAccountNo() == searchAccNo) {
acc.updateBalance(newBalance);
// Move write pointer back by sizeof(BankAccount) bytes
file.seekp(-static_cast<int>(sizeof(BankAccount)), ios::cur);
file.write(reinterpret_cast<const char*>(&acc), sizeof(BankAccount));
found = true;
break;
}
}
file.close();
return found;
}
int main() {
const char* dbFile = "accounts.dat";
// Adding initial seed records
addAccount(dbFile, BankAccount(1001, "Aarav Sharma", 45000.0));
addAccount(dbFile, BankAccount(1002, "Sneha Patel", 82000.0));
addAccount(dbFile, BankAccount(1003, "Rohan Verma", 19500.0));
displayAllAccounts(dbFile);
// Modifying Sneha Patel's balance in-place
cout << "\nUpdating Account 1002 balance to Rs. 95000.0..." << endl;
if (modifyBalance(dbFile, 1002, 95000.0)) {
cout << "Record successfully updated in binary file!" << endl;
}
displayAllAccounts(dbFile);
return 0;
}
Q10. Explain Generic Programming and Class Templates in C++. Implement a fully functional Generic Stack<T> class template supporting push(), pop(), peek(), and isEmpty(), and demonstrate its use with multiple data types.
1. Principles of Generic Programming
Generic Programming is a software development paradigm that designs algorithms and data structures without specifying concrete data types. In C++, this is realized via Templates:
- The data type becomes a parameter represented by a placeholder (e.g.
template <typename T>). - The compiler generates specific class code (template instantiation) only when a concrete type is specified:
Stack<int>orStack<string>. - Provides compile-time type safety while eliminating code duplication across types.
2. Complete Compilable Generic Stack Program
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class Stack {
private:
T* arr;
int topIndex;
int capacity;
public:
Stack(int cap = 10) : capacity(cap), topIndex(-1) {
arr = new T[capacity];
}
~Stack() {
delete[] arr;
}
bool isFull() const { return topIndex == capacity - 1; }
bool isEmpty() const { return topIndex == -1; }
void push(const T &item) {
if (isFull()) {
cout << "Stack Overflow! Cannot push item." << endl;
return;
}
arr[++topIndex] = item;
}
T pop() {
if (isEmpty()) {
cout << "Stack Underflow! Returning default." << endl;
return T();
}
return arr[topIndex--];
}
T peek() const {
if (isEmpty()) return T();
return arr[topIndex];
}
void display() const {
if (isEmpty()) { cout << "[Empty Stack]" << endl; return; }
cout << "Top -> ";
for (int i = topIndex; i >= 0; i--) {
cout << "[" << arr[i] << "] ";
}
cout << endl;
}
};
int main() {
// 1. Integer Stack Demonstration
cout << "=== Testing Generic Stack with Integers ===" << endl;
Stack<int> intStack(5);
intStack.push(10);
intStack.push(20);
intStack.push(30);
intStack.display();
cout << "Popped: " << intStack.pop() << endl;
intStack.display();
// 2. String Stack Demonstration
cout << "\n=== Testing Generic Stack with Strings ===" << endl;
Stack<string> strStack(5);
strStack.push("CCSU");
strStack.push("BCA-301");
strStack.push("Object-Oriented");
strStack.display();
cout << "Peeked top element: " << strStack.peek() << endl;
cout << "Popped: " << strStack.pop() << endl;
strStack.display();
return 0;
}
Q11. Explain User-Defined Type Conversions in C++: Basic to Class type, Class to Basic type, and Class to Class type. Provide clear rules and a complete working program.
1. Three Categories of Type Conversions in C++
| Conversion Category | Syntax Mechanism | Key Rules |
|---|---|---|
| 1. Basic to Class Type | Constructor with Single Argument:Distance(float meters) { ... } |
The single argument of primitive type is passed to the class constructor to initialize the object. |
| 2. Class to Basic Type | Casting Operator Function:operator float() const { ... } |
Must be a member function; must take no arguments; must specify no return type (the return type is implicit in the operator name). |
| 3. Class to Class Type | Conversion Constructor (in Destination) OR Casting Operator (in Source) | Translates between two custom objects (e.g. converting 24-Hour time format to 12-Hour AM/PM format). |
2. Complete Compilable Solution
#include <iostream>
using namespace std;
// Class Distance with Feet & Inches
class Distance {
private:
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0f) {}
// Type 1: Basic to Class Type (Single-argument constructor converting meters)
Distance(float meters) {
float totalInches = meters * 39.3701f;
feet = static_cast<int>(totalInches / 12);
inches = totalInches - (feet * 12);
}
// Type 2: Class to Basic Type (Casting operator function converting to meters)
operator float() const {
float totalInches = (feet * 12) + inches;
return totalInches / 39.3701f;
}
void display() const {
cout << feet << " ft " << inches << " in";
}
};
int main() {
// 1. Basic to Class conversion
float inputMeters = 2.5f;
Distance d1 = inputMeters; // Invokes Distance(float) constructor
cout << inputMeters << " meters converted to Distance object: ";
d1.display();
cout << endl;
// 2. Class to Basic conversion
float outputMeters = d1; // Invokes operator float()
cout << "Distance object converted back to basic float meters: " << outputMeters << " m" << endl;
return 0;
}
Q12. Explain the complete Exception Handling Model in C++. What is "Stack Unwinding"? Discuss standard exception classes and write a complete program illustrating a user-defined custom exception class.
1. Exception Lifecycle & Stack Unwinding
Stack Unwinding is the automated process by which the runtime environment cleans up the call stack when an exception is thrown:
- When an exception is thrown via
throw, the runtime immediately suspends execution of the current function. - It unwinds the stack frames backward until a matching
catchblock is found. - During this unwinding, the destructors of all fully constructed local objects in intermediate frames are guaranteed to be executed, preventing memory leaks and resource locks.
2. Complete Program with Custom User-Defined Exception Class
#include <iostream>
#include <exception>
#include <string>
using namespace std;
// User-Defined Custom Exception Class derived from std::exception
class InsufficientFundsException : public exception {
private:
string errorMsg;
double deficit;
public:
InsufficientFundsException(double currentBal, double withdrawAmt) {
deficit = withdrawAmt - currentBal;
errorMsg = "Transaction Failed: Deficit of Rs. " + to_string(deficit) + " exceeds account balance!";
}
// Overriding std::exception virtual what() method
const char* what() const noexcept override {
return errorMsg.c_str();
}
double getDeficit() const { return deficit; }
};
class BankAccount {
private:
int accNum;
double balance;
public:
BankAccount(int num, double bal) : accNum(num), balance(bal) {}
void withdraw(double amount) {
cout << "Attempting withdrawal of Rs. " << amount << " from Acc #" << accNum << " (Bal: Rs. " << balance << ")..." << endl;
if (amount > balance) {
throw InsufficientFundsException(balance, amount); // Throw custom exception
}
balance -= amount;
cout << "Withdrawal Successful! Remaining Balance: Rs. " << balance << endl;
}
};
int main() {
BankAccount myAccount(50124, 15000.0);
try {
myAccount.withdraw(5000.0); // Valid transaction
myAccount.withdraw(12000.0); // Triggers InsufficientFundsException
}
catch (const InsufficientFundsException &ex) {
cout << "[Custom Exception Caught] " << ex.what() << endl;
cout << "Please deposit at least Rs. " << ex.getDeficit() << " to complete transaction." << endl;
}
catch (const exception &stdEx) {
cout << "[Standard Exception Caught] " << stdEx.what() << endl;
}
catch (...) {
cout << "[Unknown Exception] Generic safety trap." << endl;
}
return 0;
}
BCA-301 High-Frequency Formula & Syntax Summary
Instant 5-Minute Pre-Examination Cheat Sheet
| Concept / Mechanism | Canonical C++ Syntax | University Exam Rule |
|---|---|---|
| Virtual Base Class (Diamond Problem) | class B : virtual public A { ... }; |
Guarantees only one shared instance of Base A exists in derived Class D. |
| Pure Virtual Function & Abstract Class | virtual void display() = 0; |
Cannot instantiate base class directly; mandatory override in derived. |
| Virtual Destructor in Base | virtual ~Base() { ... } |
Mandatory when deleting derived objects via base pointers to prevent memory leaks. |
| Binary Operator Overload (Member) | Complex operator+(const Complex &c); |
Calling object is left operand (*this); accepts 1 explicit argument. |
| Binary Operator Overload (Friend) | friend Complex operator+(Complex a, Complex b); |
Accepts 2 explicit arguments; enables symmetric conversions (e.g. 5 + c1). |
| Class to Basic Conversion | operator float() const { return val; } |
No return type specified; no arguments; must be a member function. |
| File Random Access Position | file.seekg(0, ios::end); int sz = file.tellg(); |
seekg moves get pointer; tellg returns current byte offset. |
| Generic Class Template | template <typename T> class Stack { ... }; |
Instantiated per type at compile-time: Stack<int> s; |