C++ Model Question Paper Answer
C++ Model Question Paper Answer
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
PHP
C++
Ruby
Features of oop
Encapsulation
Inheritance
Polymorphism
Abstraction
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.
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.
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:
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.
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 */
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
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:
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
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.
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;
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
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
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
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.
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.
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.
(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.
(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:
(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.
(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”;
(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:
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;
};
Following is the Binary Operator Overloading syntax in the C++ Programming language.
return_type :: operator binary_operator_symbol (arg)
{
// function definition
}
binary_operator_symbol: It represents the binary operator symbol that overloads a function to perform
the calculation.
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.
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.
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;
}
#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() {
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.
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.
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()`
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`.
Area of Rectangle: 24
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.
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;
.....
}
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.
Syntax
class BaseClass {
public:
// Base-class-members
};
27
class DerivedClass : public BaseClass {
public:
// Derived-class members
};
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
};
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.
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;
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;
}
#include <iostream>
using namespace std;
// Driver code
int main()
{
add(10, 2);
add(5.3, 6.2);
return 0;
}
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;
}
int main() {
// Initialize an array of structures
Person people[3] = {
{"Arjuna", 1, 88000},
34
{"Krishna", 2, 92000},
{"Bhima", 3, 79000}
};
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.
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.
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
};
#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
• 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
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.
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
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;
}
};
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
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.
(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
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
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.
• 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.
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.
Syntax:
Class className{
……..
public:
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
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
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:
LOGICAL-EXPRESSIONS
• Logical-expressions combine multiple conditions using logical operators (`&&`,
`||`, `! `).
• They evaluate to `true` or `false` based on the truth values of their operands.
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.
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
}
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;
}
(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.
• 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.
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.
(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};
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
15. (a1) Define class and object. Write a C++ program to illustrate the use of classes and objects.
(Refer above model paper for answer)
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();
};
// 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
#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;
}
};
// 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;
}
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
};
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.
(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;
}
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
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.
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
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.
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.
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.
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.
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.
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
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.
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
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.
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