0% found this document useful (0 votes)
506 views70 pages

C++ Model Question Paper Answer

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
506 views70 pages

C++ Model Question Paper Answer

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1. Define an algorithm. List its main features.

 An algorithm is a step by step procedure to solve a problem


 In other words, an algorithm is a sequence of instructions that act on some input data to produce
some output in a finite number of steps
 Algorithm is independent of any programming language
 Algorithm is written in the natural languages like English

Five properties/Features of algorithm are:


1) Input: An algorithm may have many inputs or no inputs at all
2) Output: An algorithm must produce at least 1 output as result
3) Finite: An algorithm should have finite number of steps and it should end after a finite time
4) Definite: Each step must be clear, well-defined and precise. There should be no any ambiguity
5) Effective: Each step must be simple and should take a finite amount of time.

2. Draw symbols for Start, End, and Decision in a flowchart.

3. What is a keyword? Give an example.


Keywords(also known as reserved words) have special meanings to the C++ compiler and are always
written or typed in short(lower) cases. Keywords are words that the language uses for a special purpose,
such as void, int, public, etc. It can’t be used for a variable name or function name or any other identifiers.

4. What are actual and formal arguments?


• Argument (or parameter) refers to data that is passed to the function-definition.
• Arguments used in the function-call are referred to as actual-arguments.

These actual values are passed to a function to compute a value or to perform a task.
• The arguments used in the function-declaration are referred as formal arguments.
They are formal variables that accept or receive the values supplied by the function-call.
• The no. of actual- and formal-arguments and their data-types should be same.

5. What is a pointer?
A pointer is a variable which holds address of another variable or a memorylocation.
• For ex:
c=22;
pc=&c;

1
Here pc is a pointer; it can hold the address of variable c
& is called reference operator

6. Define a union. Give an example.


• Union is a collection of elements of different data-type.
• Unlike structures, where each member has its own memory-location, all members of a union share the
same memory-location.
• Syntax:
union Union_name
{
data_type member1;
data_type member2;
data_type member3;
};
• The variables that are used to store the data are called members of the Union.
• For example:
union Person
{
string name;
int cit_no;
float salary;
};

7. What is object-oriented programming? Name two of its features.


This type of language treats a program as a group of objects composed of data and program elements,
known as attributes and methods. Objects can be reused within a program or in other programs. This
makes it a popular language type for complex programs, as code is easier to reuse and scale. Some
common object-oriented languages include:
 Java
 Python

 PHP

 C++

 Ruby
Features of oop
 Encapsulation
 Inheritance
 Polymorphism
 Abstraction

8. What are static member functions? Why they are used?


Definition: A static member-function can access only static data-members and other static member-
functions of the class.
• It can be called using the class-name without needing an object.
Accessing Static Member-data and Functions
• Static data-members are accessed using the class-name or through an object, but using the class-name is
the standard approach.

2
Advantages of Static Members
• Memory Efficiency: Static data-members save memory by not duplicating data for each object instance.
• Class-Level Operations: Static member-functions can perform operations at the class level rather than on
individual objects.

9. Define constructor overloading.


• Constructor overloading means having more than one constructor in a class, each with different
parameters.
Purpose
• This allows objects to be initialized in different ways.
Features
• Multiple Constructors: A class can have more than one constructor.
• Flexibility: Overloaded constructors allow the creation of objects with different initial values.
• Easy to Read: Overloading constructors makes the code easier to read and understand.

10. What is a virtual function?


Virtual-functions are functions in a base-class that can be overridden in derived classes.
They enable dynamic (runtime) polymorphism, where the function called depends on the type-of-object.
Features
• Dynamic Polymorphism: Allows base-class pointers to call derived-class methods.
• Function Overriding: Lets derived-classes provide their own version of a base class method.
• Base-class Pointer: A base-class pointer can be used to call functions in derived classes.
• Virtual Table (vtable): Stores pointers to virtual-functions, supporting their dynamic behavior.

11. What is a multi-level inheritance?


• Multi-Level Inheritance is when a class is derived from another derived-class.
• This creates a chain where each class inherits from the one above it.

Features
• Code Reusability: The final-class can reuse code from all classes in the chain.
• Transitive Inheritance: A class can use features from its base-class and also from classes higher in the
chain.
• Hierarchical Structuring: It allows creating complex class-structures that show clear relationships.
• Incremental Development: Each class can add features gradually as it inherits from the previous one.

12. What are unformatted I/O operations?


Input- and output-operations where data is read or written without applying any specific formatting-rules.
The data is transferred in its raw, unmodified form.
Purpose

3
• To perform simple, direct input- and output-operations without any concern for how the data is
presented or formatted.
• Useful for efficient, low-level data handling where formatting is not necessary.
Usage
• Often used when handling binary-data or performing low-level file operations.
• Provides more control over how data is managed and transferred, without altering its format.

Example:

1. Explain the program development life cycle with a diagram.

The PDLC is an iterative process that allows for feedback and adjustments to be made at each phase, to
ensure that the final product meets the needs of the stakeholders and is of high quality.

 Program Development Life Cycle (PDLC) is a systematic way of developing quality software.

 It provides an organized plan for breaking down the task of program development into manageable
chunks, each of which must be completed before moving on to the next phase.

Phases of PDLC

1. Planning: In this phase, the goals and objectives of the program are defined, and a plan is
developed to achieve them. This includes identifying the resources required and determining the
budget and schedule for the program.

2. Analysis: In this phase, the requirements for the program are defined and analyzed. This includes
identifying the stakeholders, their needs and expectations, and determining the functional and non-
functional requirements for the program.

3. Design: In this phase, the program’s architecture and design are developed. This includes creating a
detailed design of the program’s components and interfaces, as well as determining how the
program will be tested and deployed.

4
4. Implementation: In this phase, the program is developed and coded. This includes writing the
program’s source code and creating any necessary documentation.

5. Testing: In this phase, the program is tested to ensure that it meets the requirements and is free of
defects.

6. Deployment: In this phase, the program is deployed and made available to users.

7. Maintenance: After the deployment, the program is maintained by fixing any bugs or errors that
are found and updating the program to meet changing requirements.

2. Describe the general structure of a C++ program with an example.

GENERAL STRUCTURE OF C++ PROGRAM

#include <iostream> // Preprocessor-directive


using namespace std; // Namespace declaration
int main() // Main function
{
declaration section
statement-1 // Executable section starts
statement-2
statement-3 // Executable section ends
}

Preprocessor-directives
• The preprocessor accepts the source-program and prepares the source-program for compilation.
• The preprocessor-statements start with symbol #.
• The normal preprocessor used in all programs is include.
• The #include directive instructs the preprocessor to include the specified file contents in the beginning of
the program.

• For ex:
#include< iostream >

Namespace Declaration
• Namespaces are used to organize code into logical-groups and avoid naming conflicts.
main()
• Every C++ program should have a function-called as main().
• This the first function to be executed always.
• The statements enclosed within left and right brace is called body of the function.
• The main() function is divided into 2 parts:

i) Declaration section
• The variables that are used within the function main() should be declared in the declaration-section only.
• The variables declared inside a function are called local-variables.
Ex: int p, t, r;
ii) Executable section
• This contains the instructions given to the computer to perform a specific task.
• The task may be to
→ display a message
→ read data or
5
→ add 2 numbers etc
• Comments are portions of the code ignored by the compiler. The comments allow the user to make
simple notes in the source-code.
// this is an example for single line comment
/* this is an example
for multiple line comment */

• Program to display a message on the screen


#include <iostream>
using namespace std;
int main() {
cout << "Welcome to C++" << endl;
return 0;
}
Output: Welcome to C++

3. What are the different types of operators in C++? Explain any four with examples.
• An operator specifies what operations need to be performed on the data.
• For ex:
+ indicates add operation
* indicates multiplication operation

Different types of operators are:


1. Arithmetic operators
2. Relational operators
3. Logical Operators
4. Bitwise Operators
5. Assignment operators
6. Increment and Decrement operators
7. Comma Operator
8. Type-casting operators
9. Size of operator
10. Pointer operators
11. Scope Resolution operator

Conditional Operators:
• The conditional operator is also called ternary operator as it takes three operands.
• Conditional operators are used for decision making in C++.
• Syntax:
(exp1)? exp2: exp3;
where exp1 is an expression evaluated to true or false;
If exp1 is evaluated to true, exp2 is executed;
1. If exp1 is evaluated to false, exp3 is executed.

Relational Operators:
Relational operators are used to find the relationship between two operands.
• The output of relational-expression is either true (1) or false (0).
• For example
a>b // If a is greater than b,
// then a>b returns 1
// else a>b returns 0.
6
The 2 operands may be constants, variables or expressions.

LOGICAL OPERATORS
• These operators are used to perform logical operations.
• The output of logical-expression is either true (1) or false (0).
• There are 3 logical operators:

Operator Meaning Example


&& Logical AND If c=5 and d=2 then ((c==5) && (d>5)) returns false.
|| Logical OR If c=5 and d=2 then ((c==5) || (d>5)) returns true.
! Logical NOT If c=5 then !(c==5) returns false.
• All non-zero values (i.e. 1, -1, 2, -2) will be treated as true.
While zero value (i.e. 0) will be treated as false.

ASSIGNMENT OPERATOR
• The most common assignment operator is =.
• This operator assigns the value in right side to the left side.
• Syntax:
variable=expression;
• For ex:
c=5; //5 is assigned to c
b=c; //value of c is assigned to

4. Explain type conversion and type casting in C++. Give examples.


Type conversion is used to convert data of one type to data of another type.
• Type conversion is of 2 types:
1) Type Conversion (Implicit Conversion)
2) Type Casting (Explicit Conversion)

TYPE CONVERSION (IMPLICIT CONVERSION)


• If a compiler converts one type of data into another type of data automatically, it is known as implicit
conversions.
• There is no data loss in implicit conversion.
• The conversion always takes place from lower rank to higher rank.
• If one operand type is same as other operand type, no conversion takes place and type of result remains
same as the operands i.e. int+int=int ,float+float=float

7
• Conversion rules are as follows:
→ If either operand is long double, convert the other to long double.
→ Otherwise, if either operand is double, convert the other to double.
→ Otherwise, if either operand is float, convert the other to float.
→ Otherwise, convert char and short to int.
→ Then, if either operand is long, convert the other to long.

Program to illustrate implicit conversion.


#include <iostream>
using namespace std;
int main() {
int a = 5;
double b = 10.5;
double result = a + b; // Implicit conversion of 'a' to double before addition
cout << "Result: " << result << endl;
return 0;
}
Output: Result: 15.5

TYPE CASTING (EXPLICIT CONVERSION)


• When the data of one type is converted explicitly to another type with the help of
some pre-defined functions, it is called as explicit conversion.
• There may be data loss in this process because the conversion is forceful.
• Syntax:
data_type1 v1;
data_type2 v2 = static_cast<data_type2>(v1);
where v1 can be expression or variable

• Program to illustrate explicit conversion.


#include <iostream>
int main() {
float b = 11.000000;
int c = 22;
float d = b / static_cast<float>(c);
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "d = " << d << endl;
return 0;
}
Output:
b = 11
c = 22
d = 0.5

5. Explain inline functions with suitable example.


