CSC166 · TU past paper
Object Oriented Programming 2078 question paper
The complete TU 2078 exam paper for Object Oriented Programming (CSC166), all 12 questions with solved model answers written to the mark scheme.
Tap a question to open its answer.
- 110 marksStatic membersHideAnswer
Write a program according to the specification given below: - Create a class Account with data members acc_no, balance, and min_balance(static) - Include methods for reading and displaying values of objects - Define static member function to display min_balance - Create array of objects to store data of 5 accounts and read and display values of each object[10]
--- --- - Declared inside the class with keyword static - Only one copy is shared among all objects of the class - Must be defined and initialized outside the class: - Declared with keyword static - Can be called without creating an obje...
- 210 marksTypes of inheritanceHideAnswer
How ambiguity arises in multipath inheritance? How can you remove this type of ambiguity? Explain with suitable example.[10]
Multipath inheritance (also called diamond problem or hybrid inheritance) occurs when a derived class inherits from two or more base classes that themselves share a common ancestor. This creates multiple paths through which the derived c...
- 310 marksNumericalData ConversionHideAnswer
What is meant by type conversion? Define two way of converting one user defined data type (object) to another user defined object? Write a program that converts object of another distance class with data members feet and inch. (Assume 1m = 3.3 feet and 1cm = 0.4 inch)[10]
Type Conversion in C++
Step 1 - EXTRACT (Given data)
- Source class:
Meterwith data membersmeter(m) andcentimeter(cm). - Destination class:
Distancewith data membersfeetandinch. - Conversion factors:
- $1\ \text{m} = 3.3\ \text{feet}$
- $1\ \text{cm} = 0.4\ \text{inch}$
- Task: write a program converting an object of one class to a
Distanceobject; explain type conversion and two ways of converting between user-defined types.
No numeric input is missing. (The specific test values like $5\text{ m}, 50\text{ cm}$ are chosen for demonstration.)
Step 2 - SOLVE
1. What is Type Conversion?
Type conversion is the process of changing a value of one data type into another data type. For built-in types (e.g.,
inttofloat), the compiler performs conversions automatically. But for user-defined types (class objects), the compiler does not know the conversion rule, so the programmer must define it explicitly.Three kinds exist:
- basic to class type
- class to basic type
- class to class type (the focus here)
2. Two Ways of Converting One User-Defined Object to Another
Method 1 - Constructor in the Destination class: A single-argument (conversion) constructor is written in the destination class taking a source object as argument.
class Destination { public: Destination(Source s) { /* extract and assign */ } };On
Destination d = s;the compiler calls this constructor.Method 2 - Overloaded Casting (Conversion) Operator in the Source class: A conversion function
operator Destination()is written in the source class.class Source { public: operator Destination() { Destination t; /* fill t */ return t; } };On
Destination d = s;the compiler calls this operator.Rule: the conversion routine is placed in the destination class (constructor) or in the source class (operator function), never split.
3. Program (both methods)
#include <iostream> using namespace std; class Distance { // Destination class float feet, inch; public: Distance(float f = 0, float i = 0) { feet = f; inch = i; } void display() { cout << "Feet : " << feet << " ft, Inch : " << inch << " in" << endl; } }; class Meter { // Source class float meter, centimeter; public: Meter(float m = 0, float cm = 0) { meter = m; centimeter = cm; } void display() { cout << "Meter: " << meter << " m, cm: " << centimeter << " cm" << endl; } // Method 2: conversion (casting) operator in source class operator Distance() { // 1 m = 3.3 feet, 1 cm = 0.4 inch return Distance(meter * 3.3f, centimeter * 0.4f); } }; int main() { Meter m1(5, 50); // 5 m, 50 cm m1.display(); Distance d1 = m1; // calls operator Distance() d1.display(); return 0; }(Alternatively, Method 1 uses a
Distance(Meter m)constructor withfeet = m.getMeter()*3.3; inch = m.getCentimeter()*0.4;.)4. Verification of Calculation (for 5 m, 50 cm)
$$\text{feet} = 5 \times 3.3 = 16.5\ \text{ft}$$ $$\text{inch} = 50 \times 0.4 = 20.0\ \text{in}$$
Output:
Meter: 5 m, cm: 50 cm Feet : 16.5 ft, Inch : 20 in - Source class:
- 45 marksUnformatted Input/OutputHideAnswer
What is the use of get and getline functions? Explain with suitable example. [5]
Both get() and getline() are input functions in C++ used to read character(s) or strings from the input stream (cin). They are particularly useful when reading input that includes whitespace characters (spaces, tabs, newlines), which the...
- 55 marksFunctionsHideAnswer
What is meant by pass by reference? How can we pass arguments by reference by using reference variable? Illustrate with example. [5]
Pass by Reference in C++
Definition
Pass by reference is a method of passing arguments to a function where the address (location) of a variable is passed to the function. When a function is called by reference, the formal arguments become references to the actual arguments. This means any changes made to the formal parameters inside the function directly affect the actual arguments in the calling function.
In contrast, pass by value sends a copy of the data, so the original variable remains unchanged.
Passing Arguments by Reference Using Reference Variables
In C++, a reference variable is an alias (another name) for an existing variable. It is declared using the
&symbol. When used as a function parameter, the formal parameter becomes a reference to the actual argument -- no copy is made, and changes inside the function reflect in the original variable.Syntax:
return_type function_name(data_type ¶m1, data_type ¶m2);
Example: Swapping Two Numbers Using Pass by Reference
#include <iostream> using namespace std; // Function using reference variables as parameters void swap(int &a, int &b) { int temp; temp = a; a = b; b = temp; } int main() { int x = 10, y = 20; cout << "Before swap: x = " << x << ", y = " << y << endl; swap(x, y); // x and y are passed by reference cout << "After swap: x = " << x << ", y = " << y << endl; return 0; }Output:
Before swap: x = 10, y = 20 After swap: x = 20, y = 10
Explanation
Aspect Detail int &aais a reference to the actual argumentxint &bbis a reference to the actual argumentyChanges to aDirectly change xinmain()Changes to bDirectly change yinmain()No copy made Memory efficient; original values are modified
Key Points
- The
&symbol in the parameter list makes the parameter a reference variable. - The formal argument and actual argument share the same memory location.
- No separate copy of the variable is created, unlike pass by value.
- This is useful when a function needs to modify the original variable or when passing large objects to avoid overhead of copying.
- The
- 65 marksDefault ConstructorHideAnswer
What is constructor? Explain the concept of default and default copy with suitable example. [5]
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 - H...
- 75 marksFriend function and Static functionHideAnswer
What is the concept of friend function? How it violates the data hiding principle? Justify with example. [5]
A friend function is a non-member function that is granted special access to the private and protected members of a class. Although it is not a member of the class, it can access all private and protected data of that class as if it were...
- 85 marksOverview of structured programming approacHideAnswer
What is structured programming? Discuss characteristics and problems associated with structured programming. [5]
Structured programming (also called Procedure Oriented Programming) is a programming paradigm that contains well-structured steps and procedures, using different functions for different tasks in a program. It follows a top-to-bottom (top...
- 95 marksExceptional HandlingHideAnswer
What is exception? Why exception handling is better to use? Explain exception handling with try.... catch by using suitable example. [5]
Exception Handling in C++ with try...catch
What is an Exception?
An exception is an unusual or abnormal event (error condition) that occurs during the execution of a program and disrupts the normal flow of the program's instructions. Examples include division by zero, file not found, invalid memory access, and array index out of bounds.
Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw.
Why is Exception Handling Better to Use?
Without Exception Handling With Exception Handling Errors cause abrupt program termination Program can handle errors gracefully Error-checking code mixed with normal code Clean separation of error-handling code Difficult to maintain and read Easier to maintain and debug No mechanism to propagate errors Errors can be propagated up the call stack Key benefits:
- Keeps the normal logic and error-handling logic separate
- Prevents abnormal program termination
- Allows recovery from runtime errors
- Makes code more readable and maintainable
Three Keywords of Exception Handling
- try -- Defines a block of code to be tested for errors while it is being executed. A block that may raise an exception is placed inside a try block (called protected code).
- throw -- Used to throw (signal) an exception when a problem is detected.
- catch -- Catches the exception thrown by the try block and handles it. The catch keyword indicates the catching of an exception.
Syntax
try { // protected code // code that might throw an exception throw exception_value; } catch (type variable) { // exception handler // code to handle the exception }A try/catch block is referred to as protected code.
Example: Division by Zero
#include <iostream> using namespace std; int divide(int a, int b) { if (b == 0) { throw "Division by zero is not allowed!"; // throw exception } return a / b; } int main() { int x = 10, y = 0; try { // protected code int result = divide(x, y); cout << "Result: " << result << endl; } catch (const char* msg) { // exception handler cout << "Exception caught: " << msg << endl; } cout << "Program continues after exception handling." << endl; return 0; }Output:
Exception caught: Division by zero is not allowed! Program continues after exception handling.
How it Works (Step by Step)
Step 1: divide(10, 0) is called inside the try block Step 2: Inside divide(), b == 0, so throw is executed Step 3: Control immediately transfers to the matching catch block Step 4: catch(const char* msg) catches the thrown string Step 5: Error message is displayed Step 6: Program continues normally after the catch block
Summary
Keyword Role tryEncloses code that might cause an exception throwSignals that an exception has occurred catchHandles the exception and prevents program crash Exception handling ensures that even when errors occur at runtime, the program can handle them gracefully and continue execution rather than crashing abruptly.
- 105 marksClass templatesHideAnswer
When class templates are useful? How can you define a class that can implement stack with integer as well as sack of strings? Illustrate with example. [5]
Class templates are useful when: - You need to create a class that performs the same operations on different data types (int, float, string, etc.) - You want to avoid code duplication by writing a single generic class instead of separate...
- 115 marksFile Input/output with StreamsHideAnswer
What is meant by stream? Write a program that reads content of file data.txt and displays the content in monitor. [5]
A stream is a sequence of bytes flowing between a program and an input/output device (such as a keyboard, monitor, or file). In C++, a stream acts as an interface between the program and the actual I/O device, allowing data to flow in or...
- 125 marksInput/Output Streams and ManipulatorsHideAnswer
Write short notes on: a. Manipulators b. Protected Access Specifier [5]
--- Manipulators are special functions used in C++ to format the output or manipulate the stream in a convenient way. They are used along with the insertion (<<) and extraction () operators. In the context of file access, each file has t...