Definition
• Inline functions are small functions that the compiler can expand at the point of call rather than
executing a function-call.
• They are typically used for short and simple functions to avoid the overhead of function-call.
How It Works
8
• When a function is declared as inline, the compiler replaces the function-call with the actual code of the
function-body.
• This eliminates the overhead of function-call and improves program execution speed.
Syntax
• To declare a function as inline, use the `inline` keyword before the function definition.
• Syntax:
inline type funcation_name() {
….. . . .
}
Advantages
• Inline functions reduce function-call overhead, especially useful for small functions.
• They can improve program performance by eliminating the time spent in function call setup and return.
Example
• Program to demonstrate the use of an inline function:
#include <iostream>
using namespace std;
// Inline function to calculate the square of a number
inline int square(int num) {
return num * num;
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
// Call to the inline function square()
cout << "Square of " << num << " is: " << square(num) << endl;
return 0;
}
Output
Enter a number: 5
Square of 5 is: 25

6. Describe the different storage classes in C++.

C++ Storage Classes are used to describe the characteristics of a variable/function. It determines the
lifetime, visibility, default value, and storage location which helps us to trace the existence of a particular
variable during the runtime of a program. Storage class specifiers are used to specify the storage class for a
variable.

Syntax

To specify the storage class for a variable, the following syntax is to be followed:
storage_class var_data_type var_name;

C++ uses 6 storage classes, which are as follows:

auto Storage Class = auto Storage Class

The auto storage class is the default class of all the variables declared inside a block. The auto stands for
automatic and all the local variables that are declared in a block automatically belong to this class.
Properties of auto Storage Class Objects

9
 Scope: Local
 Default Value: Garbage Value
 Memory Location: RAM
 Lifetime: Till the end of its scope

2. register Storage Class =

The register storage class declares register variables using the ‘register’ keyword which has the
same functionality as that of the auto variables. The only difference is that the compiler tries to
store these variables in the register of the microprocessor if a free register is available. This makes
the use of register variables to be much faster than that of the variables stored in the memory
during the runtime of the program. If a free register is not available, these are then stored in the
memory only.
Properties of register Storage Class Objects
 Scope: Local
 Default Value: Garbage Value
 Memory Location: Register in CPU or RAM
 Lifetime: Till the end of its scope

3. extern Storage Class =


The extern storage class simply tells us that the variable is defined elsewhere and not within the
same block where it is used (i.e. external linkage). Basically, the value is assigned to it in a different
block and this can be overwritten/changed in a different block as well. An extern variable is nothing
but a global variable initialized with a legal value where it is declared in order to be used elsewhere.
Properties of extern Storage Class Objects
 Scope: Global
 Default Value: Zero
 Memory Location: RAM
 Lifetime: Till the end of the program.

4. static Storage Class

The static storage class is used to declare static variables which are popularly used while writing
programs in C++ language. Static variables have the property of preserving their value even after
they are out of their scope! Hence, static variables preserve the value of their last use in their
scope.
Properties of static Storage Class
 Scope: Local
 Default Value: Zero
 Memory Location: RAM
 Lifetime: Till the end of the program

5. mutable Storage Class

Sometimes there is a requirement to modify one or more data members of class/struct through the
const function even though you don’t want the function to update other members of class/struct.
This task can be easily performed by using the mutable keyword. The keyword mutable is mainly
used to allow a particular data member of a const object to be modified.

Properties of mutable Storage Class

10
The mutable specifier does not affect the linkage or lifetime of the object. It will be the same as the normal
object declared in that place.

6. thread local Storage Class

The thread_local Storage Class is the new storage class that was added in C++11. We can use the
thread_local storage class specifier to define the object as thread_local. The thread_local variable can be
combined with other storage specifiers like static or extern and the properties of the thread_local object
changes accordingly.
Properties of thread_local Storage Class
 Memory Location: RAM
 Lifetime: Till the end of its thread

7. Describe the process of initializing and accessing elements in a one-dimensional array with an
example.

Array:-

An array is defined as an ordered set of similar data items. All the data items of an array are stored
in consecutive memory locations in RAM. The elements of an array are of same data type and each
item can be accessed using the same name.

Declaration of an array:- We know that all the variables are declared before they are used in the
program. Similarly, an array must be declared before it is used. During declaration, the size of the
array has to be specified. The size used during declaration of the array informs the compiler to
allocate and reserve the specified memory locations.
Syntax:- data_type array_name[n];
where, n is the number of data items (or) index(or) dimension.
0 to (n-1) is the range of array.
Ex: int a[5];
float x[10];

Initialization of Arrays:-
The different types of initializing arrays:
1. At Compile time
(i) Initializing all specified memory locations.
(ii) Partial array initialization
(iii) Initialization without size.
(iv) String initialization.

2. At Run Time
1. Compile Time Initialization
We can initialize the elements of arrays in the same way as the ordinary variables when they are
declared.
The general form of initialization of arrays is
type array-name[size]={ list of values};

(i) Initializing all specified memory locations:- Arrays can be initialized at the time of declaration
when their initial values are known in advance. Array elements can be initialized with data items of
type int, char etc.

Ex:- int a[5]={10,15,1,3,20};


11
During compilation, 5 contiguous memory locations are reserved by the compiler for the variable
at and all these locations are initialized .
Ex:-
int a[3]={9,2,4,5,6}; //error: no. of initial vales are more than the size of array.

(ii) Partial array initialization:- Partial array initialization is possible in c language. If the number of
values to be initialized is less than the size of the array, then the elements will be initialized to zero
automatically.
Ex:-
int a[5]={10,15};

Even though compiler allocates 5 memory locations, using this declaration statement; the compiler
initializes first two locations with 10 and 15, the next set of memory locations are automatically
initialized to 0's by compiler .
Initialization with all zeros:-
Ex:-
int a[5]={0};

(iii) Initialization without size:- Consider the declaration along with the initialization.
Ex:-
char b[]={'C','O','M','P','U','T','E','R'};
In this declaration, even though we have not specified exact number of elements to be used in
array b, the array size will be set of the total number of initial values specified. So, the array size will
be set to 8 automatically. The array b is initialized.

Ex:- int ch[]={1,0,3,5} // array size is 4


(iv) Array initialization with a string: -Consider the declaration with string initialization.
Ex:-
char b[]="COMPUTER";
Even though the string "COMPUTER" contains 8 characters, because it is a string, it always ends
with null character. So, the array size is 9 bytes (i.e., string length 1 byte for null character).
Ex:-
char b[9]="COMPUTER"; // correct
char b[8]="COMPUTER"; // wrong

2. Run Time Initialization


An array can be explicitly initialized at run time. This approach is usually applied for initializing
large arrays.
Ex:- scanf can be used to initialize an array.
int x[3];
scanf(“%d%d%d”,&x[0],&x[1],&x[2]);
The above statements will initialize array elements with the values entered through the key board.
(Or)
for(i=0;i<100;i=i+1)
{
if(i<50)
sum[i]=0.0;
else
sum[i]=1.0;
}
The first 50 elements of the array sum are initialized to 0 while the remaining 50 are initialized to
1.0 at run time.
12
7. Explain string handling functions with examples.
C supports a number of string handling functions. All of these built-in functions are aimed at performing
various operations on strings and they are defined in the header file string.h.

(i). strlen( )
This function is used to find the length of the string excluding the NULL character. In other
words, this function is used to count the number of characters in a string. Its syntax is as follows:

Example: char str1[ ] = “WELCOME”;


int n;
n = strlen(str1);

(ii). strcpy( )
This function is used to copy one string to the other. Its syntax is as follows:
where string1 and string2 are one-dimensional character arrays. This function copies the content of string2
to string1.
E.g., string1 contains master and string2 contains madam, then string1 holds madam after
execution of the strcpy (string1,string2) function.

Example: char str1[ ] = “WELCOME”;


char str2[ ] =”HELLO”;
strcpy(str1,str2);

(iii). strcmp ( )
This function compares two strings character by character (ASCII comparison) and returns one
of three values {-1,0,1}. The numeric difference is „0‟ if strings are equal .If it is negative string1
is alphabetically above string2 .If it is positive string2 is alphabetically above string1.
Its syntax is as follows:
Example: char str1[ ] = “ROM”;

char str2[ ] =”RAM”;


strcmp(str1,str2);
(or)
strcmp(“ROM”,”RAM”);

(iv). strcat ( )
This function is used to concatenate two strings. i.e., it appends one string at the end of the specified
string. Its syntax as follows:

where string1 and string2 are one-dimensional character arrays.


13
This function joins two strings together. In other words, it adds the string2 to string1 and the string1
contains the final concatenated string. E.g., string1 contains prog and string2 contains ram, then string1
holds program after execution of the strcat() function.
Example: char str1[10 ] = “VERY”;
char str2[ 5] =”GOOD”;
strcat(string1,string2);
strcat(str1,str2);

8. Explain different types of constructors in C++ with examples.


Constructors:
• Special Member Function: Constructors are special member functions that are automatically called when
an object of a class is created.
• Same Name as Class: A constructor has the same name as the class and does not have a return type, not
even `void`.
• Initialization of Objects: The primary purpose of a constructor is to initialize the objects of its class.
• Automatic Invocation: Constructors are automatically invoked when an object is created.

Types
1. Default Constructor = A default constructor is a constructor that takes no arguments. It initializes
objects with default values.
 Example
class Rectangle {
public:
Rectangle() { // Default Constructor
length = 0;
width = 0;
}
private:
int length;
int width;
};
ii) Parameterized Constructor = A parameterized constructor takes one or more arguments. It allows
objects to be initialized with specific values.

class Rectangle {
public:
Rectangle(int l, int w) { // Parameterized Constructor
length = l;
width = w;
}
private:
int length;
int width;
};

iii) Copy Constructor = A copy constructor creates a new object by copying an existing one. It ensures that
all values from the original object are copied to the new one.

class Rectangle {
public:
Rectangle(const Rectangle &rect) { // Copy Constructor
length = [Link];
14
width = [Link];
}
private:
int length;
int width;
};

iv) Dynamic Constructor = A dynamic constructor allocates memory at runtime using the `new` keyword.
Memory for variables is allocated when an object is created.

class Rectangle {
public:
Rectangle(int l, int w) { // Dynamic Constructor
length = new int(l);
width = new int(w);
}
~Rectangle() { // Destructor to release memory
delete length;
delete width;
}
private:
int *length;
int *width;
};

9. Describe how binary operator overloading is implemented in C++.


An operator which contains two operands to perform a mathematical operation is called the Binary
Operator Overloading. It is a polymorphic compile technique where a single operator can perform
various functionalities by taking two operands from the programmer or user. There are multiple
binary operators like +, -, *, /, etc., that can directly manipulate or overload the object of a class.

Syntax of the Binary Operator Overloading

Following is the Binary Operator Overloading syntax in the C++ Programming language.
return_type :: operator binary_operator_symbol (arg)
{
// function definition
}

return_type: It defines the return type of the function.

operator: It is a keyword of the function overloading.

binary_operator_symbol: It represents the binary operator symbol that overloads a function to perform
the calculation.

arg: It defines the argument passed to the function.


Steps to Overload the Binary Operator to Get the Sum of Two Complex Numbers
Step 1: Start the program.
Step 2: Declare the class.

15
Step 3: Declare the variables and their member function.
Step 4: Take two numbers using the user-defined inp()function.
Step 6: Similarly, define the binary (-) operator to subtract two numbers.
Step 7: Call the print() function to display the entered numbers.
Step 8: Declare the class objects x1, y1, sum, and sub.
Step 9: Now call the print() function using the x1 and y1 objects.
Step 10: After that, get the object sum and sub result by adding and subtracting the objects using the '+'
and '-' operators.
10. What is a destructor? Explain its role in a C++ program with an example.
• Special Function: Destructors are special functions that run automatically when an
object is destroyed.
• Name with Tilde (~): A destructor has the same name as the class but starts with
a tilde (`~`). It has no return type or parameters.
• Cleans Up Resources: The main job of a destructor is to clean up resources like
memory or file handles when an object is no longer needed.
• Runs Automatically: Destructors run automatically when an object goes out of
scope or is deleted.

• Example: Program to illustrate Destructors


#include <iostream>
class Rectangle {
public:
// Public data members
int length, width;
// Constructor
Rectangle(int l, int w) {
length = l;
width = w;
cout << "Rectangle is created << endl;
}
// Destructor
~Rectangle() {
cout << "Rectangle is destroyed" << endl;
}
// Public member function to calculate area
int area() {
return length * width;
}
};
int main() {
// Creating an object of Rectangle class
Rectangle rect(10, 5);
// Displaying the area
cout << "Area: " << [Link]() << endl;
return 0;
}
Output:
Rectangle is created
16
Area: 50

Rectangle is destroyed

11. Describe the process of defining and accessing class objects in C++.
C++ Class
A class is a blueprint for the object.
We can think of a class as a sketch (prototype) of a house.
It contains all the details about the floors, doors, windows, etc - we build the house based on these
descriptions.
The house is the object.
Create a Class
A class is defined in C++ using the keyword class followed by the name of the class.
The body of the class is defined inside curly brackets and terminated by a semicolon at the end.
class ClassName {
// some data
// some functions
};

For example,
class Room {
public:
double length;
double breadth;
double height;

double calculate_area(){
return length * breadth;
}
double calculate_volume(){
return length * breadth * height;
}
};
Here, we defined a class named Room.
The variables length, breadth, and height declared inside the class are known as data members.
And the functions calculate_area() and calculate_volume () are known as member functions of a class.

C++ Objects
When a class is defined, only the specification for the object is defined; no memory or storage is allocated.
To use the data and access functions defined in the class, we need to create objects.

Syntax to Define Object in C++


ClassName object_name;

We can create objects of Room class (defined in the above example) as follows:
// sample function
void sample_function() {
17
// create objects
Room room1, room2;
}
int main(){
// create objects
Room room3, room4;
}

C++ Access Data Members and Member Functions


We can access the data members and member functions of a class by using a . (dot) operator.
For example,
room2.calculate_area();
This will call the calculate_area() function inside the Room class for object room2.
Similarly, the data members can be accessed as:
[Link] = 5.5;
In this case, it initializes the length variable of room1 to 5.5.

Example: Object and Class in C++ Programming


// Program to illustrate the working of
// objects and class in C++ Programming

#include <iostream>
using namespace std;

// create a class
class Room {

public:
double length;
double breadth;
double height;

double calculate_area() {
return length * breadth;
}

double calculate_volume() {
return length * breadth * height;
}
};

int main() {

// create object of Room class


Room room1;

// assign values to data members


18
[Link] = 42.5;
[Link] = 30.8;
[Link] = 19.2;

// calculate and display the area and volume of the room


cout << "Area of Room = " << room1.calculate_area() << endl;
cout << "Volume of Room = " << room1.calculate_volume() << endl;

return 0;
}
Run Code

Output
Area of Room = 1309
Volume of Room = 25132.8

In this program, we have used the Room class and its object room1 to calculate the area and volume of a
room.

In main(), we assigned the values of length, breadth, and height with the code:
[Link] = 42.5;
[Link] = 30.8;
[Link] = 19.2;

We then called the functions calculate_area() and calculate_volume() to perform the necessary
calculations.

12. Discuss single and multi-level inheritance with examples.


SINGLE-INHERITANCE
Definition
• Single-Inheritance allows a derived-class to inherit properties & behaviors from only one base-class.
Features
• Code Reusability: The derived-class can reuse code from the base-class. This reduces repeated-code.
• Extensibility: New features can be added to existing-classes without modifying them directly.
• Access Control: The derived-class can control how much of the base-class it exposes.
• Hierarchical Representation: The relationship between classes is clear and easy to understand.
Syntax
class BaseClass {
// Base-class-members
};
class DerivedClass : public BaseClass {
// Derived-class members
};
Where,
BaseClass: The class from which properties are inherited.
DerivedClass: The class that inherits properties.
public: Defines how the derived-class can use inherited-members.

19
Demonstrating Single-Inheritance
#include <iostream>
using namespace std;
// Base-class
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};
// Derived-class
class Dog : public Animal {
public:
void bark() {
cout << "Barking..." << endl;
}
};
int main() {
Dog myDog;
[Link](); // Inherited from Animal class
[Link](); // Defined in Dog class
return 0;
}
Output:
Eating...
Barking...
Explanation
• The `Animal` class has a function called `eat()`.
• The `Dog` class inherits from `Animal` and has its own function called `bark()`.
• In the `main()` function, the `Dog` object can use both `eat()` from `Animal`and `bark()` from `Dog`.

Definition
• Multi-Level Inheritance is when a class is derived from another derived-class.
• This creates a chain where each class inherits from the one above it.
Features
• Code Reusability: The final-class can reuse code from all classes in the chain.
• Transitive Inheritance: A class can use features from its base-class and also from classes higher in the
chain.
• Hierarchical Structuring: It allows creating complex class-structures that show clear relationships.
• Incremental Development: Each class can add features gradually as it inherits from the previous one.
Syntax
class BaseClass {
// Base-class-members
};
class IntermediateClass : public BaseClass {
// Intermediate class members
};
class DerivedClass : public IntermediateClass {
// Derived-class members
};
Where
BaseClass: The class at the start of the chain.
20
IntermediateClass: A class that inherits from BaseClass and serves as a base
for the next class.

DerivedClass: The class that inherits from IntermediateClass.

Example Program: Demonstrating Multi-Level Inheritance


#include <iostream>
// Base-class
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};
// Intermediate derived-class
class Mammal : public Animal {
public:
void walk() {
cout << "Walking..." << endl;
}
};
// Final derived-class
class Dog : public Mammal {
public:
void bark() {
cout << "Barking..." << endl;
}
};
int main() {
Dog myDog;
[Link](); // Inherited from Animal class
[Link](); // Inherited from Mammal class
[Link](); // Defined in Dog class
return 0;
}

Output:
Eating...
Walking...
Barking...
Explanation
• The `Animal` class has a function `eat()`.
• The `Mammal` class inherits from `Animal` and has a function `walk()`.
• The `Dog` class inherits from `Mammal` and has a function `bark()`.
• In the `main()` function, the `Dog` object can use all three functions: `eat()`

from `Animal`, `walk()` from `Mammal`, and `bark()` from `Dog`.

13. Describe the concept of abstract classes with suitable example


Definition
• Abstract classes are classes from which objects cannot be created directly.
• They define functions that derived-classes must implement.
21
• They have at least one pure virtual-function.

Features
• Cannot be Instantiated: Objects cannot be created from an abstract class.
• Pure Virtual-functions: They have at least one pure virtual-function, which is a function with no
definition.
• Defines Interface: They provide a common interface that derived-classes must follow.
• Encourages Reusability: They allow methods to be defined that can be reused and overridden in derived
classes.
Syntax
class AbstractClass {
public:
virtual void pureVirtualFunction() = 0; // Pure virtual-function
// Other members
};
Where,
AbstractClass: The class with at least one pure virtual-function.
pureVirtualFunction(): A pure virtual-function, marked with `= 0`.

Example Program: Demonstrating Abstract-Classes


#include <iostream>
#include <cmath> // For M_PI constant
using namespace std;
// Abstract base class
class Shape {
public:
// Pure virtual function for calculating area
virtual double calcArea() = 0;
};

// Derived class for Circle


class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
// Override calcArea to calculate the area of the circle
double calcArea() override {
return M_PI * radius * radius;
}
};
// Derived class for Rectangle
class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
// Override calcArea to calculate the area of the rectangle
double calcArea() override {
return length * width;
}
};
22
int main() {
// Create objects of derived classes
Circle myCircle(5.0);
Rectangle myRectangle(4.0, 6.0);
// Calculate and display areas
cout << "Area of Circle: " << [Link]() << endl;
cout << "Area of Rectangle: " << [Link]() << endl;
return 0;
}
Output:
Area of Circle: 78.5398

Area of Rectangle: 24

14. Explain the concept of formatted I/O with examples.


• Definition: Input- and output-operations where data is formatted according to
specific rules or styles before being written to or read from a stream.
Purpose
• To present data in a readable and structured format.
• To ensure data is aligned, padded, or displayed in a particular way according to user requirements.
Usage
• Formatted-I/O functions are used with output streams (cout) to control how data is formatted when
displayed.
• They can be applied to both numbers and text to ensure consistent and readable output.
• Description: This function sets the number of digits to display after the decimal point for floating-point
numbers in the output stream.
• Parameters:
`int n`: The number of digits to display
• Example Usage:
cout << setprecision(3) << 3.14159; // Outputs: 3.14
setw(int width)
• Description: This function sets the width of the next input/output field. If the data
is shorter than the specified width, it will be padded with spaces or another character
(set by `setfill()`).
• Parameters:
- `int width`: The width of the field for the next input/output operation.
• Example Usage:
cout << setw(10) << 123; // Outputs: " 123" (7 spaces before 123)
setfill(char c)
• Description: This function sets the fill character used to pad fields in the output stream. It is used in
conjunction with `setw()` to pad the output with a specific character instead of spaces.
• Parameters:
`char c`: The character used to pad the output field.
• Example Usage:

cout << setfill('*') << setw(10) << 1234; // Outputs:"1234" (padded with *)

15. Explain standard class functions for File I/O with suitable example.

The I/O system of C++ contains a set of classes which define the file handling methods. These include
ifstream, ofstream and fstream classes. These classes are derived from fstream and from the

23
corresponding iostream class. These classes, designed to manage the disk files, are declared in fstream and
therefore we must include this file in any program that uses files
1. ios:-
 ios stands for input output stream.
 This class is the base class for other classes in this class hierarchy.
 This class contains the necessary facilities that are used by all the other derived classes for input
and output operations.

2. istream:-
 istream stands for input stream.
 This class is derived from the class ‘ios’.
 This class handle input stream.
 The extraction operator(>>) is overloaded in this class to handle input streams from files to the
program execution.
 This class declares input functions such as get(), getline() and read().

3. ostream:-
 ostream stands for output stream.
 This class is derived from the class ‘ios’.
 This class handle output stream.
 The insertion operator(<<) is overloaded in this class to handle output streams to files from the
program execution.
 This class declares output functions such as put() and write().

4. streambuf:-
 This class contains a pointer which points to the buffer which is used to manage the input and
output streams.

5. fstreambase:-
 This class provides operations common to the file streams. Serves as a base for fstream, ifstream
and ofstream class.
 This class contains open() and close() function.

6. ifstream:-
 This class provides input operations.
 It contains open() function with default input mode.
 Inherits the functions get(), getline(), read(), seekg() and tellg() functions from the istream.

7. ofstream:-
 This class provides output operations.
 It contains open() function with default output mode.
 Inherits the functions put(), write(), seekp() and tellp() functions from the ostream.

8. fstream:-
 This class provides support for simultaneous input and output operations.
 Inherits all the functions from istream and ostream classes through iostream.

24
9. filebuf:-
 Its purpose is to set the file buffers to read and write.
 We can also use file buffer member function to determine the length of the file.

1. What is an expression? Give an example.


• An expression is combination of operands and operator that reduces to a single value.
• For examples: Simple expressions: `x + y`, `5 * z`
Complex expressions: `a + b * (c - d)`
• Expressions are used to perform computations, assign values, or compare values.

2. What is the purpose of the scope resolution operator (`::`) in C++?


• This operator is used to access global-variables from within local scopes such as
functions.
• Syntax: `
::variable_name`
• This operator is used to differentiate between local and global-variables with the
same name.
• This operator helps in accessing global-variables within any scope without ambiguity.

3. What is a constant? Give an example.


A constant is an identifier whose value remains fixed throughout the execution of the program.
• The constants cannot be modified in the program.
• For example:
1, 3.14512 , “z‟, “gcwmaddur"
Five different types of constants are:
1) Integer-constant
2) Floating-point-constant
3) Character-constant
4) String-constant
5) Escape Sequence Characters

4. What is recursion? Give an example.


• Recursion is a technique where a function calls itself repeatedly until a certain condition is met
• Basic idea of recursion:
1) Break a problem into smaller sub-problems until the sub-problems can be solved directly.
2) Then, combine the solutions of the sub-problems to get the solution of the original problem.
• Recursion requires a base-case and a recursive-case.
1) In base-case, the problem can be solved directly w/o recursion.
2) In recursive-case, the function calls itself with a smaller input. This makes the problem simpler and
closer to the base-case.
25
• Eventually, the recursive-case will lead to the base-case and the recursion will terminate.
• Recursive-functions can be slower and less memory efficient than iterative functions.
• Recursion can be used to solve following problems:
1) Finding GCD of 2 numbers
2) Generating Fibonacci numbers

5. Mention advantages of functions in C++.


Reusability: One of the main advantages of using functions in C++ is that they enable code to be reused,
which can save a great deal of time and effort. Functions can be written once and then called multiple
times throughout the program, making it much easier to maintain an application.

5. What are reference variables? Provide an example


• Reference-variables provide an alias (an alternative name) to an existing variable.
• Once initialized, a reference-variable remains bound to the same object throughout its lifetime.
Declaration and Initialization
• Declaring a reference-variable involves using an ampersand (`&`) symbol after the
type in the declaration.
Usage and Benefits
• They are particularly useful in function-parameters to pass variables by reference.
This enables functions to modify the original data
.
6. What is a parameterized constructor?
• A parameterized constructor takes one or more arguments.
Purpose
• It allows objects to be initialized with specific values.
Features
• It requires arguments to initialize variables.
• Multiple constructors with different arguments can be created (overloading).
• It initializes the object with the provided values.
Example
class Rectangle {
public:
Rectangle(int l, int w) { // Parameterized Constructor
length = l;
width = w;
}
private:
int length;
int width;
};

7. What is the role of static member data?


Static data members are class members that are declared using static keywords. A static member has
certain special characteristics which are as follows:

26
 Only one copy of that member is created for the entire class and is shared by all the objects of that
class, no matter how many objects are created.
 It is initialized before any object of this class is created, even before the main starts outside the
class itself.
 It is visible can be controlled with the class access specifiers.
 Its lifetime is the entire program.

Syntax
className {
static data_type data_member_name;
.....
}

8. What are member functions? Why are they used?


In C++, a member function is a function that is associated with a specific class or object. These functions
are defined within the class definition and provide the ability to perform operations on the class’s data
members and interact with other objects of the same class. They play a crucial role in the object-oriented
programming paradigm by allowing the encapsulation of implementation details and providing a way to
validate and manipulate the data stored within an object
Member-Functions can be defined in 2 ways
1) Inside the Class
• A Member-Function can be defined directly inside the class definition, which is known as an inline
definition.
2) Outside the Class
• A Member-Function can be declared inside the class and defined outside using the scope resolution
operator (::).

Types of Member-functions
• Accessor Functions: Used to retrieve the value of member-variables (often called "getters").
• Mutator Functions: Used to modify the value of member-variables (often called "setters").
• Utility Functions: Perform operations related to the class but may not directly modify member-variables.

9. What are access specifiers in C++?


Access-Specifiers
• Access-Specifiers determine the accessibility of the base-class-members in the derived-class.
i) public: Public-members of the base-class become public in the derived-class
ii) protected: Public- and protected-members of the base-class become protected in the derived-class
iii) private: Public- and protected-members of the base-class become private in the derived-class

Syntax
class BaseClass {
public:
// Base-class-members
};

27
class DerivedClass : public BaseClass {
public:
// Derived-class members
};

10. What is an abstract class?


Abstract classes are classes from which objects cannot be created directly.
• They define functions that derived-classes must implement.
• They have at least one pure virtual-function.
Features
• Cannot be Instantiated: Objects cannot be created from an abstract class.
• Pure Virtual-functions: They have at least one pure virtual-function, which is a function with no
definition.
• Defines Interface: They provide a common interface that derived-classes must follow.
• Encourages Reusability: They allow methods to be defined that can be reused and overridden in derived
classes.
Syntax
class AbstractClass {
public:
virtual void pureVirtualFunction() = 0; // Pure virtual-function
// Other members
};

11. What is hybrid inheritance?


Hybrid-Inheritance combines two or more types of inheritance in a single program.
• It mixes different inheritance styles, like single, multiple and multilevel.

Syntax
class BaseClass1 {
// Base-class 1 members
};
class BaseClass2 {
// Base-class 2 members
};
class IntermediateClass : public BaseClass1 {
28
// Intermediate class members
};
class DerivedClass : public IntermediateClass, public BaseClass2 {
// Derived-class members
};

1. Explain different data types in C++ with examples.

The data-type defines the type of data stored in a memory-location.


• C++ supports 3 classes of data-types:
1) Primary data-type e.g. int, flaot
These are the primary types used to define simple variables.
 Int : used for integers (Whole numbers)
 Float: used for single precision floating point numbers(decimal values)
 Double: used for double precision floating point members. More accurate that float
 Char: used to store single characters
 Bool: used to store Boolean values (true or false)

2) Derived data-types e.g. array


These types are derived from basic data types.
 Array: collection of items of the same data type
 Pointer: stores memory addresses of other variables
 Reference: Another name for an existing variable.
 Enumeration(enum): Defines a setoff named integer constants. Useful for variables that can
only take a specific set of values.

3) User defined data-types e.g. structure, class


These types allow you to define your own data types.
 Structure(Struct): Groups different data types together.
 Union: Like struct but members share the same memory.
 Class: Defines objects with properties and methods.

2. Describe the rules for naming identifiers in C++.


As the name indicates, identifier is used to identify various entities of program such as variables, constants,
functions etc.
• In other words, an identifier is a word consisting of sequence of
→ Letters
→ Digits or
→ "_"(underscore)
• For ex:
area, length, breadth

Here are the rules for naming identifiers:


1. Only Alphanumberic characters and underscores- Identifiers can contain letters (a-z , A-Z) digits (0-9)
and underscores.
Special characters are not allowed like @, !, ^,% etc.,
2. Cannot start with a Digit- identifiers cannot begin with a number. They must start with a letter or
an underscore.

29
3. Case-Sensitive – identifiers are case-sensitive meaning age, Age and AGE are considered different
identifiers.
4. Cannot use C++ Keywords – Keywords (such as int, return, for, class etc) cannot be used as
identifiers because they have predefined meanings in C++
5. No length Limit- C++ does not enforce a length limit for identifiers. However, using very long names
is generally discourages for readability.
6. Meaningful Names are Encouraged – while not strictly a rule, using descriptive names makes the
code easier to understand.

12. Explain looping statements in C++ with suitable examples.


In C++ looping statements allow code to be executed repeatedly based on a condition.
C++ provides three primary types for loops:
1. for Loop – The for loop is used when the number of iterations is known in advance. It has a definite
starting point, condition, and an increment, decrement loop.
Syntax: for(initialization; condition;increment;decrement)
{
Code to be executed
}

Example Programme:
#include<iostream.h>
#include<conio.h>
int main()
{
for(int i=0;i<=5;i++)
{
cout<< i<<” “;
}
Return 0;
}

2. while loop – The while loop is used when the number of iterations isn’t known in advance. It
continues to execute as long as the condition is true.

Syntax:
while(condition)
{
Code to be executed
}

Example Programme:
#include<iostream.h>
#include<conio.h>
int main()
int i=1;
while(i<=5)
{
cout<< i<<” “;
i++;
}
Return 0;
30
}

3. do-while loop – The do while loop is similar to the while loop but guarantees at least one execution
of the loop body, even if the condition is false.

do
{
Code to be executed
} while (condition);

Example Programme:
#include<iostream.h>
#include<conio.h>
int main()
int i=1;
do {
cout<< i<<” “;
i++;
}
while(i<=5);
Return 0;
}

13. Write a program that uses a switch statement to print the day of the week based on user input.

#include <stdio.h>
int main()
{
int week;

/* Input week number from user */


printf("Enter week number(1-7): ");
scanf("%d", &week);

switch(week)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
31
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
default:
printf("Invalid input! Please enter week number between 1-7.");
}
return 0;
}

14. Explain function overloading with examples.


Function overloading is a feature of object-oriented programming where two or more functions can have
the same name but different parameters. When a function name is overloaded with different jobs it is
called Function Overloading. In Function Overloading “Function” name should be the same and the
arguments should be different. Function overloading can be considered as an example of a polymorphism
feature in C++.

#include <iostream>
using namespace std;

void add(int a, int b)


{
cout << "sum = " << (a + b);
}

void add(double a, double b)


{
cout << endl << "sum = " << (a + b);
}

// Driver code
int main()
{
add(10, 2);
add(5.3, 6.2);

return 0;
}

(a2) Discuss the role of friend functions in C++ with an example.


Friend function in C++ is the creative function that breaks the data hiding in an object-oriented
programming language. The data hiding prevents the access of private members externally from the class.
The protected members are inaccessible from the outside and can only be accessed by the derived classes.

Syntax of Friend Function in C++

You can declare the friend function using the keyword “friend” inside the body of the class.

class Box {
double width;
32
public:
double length;
friend void printWidth ( Box box ) ;
void setWidth ( double wid ) ;
};

Example program:

#include <iostream>
using namespace std;
class Distance {
private:
int meter;
// friend function
friend int addFive(Distance);
public:
Distance() : meter(0) {}
};
// friend function definition
int addFive(Distance d) {
//accessing private members from the friend function
[Link] += 5;
return [Link];
}
int main() {
Distance D;
cout << "Distance: " << addFive(D);
return 0;
}

Output: Distance 5

(b1) Describe the process of initializing and accessing elements in a two-dimensional array with an
example.

In c++ a two dimensional array is essentially an array of arrays. To initialize and access elements in a 2D
array, follow these steps:
1. Declare and initialize the array:
To declare a 2D array, specify the number of roows and coloumns.
Syntax:
In array [3][3] – three rows and three coloumns
Each element in this 3 X 3 array can be accessed using two indices; one for the row and one for the
coloumn.

We can initialize the array with values directly using nested braces.
33
Int array[3][3]
{
[1,2,3}
{4,5,6}
{7,8,9}
};

Accessing Elements: to access or modify an element in a 2D array, use the indices in the format array[row]
[coloumn].

Example Program:
#include<iostream.h>
#include<conio.h>
int main()
{
Int array[3][3]
{
{[1,2,3}
{4,5,6}
{7,8,9}
};

for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++
{
cout<<”array”<<i<<”||”<<j<<”||”<<array[i][j]<<endl;
}
}
Return 0;
}

(b2) Explain arrays of structures with an example program.


• An array of structures is a collection of structures of the same type.
• This allows storing multiple records of structured data in a single array.
• It is useful when you need to manage and manipulate a collection of records, such as a list of students,
employees, or products.

• Program to illustrate use of Array of Structures


#include <iostream>
#include <string> // Include the string library
struct Person {
string name;
int cit_no;
float salary;
};

int main() {
// Initialize an array of structures
Person people[3] = {
{"Arjuna", 1, 88000},
34
{"Krishna", 2, 92000},
{"Bhima", 3, 79000}
};

// Print details of each person


for (int i = 0; i < 3; ++i) {
cout << "Person " << (i + 1) << " details:" << endl;
cout << "Name: " << people[i].name << endl;
cout << "Citizen Number: " << people[i].cit_no << endl;
cout << "Salary: " << people[i].salary << endl << endl;
}
return 0;
}

Output:
Person 1 details:
Name: Arjuna
Citizen Number: 1
Salary: 88000

Person 2 details:
Name: Krishna
Citizen Number: 2
Salary: 92000

Person 3 details:
Name: Bhima
Citizen Number: 3
Salary: 79000

4. What are the features of object-oriented programming? Explain each feature briefly.

Object-oriented programming aims to implement real-world entities like inheritance, hiding,


polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions
that operate on them so that no other part of the code can access this data except that function.

There are some basic features of OOPs i.e.

 Class
 Object
 Encapsulation
 Abstraction
 Polymorphism
 Inheritance
 Dynamic Binding
 Message Passing

Class = The building block of C++ that leads to Object-Oriented programming is a Class. It is a user-defined
data type, which holds its own data members and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an object.

35
Object = An Object is an identifiable entity with some characteristics and behavior. An Object is an instance
of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is
created) memory is allocated.

Encapsulation = Encapsulation is defined as wrapping up data and information under a single unit. In
Object-Oriented Programming, Encapsulation is defined as binding together the data and the functions
that manipulate them.

Abstraction = Data abstraction is one of the most essential and important features of object-oriented
programming in C++. Abstraction means displaying only essential information and hiding the details.

Polymorphism = The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A person at the same
time can have different characteristics.

Inheritance = The capability of a class to derive properties and characteristics from another class is called
Inheritance. Inheritance is one of the most important features of Object-Oriented Programming.

Dynamic binding = In dynamic binding, the code to be executed in response to the function call is decided
at runtime. C++ has virtual functions to support this. Because dynamic binding is flexible, it avoids the
drawbacks of static binding, which connected the function call and definition at build time.

Message passing = Objects communicate with one another by sending and receiving information. A
message for an object is a request for the execution of a procedure and therefore will invoke a function in
the receiving object that generates the desired results. Message passing involves specifying the name of
the object, the name of the function, and the information to be sent.

(a2) Describe the concept of dynamic constructor with an example.


• A dynamic constructor allocates memory at runtime using the `new` keyword.

Purpose
• Memory for variables is allocated when an object is created.

Features
• It uses `new` to allocate memory for data members.
• A destructor is typically defined to free memory using `delete`.
• It allows the object to manage its own memory based on runtime needs.

Example
class Rectangle {
public:
Rectangle(int l, int w) { // Dynamic Constructor
length = new int(l);
width = new int(w);
}
~Rectangle() { // Destructor to release memory
delete length;
delete width;
}
private:
int *length;
int *width;
36
};

(b1) Describe how unary operator overloading is implemented in C++.

Overloading operators that take a single operand.


Examples: +, -, ++, --, !, ~
• Purpose: To extend the functionality of unary operators to work with objects.
• Typically, the unary operator is implemented as a member function.
Syntax:
ReturnType operator op();
Where:
- `ReturnType`: The type of value that the operator will return.
- `operator op`: The operator being overloaded. It does not take any parameters other than the implicit
`this` pointer.

Example: Program to complement a complex number

#include <iostream>
class Complex {
private:
int real, imag;
public:
// Overloading unary `-` operator
Complex operator-() const {
return Complex(-real, -imag);
}
// Function to display complex number
void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
// Create a Complex object
Complex c1(4, 5);
cout << "Original Complex number: ";
[Link]();
Complex c2 = -c1; // Apply unary `-` operator
cout << "After applying unary `-` operator: ";
[Link]();
return 0;
}
Output:
Original Complex number: 4 + 5i
After applying unary `-` operator: -4 + -5i

(b2) Explain array of objects with suitable program.

• Definition: An array of objects is a collection of objects of the same class stored in contiguous memory-
locations.
• Each element in the array is an object that can have its own attributes and methods.

37
• Example: Demonstrating Array of Objects

#include <iostream>
using namespace std;
// Class definition
class Rectangle {
public:
double length;
double width;
// Member method to calculate the area of the rectangle
double calculateArea() const {
return length * width;
}
};
int main() {
Rectangle rects[3]; // Array of 3 Rectangle objects
// Set dimensions for each rectangle
rects[0].length = 4.0;
rects[0].width = 2.0;
rects[1].length = 6.0;
rects[1].width = 3.0;
rects[2].length = 5.0;
rects[2].width = 5.0;
// Display area for each rectangle
for (int i = 0; i < 3; i++) {
cout << "Rectangle " << i+1 << " Area: " << rects[i].calculateArea() << endl;
}
return 0;
}
Output:
Rectangle 1 Area: 8
Rectangle 2 Area: 18
Rectangle 3 Area: 25

16. Explain multiple and hierarchical inheritance with examples.

Multiple-Inheritance allows a class to inherit from more than one base-class.


This helps the derived-class to use features from multiple-classes.

38
Features
• Combining Features: The derived-class can use features from all its base-classes.
This makes it flexible.
• Complex Relationships: It helps create more complex class-structures.
• Avoiding Redundancy: Common features from different classes can be combined
in one class. This reduces repeated-code.
• Conflict Resolution: If two base-classes have functions with the same name, the
derived-class must decide which one to use.
Syntax
class BaseClass1 {
// Base-class 1 members
};
class BaseClass2 {
// Base-class 2 members
};
class DerivedClass : public BaseClass1, public BaseClass2 {
// Derived-class members
};
Where,
BaseClass1: The first base-class.
BaseClass2: The second base-class.

Example Program: Demonstrating Multiple-Inheritance


#include <iostream>
// First base-class
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};
// Second base-class
class Bird {
public:
void fly() {
cout << "Flying..." << endl;
}
};
// Derived-class
class Bat : public Animal, public Bird {
public:
void sleep() {
cout << "Sleeping..." << endl;
}
};
int main() {
Bat myBat;
[Link](); // Inherited from Animal class
[Link](); // Inherited from Bird class
[Link](); // Defined in Bat class
return 0;
}
39
Output:
Eating...
Flying...
Sleeping...

• Hierarchical-Inheritance is when multiple derived-classes inherit from the same


base-class.
• This lets different classes share features of one common class.

Features
• Shared Base-class: Different derived-classes use the features of the same baseclass.
• Code Reusability: Common code in the base-class is reused by all derived-classes.
This reduces repeated-code.
• Organized Structure: It organizes related classes under one base-class, making
the structure clear.
• Extended Functionality: Each derived-class can add features while still inheriting
from the base-class.
Syntax
class BaseClass {
// Base-class-members
};
class DerivedClass1 : public BaseClass {
// Derived-class 1 members
};
class DerivedClass2 : public BaseClass {
// Derived-class 2 members
};
Where,
BaseClass: The class from which other classes inherit.
DerivedClass1: A class that inherits from BaseClass.
DerivedClass2: Another class that inherits from Baseclass

(a2) Discuss the role of virtual functions in achieving polymorphism.

Definition
• Virtual-functions are functions in a base-class that can be overridden in derived classes.
• They enable dynamic (runtime) polymorphism, where the function called depends
on the type-of-object.

40
Features
• Dynamic Polymorphism: Allows base-class pointers to call derived-class methods.
• Function Overriding: Lets derived-classes provide their own version of a baseclass
method.
• Base-class Pointer: A base-class pointer can be used to call functions in derived
classes.
• Virtual Table (vtable): Stores pointers to virtual-functions, supporting their
dynamic behavior.
Syntax
class BaseClass {
public:
virtual void virtualFunction() {
// Base-class implementation
}
};
class DerivedClass : public BaseClass {
public:
void virtualFunction() override {
// Derived-class implementation
}
};

Where,
BaseClass: Contains a virtual-function.
virtual void virtualFunction(): Marks the function as virtual.
DerivedClass: Provides its own implementation of the virtual-function.

#include<iostream>
using namespace std;

class A //superclass A
{
public:
void show_A() {
cout<<"class A"<<endl;
}
};
class B : public A //subclass B
{
public:
void show_B() {
41
cout<<"class B"<<endl;
}
};

class C : public A //subclass C


{
public:
void show_C() {
cout<<"class C"<<endl;
}
};

int main() {
B b; // b is object of class B
cout<<"calling from B: "<<endl;
b.show_B();
b.show_A();

C c; // c is object of class C
cout<<"calling from C: "<<endl;
c.show_C();
c.show_A();
return 0;
}

Output
calling from B:
class B
class A
calling from C:
class C
class A

(b1) Explain the concept of unformatted I/O with examples.


Input- and output-operations where data is read or written without applying any specific formatting-rules.
The data is transferred in its raw, unmodified form.
Purpose
• To perform simple, direct input- and output-operations without any concern for how the data is
presented or formatted.
• Useful for efficient, low-level data handling where formatting is not necessary.
Usage
• Often used when handling binary-data or performing low-level file operations.
• Provides more control over how data is managed and transferred, without altering its format.

getline(istream &input, string &str, char delim = '\n');


• Description: This function reads a line-of-text from the input-stream and stores it in a string.
It reads until it encounters a newline-character (`'\n'`) or the end of the file, and then discards the newline-
character.
• Parameters:
`istream &input`: The input-stream from which the line is read (e.g., `cin`).
`string &str`: A reference to a `string` variable where the line-of-text will be stored.

42
`char delim` (optional): A delimiter-character that specifies where the input should stop. By default, it is `'\
n'`.

get(char &ch)
• Description: This function reads a single character from the input-stream and stores it in the variable `ch`.
• Parameters:
`char &ch`: A reference to a `char` variable where read character will be stored put(char ch)
• Description: This function writes a single character to the output stream.
• Parameters:
`char ch`: The character to be written to the output stream.

read(char *buffer, streamsize count);`


• Description: This function reads a block of characters from the input-stream and stores them in the array
pointed to by `buffer`.
• Parameters:
`char *buffer`: A pointer to a character-array where the read characters will be stored.
`streamsize count`: The maximum number of characters to read.
write(const char *buffer, streamsize count)
• Description: This function writes a block of characters from the array pointed to by `buffer` to the output
stream.
• Parameters:
`const char *buffer`: A pointer to a character-array containing the data to be written.
`streamsize count`: The number of characters to write.

(b2) Explain ios class functions and flags with suitable example.
• Definition: The `ios` class is a Base-class for streams like `istream`, `ostream`,and `fstream`.
• It provides functions and flags to manage stream operations.
Table: ios Class Functions

Table: ios Class Flags


43
44
1. Mention the steps in C++ program execution?
Translating the source code (high-level language code) into machine-readable code consists of the
following four processes:

1. Pre-processing the source code.


2. Compiling the source code.
3. Assembling the compiled file.
4. Linking the object code file to create an executable file.

2. What is a variable? Give an example.


A variable is an identifier whose value can be changed during execution of the program.
In other words, a variable is a name given to a memory-location where the data can be stored.
• Using the variable-name, the data can be
→ stored in a memory-location and
→ accessed or manipulated

RULES FOR DEFINING A VARIABLE


1) The first character in the variable should be a letter or an underscore(‘_’)
2) The first character can be followed by letters or digits or underscore
3) No extra symbols are allowed (other than letters, digits and underscore)
4) Length of a variable can be up to a maximum of 31 characters
5) Keywords should not be used as variable-names

Valid variables:
z, principle_amount, gcw_maddur
Invalid variables:
3fact //violates rule 1
sum= sum-of-digits dollar$ //violates rule 3
for int if //violates rule 5

3. What is character set? Give an example.


• Character-set refers to the set of alphabets, letters and some special-characters that are valid in C++
language.
• For example, the characters in C++ are:
→ Letters A-X, a-z, both upper and lower
→ Digits 0-9
→ Symbols such as + - * / %
→ White spaces

4. What are strings? Give an example.


Definition

45
• A string is an array of characters (`char`).
• It represents a sequence of characters stored in contiguous memory-locations.
• Strings are terminated by a null-character (`'\0'`), which marks the end of the string.

Declaration and Initialization


• Strings can be declared and initialized using C-style character arrays or using `string`.
• Example:
char s[10] = "rama"; // C-style string
string s = "rama"; // string
• The above code can be pictorially represented as shown below:

5. What are library functions? Give an example.

• In C++, functions are categorized into two types:


1) Library Function
• Library functions are built-in functions provided by the C++ standard-library.
• Examples:
`main()`, which is where every C++ program begins execution
`cout` for output
`cin` for input

6. What is the purpose of a default argument in functions?

• In C++, you can assign default-values to function-parameters. This allows some or all arguments to have
predefined-values.
• This feature is helpful when you want to provide a default behavior if the user does not specify values for
certain arguments.

• Syntax:
returnType functionName(type arg1 = defaultValue1, type arg2 = defaultValue2, ...) {
// Function-body
// Use arg1, arg2, and other arguments
}
Where:
`arg1`, `arg2`, etc.: These are the function-parameters for which defaultvalues
are specified.
`defaultValue1`, `defaultValue2`, etc.: These values are assigned as defaults for the respective parameters.

7. What is a copy constructor?

Definition
• A copy constructor creates a new object by copying an existing one.
Purpose
• It ensures that all values from the original object are copied to the new one.
Features
• It takes one argument, which is a reference to an object of the same class.
46
• If the object has pointers, the copy constructor can create new memory (deep copy).
• If not defined, the compiler provides a basic version (shallow copy).
Example
class Rectangle {
public:
Rectangle(const Rectangle &rect) { // Copy Constructor
length = [Link];
width = [Link];
}
private:
int length;
int width;

};
};
8. What is the difference between public and private members in a class?

Public Private
All the class members declared under public will be The class members declared as private can be
available to everyone. accessed only by the functions inside the class.
Only the member functions or the friend functions
The data members and member functions declared
are allowed to access the private data members of a
public can be accessed by other classes too.
class.
The public members of a class can be accessed from
They are not allowed to be accessed directly by any
anywhere in the program using the direct member
object or function outside the class.
access operator (.) with the object of that class.

9. Write the syntax of operator overloading function.

Operator overloading allows custom behaviors to be defined for


operators when used with objects of user-defined classes.
• Purpose: It enables the use of traditional operators like +, -, *, and == with objects.

Syntax:

Class className{
……..
public:

returnType operator symbol(arguments){


……
}
…..
};
10. What are text and binary files?

Aspect Text Files Binary Files


Content Human-readable text Non-human-readable data
Representation Characters and character encodings Binary code (0s and 1s)

47
Aspect Text Files Binary Files
Examples .txt, .html, source code files .jpg, .mp3, .exe, .pdf, .avi, .zip
Readability Easily understandable Appears as gibberish
Editability Can be edited directly Typically requires specialized software

11. What are formatted I/O operations?

C++ helps you to format the I/O operations like determining the number of digits to be displayed after the
decimal point, specifying number base etc.

Example:

 If we want to add + sign as the prefix of out output, we can use the formatting to do so:

[Link](ios::showpos)
If input=100, output will be +100

 If we want to add trailing zeros in out output to be shown when needed using the formatting:

[Link](ios::showpoint)
If input=100.0, output will be 100.000

There are two ways to do so:

1. Using the ios class or various ios member functions.


2. Using manipulators(special functions)

1. Explain arithmetic, relational and logical expressions with suitable examples.

• An expression is combination of operands and operator that reduces to a singlevalue.


• For examples: Simple expressions: `x + y`, `5 * z`
Complex expressions: `a + b * (c - d)`
• Expressions are used to perform computations, assign values, or compare values.
3.2.1 ARITHMETIC EXPRESSIONS
• Arithmetic expressions performs basic arithmetic operations on numeric data-types
(`int`, `float`).

Program to illustrate the use of Arithmetic Expressions.


#include <iostream>
using namespace std;
int main() {
int a = 9, b = 4, c;
c = a + b;
cout << "a+b=" << c << endl;
c = a - b;
cout << "a-b=" << c << endl;
return 0;
}
Output:
a+b=13
a-b=5

48
RELATIONAL-EXPRESSIONS
• Relational-expressions compare two values and return a Boolean result (`true` or
`false`).
• They are used in decision-making statements like `if`, `while`, and `for` loops:

Program to illustrate the use of Relational-expressions.


#include <iostream>
using namespace std;
int main() {
cout << "4>5 : " << (4 > 5) << endl;
cout << "4>=5 : " << (4 >= 5) << endl;
return 0;
}
Output:
4>5 : 0
4>=5 : 0
4<5 : 1

LOGICAL-EXPRESSIONS
• Logical-expressions combine multiple conditions using logical operators (`&&`,
`||`, `! `).
• They evaluate to `true` or `false` based on the truth values of their operands.

Program to illustrate the use of Logical-expressions.


#include <iostream>
using namespace std;
int main() {
cout << "7 && 0 : " << (7 && 0) << endl;
cout << "7 || 0 : " << (7 || 0) << endl;
return 0;
}
Output:
7 && 0 : 1
7 || 0 : 1

(a2) Explain control structures in C++ with suitable examples.

A program is nothing but the execution of sequence of one or more instructions.


• Quite often, it is desirable to change the order of execution of statements based on certain conditions
• This involves a kind of decision making to see whether a particular condition has occurred or not and
direct the computer to execute certain statements accordingly.
• Based on application, it is necessary / essential
i) To alter the flow of a program
ii) Test the logical conditions
iii) Control the flow of execution as per the selection.
• These conditions can be placed in the program using decision-making statements.

C++ SUPPORTS MAINLY THREE TYPES OF CONTROL STATEMENTS

49
1) Decision making statements = Decision making is critical to computer programming. There will be many
situations when you will be given 2 or more options and you will have to select an option based on the
given conditions.

There are 5 types of decision-statements:


i) if statement = This is basically a “one-way” decision-statement.
• This is used when we have only one alternative.
• Syntax:
if(expression)
{
statement1;
}

ii) if else statement = • This is basically a “two-way” decision-statement.


• This is used when we must choose between two alternatives.
• Syntax:
if(expression)
{
statement1;
}
else
{
statement2;
}

iii) nested if statement = • An if-else statement within another if-else statement is called nested if
statement.
• This is used when an action has to be performed based on many decisions. Hence, it is called as multi-
way decision-statement.
• Syntax:
if(expr1)
{
if(expr2)
statement1
else
statement2
}
else
{
if(expr3)
statement3
else
statement4
}

iv) else if ladder =This is basically a “multi-way” decision-statement.


• This is used when we must choose among many alternatives.
• Syntax:
if(expression1)
statement1;
else if(expression2)
statement2;
50
else if(expression3)
statement3
else if(expression4)
statement4
else
default statement5
• The expressions are evaluated in order (i.e. top to bottom).
• If an expression is evaluated to true, then
→ statement associated with the expression is executed &
→ control comes out of the entire else if ladder

v) switch-statement =• This is basically a “multi-way” decision-statement.


• This is used when we must choose among many alternatives.
• The syntax & flow diagram is shown below:

2) Loop control statements = Loops are used to execute one or more statements repeatedly

1. for Loop – The for loop is used when the number of iterations is known in advance. It has a definite
starting point, condition, and an increment, decrement loop.
Syntax: for(initialization; condition;increment;decrement)
{
Code to be executed
}

Example Programme:
#include<iostream.h>
#include<conio.h>
int main()
{
for(int i=0;i<=5;i++)
{
cout<< i<<” “;
}
Return 0;
}
51
2. while loop – The while loop is used when the number of iterations isn’t known in advance. It
continues to execute as long as the condition is true.

Syntax:
while(condition)
{
Code to be executed
}

Example Programme:
#include<iostream.h>
#include<conio.h>
int main()
int i=1;
while(i<=5)
{
cout<< i<<” “;
i++;
}
Return 0;
}

3. do-while loop – The do while loop is similar to the while loop but guarantees at least one execution
of the loop body, even if the condition is false.

do
{
Code to be executed
} while (condition);

Example Programme:
#include<iostream.h>
#include<conio.h>
int main()
int i=1;
do {
cout<< i<<” “;
i++;
}
while(i<=5);
Return 0;
}

3) Unconditional control statements


i) break statement = The break statement is jump-statement which can be used in switch-statement and
loops.
• The break statement works as shown below:
1) If break is executed in a switch-block, the control comes out of the switch-block and the statement
following the switch-block will be executed.
2) If break is executed in a loop, the control comes out of the loop and the statement following the loop
will be executed
52
ii) continue statement = During execution of a loop, it may be necessary to skip a part of the loop based on
some condition. In such cases, we use continue statement.
The continue statement is used only in the loop to terminate the current iteration

(b1) Explain the break and continue statements with suitable examples. (8 Marks)
THE break STATEMENT
• The break statement is jump-statement which can be used in switch-statement and
loops.
• The break statement works as shown below:
1) If break is executed in a switch-block, the control comes out of the switch-block
and the statement following the switch-block will be executed.
2) If break is executed in a loop, the control comes out of the loop and the statement
following the loop will be executed.

• Program to illustrate usage of break statement.


#include <iostream>
int main() {
for (int i = 1; i <= 10; ++i) {
if (i == 5) {
cout << "Breaking the loop at i = 5" << endl;
break;
}
cout << i << " ";
}
return 0;
}
Output:
1 2 3 4 Breaking the loop at i = 5

• During execution of a loop, it may be necessary to skip a part of the loop based on
some condition. In such cases, we use continue statement.
• The continue statement is used only in the loop to terminate the current iteration.

Program to read and add only positive numbers using continue statement.
#include <iostream>
using namespace std;
int main() {
int i = 1, num, sum = 0;
for (i = 0; i < 5; i++) {
cout << "Enter an integer: ";
cin >> num;
if (num < 0) {
cout << "You have entered a negative number" << endl;
continue; // skip the remaining part of loop
}
sum = sum + num;
}
cout << "The sum of the positive integers entered = " << sum << endl;
return 0;
}
Output:
53
Enter an integer: 10
Enter an integer:-15
You have entered a negative number
Enter an integer: 15
Enter an integer: -100
You have entered a negative number
Enter an integer: 30
The sum of the positive integers entered = 55

(b2) Describe the rules for precedence and associativity of operators in C++.
Operator precedence specifies the order of operations in expressions that contain more than one
operator. Operator associativity specifies whether, in an expression that contains multiple operators with
the same precedence, an operand is grouped with the one on its left or the one on its right.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear
at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

Describe the general structure of a function with an example. (8 Marks)

A function is a block of code to perform a specific-task.


• Every C++ program has at least one function main().
• Without main() function, there is technically no C++ program .
• The function can take one or more arguments.
• The function can also return-values using the `return` statement.

CLASSIFICATION (TYPES) OF FUNCTIONS


• In C++, functions are categorized into two types:
1) Library Function
• Library functions are built-in functions provided by the C++ standard-library.
• Examples:
`main()`, which is where every C++ program begins execution
`cout` for output
54
`cin` for input
2) User-Defined-Function
• C++ allows programmers to define their own functions according to their specific
requirements. These functions are called user-defined-functions.
• For example, if a programmer needs to calculate the factorial of a number, they can
create separate user-defined-function.

STRUCTURE OF USER-DEFINED-FUNCTIONS
#include <iostream> // C++ standard input/output library
void function_name(); //function-declaration
int main()
{
...........
...........
function_name(); // function-call
...........
...........
}
void function_name() //function-definition
{
................
................
}
• Every C++ program begins from main().
• Program starts executing the codes inside main() function.
• When the control of program reaches to function_name() inside main() function, the
control of program jumps to void function_name() and executes the codes inside it.
• When all the codes inside that user-defined-function are executed, control of the
program jumps to the statement just after function_name() from where it is called.

(a2) What is a pointer? Explain its declaration and initialization.


• A pointer is a variable which holds address of another variable or a memorylocation.
• For ex:
c=22;
pc=&c;
Here pc is a pointer; it can hold the address of variable c
& is called reference operator

DECLARATION & INITIALIZATION OF POINTER VARIABLE


• Dereference operator(*) are used for defining pointer-variable.
• Syntax:
data_type *ptr_var_name;
• For ex:
int *a; // a as pointer variable of type int
55
float *c; // c as pointer variable of type float
• Steps to access data through pointers:
1) Declare a data-variable ex: int c;
2) Declare a pointer-variable ex: int *pc;
3) Initialize a pointer-variable ex: pc=&c;
4) Access data using pointer-variable ex: cout << *pc

Program to illustrate working of pointers.


#include <iostream>
int main() {
int *pc;
int c;
c = 22;
cout << "Address of c: " << &c << endl;
cout << "Value of c: " << c << endl;
pc = &c;
cout << "Address of pointer pc: " << pc << endl;
cout << "Content of pointer pc: " << *pc << endl;
return 0;
}
Output:
Address of c: 1232
Value of c: 22
Address of pointer pc: 1232
Content of pointer pc: 22

(b1) Describe the process of declaring and accessing elements of structure with suitable example.
Structure is a collection of elements of different data-type.
• Syntax:
struct structure_name
{
data_type member1;
data_type member2;
data_type member3;
};
• The variables that are used to store the data are called members of the structure.
• For example:
struct Person
{
string name;
int cit_no;
float salary;
};

STRUCTURE-VARIABLE DECLARATION
• When you declare a structure-variable, you define an instance of that structure
type.
• Syntax:
struct StructureName variableName;
• Example:
struct person p1, p2;

56
STRUCTURE-VARIABLE INITIALIZATION
• Structure-variables can be declared and initialized at the time of declaration or
separately.
• Syntax:
struct StructureName variableName = {value1, value2, ...};
• Example:
struct Person p1 = {"rama", 24, 23000};

ACCESSING MEMBERS OF A STRUCTURE


• Members of a structure are accessed using the member-access-operator (.).
• Syntax:
[Link]
• Example:
cout << "Name: " << [Link] << endl;
• Here the above statement accesses and prints the name member of structure p1.

(b2) Discuss the concept of recursion in C++ with an example.

Recursion is a technique where a function calls itself repeatedly until a certain condition is met
• Basic idea of recursion:
1) Break a problem into smaller sub-problems until the sub-problems can be solved directly.
2) Then, combine the solutions of the sub-problems to get the solution of the original problem.
• Recursion requires a base-case and a recursive-case.
1) In base-case, the problem can be solved directly w/o recursion.
2) In recursive-case, the function calls itself with a smaller input. This makes the problem simpler and
closer to the base-case.
• Eventually, the recursive-case will lead to the base-case and the recursion will terminate.
• Recursive-functions can be slower and less memory efficient than iterative functions.
• Recursion can be used to solve following problems:
1) Finding GCD of 2 numbers
2) Generating Fibonacci numbers

Program to find GCD using Recursive-function


#include <iostream>
using namespace std;
int gcd(int x, int y) {
if (y == 0) {
return x;
} else {
return gcd(y, x % y);
}
}
int main() {
int x, y, result;
cout << "Enter two positive integers: ";
cin >> x >> y;
result = gcd(x, y);
cout << "The GCD of " << x << " and " << y << " is " << result << endl;
return 0;
}
Output:
Enter two positive integers: 30 12
57
The GCD of 30 and 12 is 2

15. (a1) Define class and object. Write a C++ program to illustrate the use of classes and objects.
(Refer above model paper for answer)

(a2) Explain the concept of parameterized constructors with an example.

Definition
• A parameterized constructor takes one or more arguments.
Purpose
• It allows objects to be initialized with specific values.
Features
• It requires arguments to initialize variables.
• Multiple constructors with different arguments can be created (overloading).
• It initializes the object with the provided values.
Example
class Rectangle {
public:
Rectangle(int l, int w) { // Parameterized Constructor
length = l;
width = w;
}
private:
int length;
int width;
};

Example program
#include <iostream>
#include <string.h>
using namespace std;

// class definition
class student {
int rno;
char name[50];
double fee;

public:
student(int, char[], double);
void display();
};

// parameterized constructor outside class


student::student(int no, char n[], double f)
{
rno = no;
strcpy(name, n);
fee = f;
}
void student::display()
{
58
cout << endl << rno << "\t" << name << "\t" << fee;
}

// driver code
int main()
{
student s(1001, "Ram", 10000);
[Link]();
return 0;
}

Output
1001 Ram 10000

(b1) Describe the different ways to define member functions in C++ and provide a suitable example.
In C++, a member function is a function that is associated with a specific class or object. These functions
are defined within the class definition and provide the ability to perform operations on the class’s data
members and interact with other objects of the same class. They play a crucial role in the object-oriented
programming paradigm by allowing the encapsulation of implementation details and providing a way to
validate and manipulate the data stored within an object

Member-Functions can be defined in 2 ways


1) Inside the Class = A Member-Function can be defined directly inside the class definition, which is known
as an inline definition.
class MyClass {
public:
int x;
void assign(int value){
x=value;
}};

#include<iostream.h>
#include<conio.h>
class MyClass
{
public:
Int data=5;
void printData()
{
Cout<<”Data”<<data;
}};
int main()
{
MyClass obj;
[Link]();
return 0; }
2) Outside the Class

59
• A Member-Function can be declared inside the class and defined outside using the scope resolution
operator (::).

void MyClass::myFunction(){
//function body
}
#include<iostream>
class MyClass
{
Public;
Int data=5;
Void printData();
};
Void MyClass::printData()[
Cout<<”Data”<<data;
}
int main()
{
MyClass obj;
[Link]();
return 0;
}

(b2) Explain the concept of static member data and functions with suitable example.

Static members of a class are not associated with the objects of the class. Just like a static variable once
declared is allocated with memory that can’t be changed every object points to the same memory.

Example:

class Person{
static int index_number;
};

Static member functions in C++ are special functions associated with a class that belongs to the class itself
rather than to any specific object of the class. A member function is declared static using the static
keyword, just like when defining static data members. // This function is a static member function.

#include <iostream>
using namespace std;

class Box
{
private:
static int length;
static int breadth;
static int height;

public:
60
static void print()
{
cout << "The value of the length is: " << length << endl;
cout << "The value of the breadth is: " << breadth << endl;
cout << "The value of the height is: " << height << endl;
}
};

// initialize the static data members

int Box :: length = 10;


int Box :: breadth = 20;
int Box :: height = 30;

// Driver Code

int main()
{

Box b;

cout << "Static member function is called through Object name: \n" << endl;
[Link]();

cout << "\nStatic member function is called through Class name: \n" << endl;
Box::print();

return 0;
}

17. (a1) Explain hybrid and multi-path inheritance with an example.


• Hybrid-Inheritance combines two or more types of inheritance in a single program.
• It mixes different inheritance styles, like single, multiple and multilevel.

Syntax
class BaseClass1 {

61
// Base-class 1 members
};
class BaseClass2 {
// Base-class 2 members
};
class IntermediateClass : public BaseClass1 {
// Intermediate class members
};
class DerivedClass : public IntermediateClass, public BaseClass2 {
// Derived-class members
};

Definition
• Multi-Path Inheritance happens when a class inherits from multiple base-classes.
• These base-classes might also have a common base-class.
• This creates multiple-paths of inheritance.

Syntax
class BaseClass {
// Base-class-members
};
class BaseClass1 : public BaseClass {
// Base-class 1 members
};
class BaseClass2 : public BaseClass {
// Base-class 2 members
};
class DerivedClass : public BaseClass1, public BaseClass2 {
// Derived-class members
};

Describe the purpose of virtual base classes in C++ with an example.


• Virtual Base-classes make sure there is only one instance of a base-class when
using multiple-Inheritance.
• This avoids having multiple copies of the same base-class.
Features
• Single Instance: Ensures only one instance of the virtual base-class is created.
• Solves Diamond Problem: Fixes the diamond problem where a base-class is
inherited through multiple-paths.
• Reduces Ambiguity: Avoids confusion by keeping one copy of base-class data.
62
• Consistency: Keeps behavior consistent by sharing the same base-class instance.

Syntax
class BaseClass {
// Base-class-members
};
class DerivedClass1 : virtual public BaseClass {
// Derived-class 1 members
};
class DerivedClass2 : virtual public BaseClass {
// Derived-class 2 members
};
class FinalDerivedClass : public DerivedClass1, public DerivedClass2 {
// Final derived-class members
};
Where,
BaseClass: The virtual base-class.
DerivedClass1: Inherits from BaseClass as a virtual base-class.
DerivedClass2: Also inherits from BaseClass as a virtual base-class.
FinalDerivedClass: Inherits from both DerivedClass1 and DerivedClass2, using
only one instance of BaseClass.

(b1) Explain built in classes for I/O with an example. (8 Marks)


Definition
• Built-in Classes for I/O handle input and output-operations.
• These classes simplify file and console I/O.
Features
• Stream-Based I/O: I/O-classes use streams to manage data flow.
This provides a consistent way to handle data from different sources like the console or files.
• Overloaded Operators: I/O-classes support overloaded operators.
The `<<` operator is used for output, and the `>>` operator is used for input.
This makes it easy to format and handle data.
• Common built-in classes are listed in below table:
1) `iostream`
2) `istream`
3) `ostream`
1) `iostream`
• Description: The Base-class for input and output-stream classes.
• It provides functionalities for both input and output-operations.
• Derived-classes:
`istream`: For input-operations.
`ostream`: For output-operations.
2) `istream`
• Description: A class for input-stream operations.
• It is used for reading data from input-sources like the keyboard or files.
• Common Functions:
`>>` (extraction-operator) for reading formatted data.
`getline()` for reading lines of text.
`eof()` to check if the end of the input-stream is reached.
3) `ostream`
• Description: A class for output-stream operations.
• It is used for writing data to output-destinations like the console or files.
63
• Common Functions:
`<<` (insertion-operator) for writing formatted data.
`flush()` to flush the output buffer.
`endl` for inserting a newline and flushing the stream.

Example Program: Demonstrating istream and ostream


#include <iostream>
int main() {
int number;
cout << "Enter an integer: "; // Using ostream to print to console
cin >> number; // Using istream to read from keyboard
cout << "You entered: " << number << endl;
return 0;
}
Output:
Enter an integer: 42
You entered: 42

(b2) What are file stream classes in C++? Explain their role with examples.
Definition: File-stream-classes are specialized classes used for performing input and output operations on
files.
• File-stream-classes include
ifstream (Input File Stream)
ofstream (Output File Stream)
fstream (File Stream)

14.2.1 ifstream
• Purpose: Used to read data from files.
• Functionality: It allows opening a file and reading its contents, operating in input
mode by default.
• Example Usage:
ifstream inFile("[Link]");
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
[Link]();

14.2.2 ofstream
• Purpose: Used to write data to files.
• Functionality: It allows creating a file or opening an existing file to write data to it,
operating in output mode by default.
• Example Usage:
ofstream outFile("[Link]");
outFile << "Hello, World!" << endl;
[Link]();

14.2.3 fstream
• Purpose: Combines both input and output file-operations.
• Functionality: It allows both reading from and writing to files and can be used in
input, output, or both modes.

64
• Example Usage:
fstream file("[Link]", ios::in | ios::out);
string line;
while (getline(file, line)) {
cout << line << endl;
}
file << "New line added." << endl;
[Link]();

What is an inline function? Write a program to calculate area and circumference of circle using inline
function?

Definition
• Inline functions are small functions that the compiler can expand at the point of call rather than
executing a function-call.
• They are typically used for short and simple functions to avoid the overhead of function-call.
How It Works
• When a function is declared as inline, the compiler replaces the function-call with the actual code of the
function-body.
• This eliminates the overhead of function-call and improves program execution speed.
Syntax
• To declare a function as inline, use the `inline` keyword before the function definition.
• Syntax:
inline type funcation_name() {
….. . . .
}
Advantages
• Inline functions reduce function-call overhead, especially useful for small functions.
• They can improve program performance by eliminating the time spent in function call setup and return.

Program:
#include<iostream.h>
#include<conio.h>
#define PI 3.14159
// inline function for area of a circle
Inline double area(double radius)
{
return PI*radius*radius;
}
//inline function for circumference of a circle
Inline double circumference (double radius)
{
Return2*PI*radius;
}
Int main()
{
double radius;
cout<<”Enter the radius of the circle”<<endl;
cin>>radius;
cout<<Area of a circle”<<area(radius)<<endl;
cout<<”Circumference of the circle”<<circumference (radius) <<endl;

65
return 0;
}

Answer the following:


1. Define Class and Object.

Class is a user-defined datatype that has its own data members and member functions whereas an
object is an instance of class by which we can access the data members and member functions of the
class. A class is declared using the `class` keyword.
Syntax:
class ClassName {
DataType DataMember;
void Method();
};

Object Creation
• Creating an object means allocating memory for a specific instance of a class.
• Syntax:
ClassName objectName

2. What is the difference between Data Abstraction and Data Encapsulation?

Abstraction is the concept of object-oriented programming that "shows" only essential attributes
and "hides" unnecessary information. The main purpose of abstraction is hiding the unnecessary
details from the users. Abstraction is selecting data from a larger pool to show only relevant details
of the object to the user. It helps in reducing programming complexity and efforts. It is one of the
most important concepts of OOPs.

Encapsulation is a method of making a complex system easier to handle for end users. The user
need not worry about internal details and complexities of the system. Encapsulation is a process of
wrapping the data and the code, that operate on the data into a single entity. You can assume it as
a protective wrapper that stops random access of code defined outside that wrapper.

3. What is function prototype?


A function prototype in C++ informs the compiler about the intention to use a function, along with
its return type, parameters, and name. It is separate from the actual definition of the function

4. Define scope resolution operator in c++. Give example.

In C++, the scope resolution operator is ::. It is used for the following purposes.

1. To access a global variable when there is a local variable with same name:
2. To define a function outside a class.
3. To access a class’s static variables.
4. In case of multiple Inheritance: If the same variable name exists in two ancestor classes, we can use
scope resolution operator to distinguish.
5. For namespace If a class having the same name exists inside two namespaces we can use the
namespace name with the scope resolution operator to refer that class without any conflicts
6. Refer to a class inside another class: If a class exists inside another class we can use the nesting
class to refer the nested class using the scope resolution operator
7. Refer to a member of the base class in the derived object: In the case of having the same method in
both the base and derived classes, we could refer to each by the scope resolution operator
66
#include <iostream>
using namespace std;
class MyClass {
public:
void show() {
cout << "Member function of MyClass" << endl;
}
// Static member function
static void staticShow() {
cout << "Static member function of MyClass" << endl;
}
};
int main() {
MyClass obj;
[Link](); // Calls non-static member function
MyClass::staticShow(); // Calls static member function
return 0;
}
OUTPUT:
Member function of MyClass
Static member function of MyClass

4. What is constructor?

CONSTRUCTORS
• Special Member Function: Constructors are special member functions that are automatically called when
an object of a class is created.
• Same Name as Class: A constructor has the same name as the class and does not have a return type, not
even `void`.
• Initialization of Objects: The primary purpose of a constructor is to initialize the objects of its class.
• Automatic Invocation: Constructors are automatically invoked when an object is created.
• Types
i) Default Constructor
ii) Parameterized Constructor
iii) Copy Constructor
iv) Dynamic Constructor

5. Define operator overloading?


Operator overloading allows custom behaviors to be defined for operators when used with objects of user-
defined classes.
• Purpose: It enables the use of traditional operators like +, -, *, and == with objects.
Features
• Custom Behavior: The behavior of operators with objects can be determined as needed.
• Improved Readability: Operators can be used in expressions with objects, making the code easier to
read. For example, `a + b` can be used instead of `add(a, b)`.
• Member and Non-Member Functions: Operators can be overloaded using member functions (affecting
the object) or non-member functions (can involve multiple objects).
• Syntax: Overloaded operators must be defined with the operator keyword, followed by the operator
symbol.

6. What is the difference between a base class and a derived class?


67
A base class is an existing class from which the other classes are derived and inherit the methods and
properties. A derived class is a class that is constructed from a base class or an existing class. 2. Base class
can't acquire the methods and properties of the derived class.

7. Define inheritance.
Inheritance allows a new-class to inherit properties & behaviors (methods) from an existing-class.
The new-class is called as the derived-class.
The existing-class is called as the base-class.

8. Differentiate between function overloading and overriding?

Function overloading lets you declare functions with the same name but different parameters. Function
overriding lets you define one or more tasks that will override the function defined in the base class or
parent class. WHO can do this by calling virtual prototypes or inheriting the type declared in your base
class.

9. Define virtual base class.


Virtual base classes in C++ are used to prevent multiple instances of a given class from appearing in an
inheritance hierarchy when using multiple inheritances.

10. What are input and output streams?

In C++ input and output are performed in the form of a sequence of bytes or more commonly known as
streams.

 Input Stream: If the direction of flow of bytes is from the device(for example, Keyboard) to the
main memory then this process is called input.

 Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to
device( display screen ) then this process is called output.

11. What are templates?

Templates are the foundation of generic programming, which involves writing code in a way that is
independent of any particular type.

A template is a blueprint or formula for creating a generic class or a function. The library containers like
iterators and algorithms are examples of generic programming and have been developed using
template concept.

12. What is exception handling?

In C++, exceptions are runtime anomalies or abnormal conditions that a program encounters during its
execution. The process of handling these exceptions is called exception handling. Using the exception
handling mechanism, the control from one part of the program where the exception occurred can be
transferred to another part of the code.

Types of C++ Exception

There are two types of exceptions in C++

68
1. Synchronous: Exceptions that happen when something goes wrong because of a mistake in the
input data or when the program is not equipped to handle the current type of data it’s working
with, such as dividing a number by zero.

2. Asynchronous: Exceptions that are beyond the program’s control, such as disc failure, keyboard
interrupts, etc

13. differentiate call by value and call by reference in c++

In the case of Call by Value, when we pass the value of the parameter during the calling of the function,
it copies them to the function's actual local argument. In the case of Call by Reference, when we pass
the parameter's location reference/address, it copies and assigns them to the function's local
argument.

14. Define Aggregation

Aggregation is a relationship between two classes in which one class, known as the aggregate class,
contains a pointer or reference to an object of another class, known as the component class. The
component class can exist independently of the aggregate class, and it can be shared by multiple aggregate
classes

15. Explain the role of seekg(),seekp(),tellg(),tellp(),function in the process of random access in a file

seekg() is used to move the get pointer to a desired location


seekp() is used to move the put pointer to a desired location
tellp() is used to know where the put pointer is in a file.
tellg() is used to know where the get pointer is in a file
clear() function is used to remove all the elements of the set container, thus making its size

16. What are the file streams?

In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream. fstream: This Stream class
can be used for both read and write from/to files.

17. Explain the process of open,read,write and close files?

File Operations in C++

 open() – This is used to create a file.


 read() – This is used to read the data from the file.
 write() – This is used to write new data to file.
 close() – This is used to close the file.

18. What is a file mode? What are the different mode options available for opening a file?

In C++, for every file operation, exists a specific file mode. These file modes allow us to create, read,
write, append or modify a file. The file modes are defined in the class ios.

File opening-modes determine how a file is accessed and modified during fileoperations.
• They are specified when opening a file using file stream-classes (`ifstream`,
`ofstream`, `fstream`).

69
• Common file opening-modes are listed in below table:

70

You might also like