0% found this document useful (0 votes)
1 views

ESCPP

The document discusses key concepts of Object-Oriented Programming (OOP) including encapsulation, inheritance, polymorphism, and abstraction. It defines various terms such as destructors, pure virtual functions, and access specifiers, while also explaining features like multiple inheritance and default arguments. Additionally, it covers operator overloading, exception handling, and memory management techniques in C++, providing a comprehensive overview of the language's capabilities.

Uploaded by

isnehanagar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

ESCPP

The document discusses key concepts of Object-Oriented Programming (OOP) including encapsulation, inheritance, polymorphism, and abstraction. It defines various terms such as destructors, pure virtual functions, and access specifiers, while also explaining features like multiple inheritance and default arguments. Additionally, it covers operator overloading, exception handling, and memory management techniques in C++, providing a comprehensive overview of the language's capabilities.

Uploaded by

isnehanagar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

a) List any four features of OOP's. g) Define destructor.

Encapsulation binds data and functions into a single A destructor is a special member function with the
unit and restricts direct access to data members. same name as the class, preceded by a tilde (~),
Inheritance allows one class to derive and reuse and is automatically called when an object is
properties and methods from another class. destroyed. It is used to release resources such as
Polymorphism enables functions to behave memory or file handles.
differently based on the object that invokes them.
Abstraction hides implementation details and only h) What is 'this' pointer?
shows the essential features to the user. The this pointer is an implicit pointer available in all
non-static member functions, which points to the
b) Define pure virtual function. object that invoked the function. It helps
A pure virtual function is a virtual function declared differentiate between instance variables and
in a base class that has no definition there and function parameters when they have the same
must be overridden in derived classes. It is declared name.
using = 0 syntax and makes the class abstract,
preventing its direct instantiation. i) What is Run-Time Polymorphism?
Run-time polymorphism allows the program to
c) What is cascading of I/O operator? determine at runtime which function to call using
Cascading of I/O operators means chaining multiple virtual functions and base class pointers. This
input (>>) or output (<<) operations in one enables dynamic method binding and allows
statement. For example, cout << a << b; prints both behavior to change depending on the object's
variables one after another, improving code actual type.
readability and conciseness.
j) Enlist manipulators in C++.
d) List the ways to define a constant. Some commonly used manipulators in C++ are endl
Constants can be defined using the const keyword (newline), setw (set width), setprecision (set
(e.g., const int x = 10;), #define macro (e.g., #define decimal precision), fixed (fixed-point notation), and
PI 3.14), or by using enum for a group of related showpoint (force display of decimal point). These
constants. These methods ensure that the values are used with output streams to format the output
remain unchanged during execution. neatly.

e) What is an abstract class? a) Explain any two manipulators.


An abstract class is a class that contains at least one endl: This manipulator is used to insert a new line
pure virtual function. It cannot be instantiated and and flush the output buffer. It is equivalent to using
serves as a base for derived classes that must \n but is safer as it ensures all output is written
implement the pure virtual functions. immediately.
setw(): Defined in <iomanip>, setw(n) sets the
f) Define multiple inheritance. width of the next output field to n characters. It
Multiple inheritance is a feature in C++ where a helps align numbers or text in tabular form by
class can inherit from more than one base class adding spaces if necessary.
simultaneously. This allows the derived class to
access members of all its parent classes, but can b) Explain tellg() and tellp() with syntax.
lead to ambiguity like the diamond problem. tellg() is a member function of input file streams
like ifstream that returns the current byte position
of the file pointer while reading. Syntax:
stream_name.tellg();.
tellp() is used with output file streams like ofstream
and returns the current byte position for writing.
Syntax: stream_name.tellp();.
c) What are the visibility labels used in C++? h) What is static Polymorphism?
C++ supports three visibility labels: private, Static polymorphism, also called compile-time
protected, and public. polymorphism, is achieved using function
private members are accessible only within the overloading or operator overloading.
class. The function to be executed is determined during
protected members are accessible within the class compile-time based on the function signature or
and its derived classes. number/type of arguments.
public members are accessible from anywhere in
the program. i) Explain structure of C++ program.
A basic C++ program structure includes:
d) What is extraction and insertion operator? Preprocessor directives like #include<iostream>.
The extraction operator (>>) is used with cin to Global declarations (optional).
input data from the user, while the insertion The main() function, which is the entry point of the
operator (<<) is used with cout to display output. program, containing variable declarations, logic,
These operators are overloaded in the iostream and return statement.
library to handle various data types for Additional user-defined functions or classes may
input/output operations. also be defined before or after the main().
Example:
e) What is abstraction and encapsulation? #include <iostream> // Header file
Abstraction means hiding complex implementation
details and showing only essential information; it using namespace std; // Namespace
helps reduce complexity. declaration
Encapsulation is the process of wrapping data and
methods into a single unit (class), protecting the // Main function
data from direct outside access and misuse. int main() {
cout << "Hello, World!"; // Output statement
f) What is default argument in function? return 0; // Return statement
A default argument is a value provided in a function }
declaration that is automatically used if the caller
omits that argument. c) Define constructor.
For example: void print(int x, int y = 10); allows the A constructor is a special member function of a
function to be called with one or two arguments, class that is automatically invoked when an object
using 10 as the default for y if omitted. is created. It has the same name as the class and is
used to initialize objects. Constructors do not have
g) Write any two uses of scope resolution a return type and can be overloaded to allow
operator. multiple ways of initializing an object. If no
It is used to define a member function of a class constructor is defined, C++ provides a default one.
outside the class body. Example: void
ClassName::functionName() {}. d) What is inline function.
It is used to access a global variable when a local An inline function is declared using the inline
variable has the same name. Example: ::x accesses keyword and is meant to reduce the overhead of
the global x. function calls. The compiler attempts to replace the
function call with the actual code of the function
during compilation. This is effective for small,
frequently used functions. However, it is only a
suggestion to the compiler, which may ignore it in
some cases.
e) What is reference variable? What is its major This improves security and data hiding, helping to
use. create a clear interface and maintain control over
A reference variable acts as an alias for another data.
variable and is declared using the & symbol. Once a
reference is initialized to a variable, it cannot be b) Define the following terms
changed to refer to another variable. The major use i) Early Binding:
of reference variables is in passing arguments to Early binding, also known as static binding, occurs
functions by reference, allowing the function to when the function call is resolved at compile time.
It is used in function overloading and operator
modify the original variable directly. This helps in
overloading, where the function to be executed is
saving memory and avoiding copying large data
determined by the compiler.
structures. ii) Late Binding:
Late binding, or dynamic binding, occurs when the
g) What is compile-time polymorphism. function call is resolved at runtime. It is
Compile-time polymorphism refers to function or implemented using virtual functions and is essential
operator overloading, where the compiler for achieving runtime polymorphism.
determines which version of a function or operator
to call based on the arguments. It allows multiple d) Explain get() and put() function.
functions with the same name but different The get() function is used to read a single
parameters. This is resolved during the compilation character from an input stream, including
phase, improving performance. It is also known as whitespaces. It can be used with file or console
static polymorphism. input and is useful when reading character data. The
put() function is used to write a single character to
h) What is default argument. an output stream. It is often used to write characters
A default argument is a value assigned to a function to a file or display output one character at a time.
parameter that is used if no argument is provided
by the caller. This allows functions to be called with e) What is stream?
fewer arguments than declared. Default arguments A stream in C++ is an abstraction used to perform
input and output operations. It represents a flow of
must be provided from right to left in the
data, either from a source to a program (input
parameter list. Example: void display(int x, int y =
stream) or from a program to a destination (output
10);.
stream). Streams are part of the iostream library and
include types like cin, cout, ifstream, and
j) What are the access specifiers used in C++? ofstream.
C++ provides three access specifiers: private,
protected, and public. f) Define Friend function.
private: Members are accessible only within the A friend function is a non-member function that is
class and not outside. given special access to private and protected
protected: Members are accessible within the class members of a class. It is declared using the friend
and its derived classes. keyword inside the class. This is useful when two or
public: Members are accessible from anywhere in more classes need to access each other’s private
the program using the object. data directly, such as in operator overloading.
These specifiers help implement data hiding and
control access to class members. g) Explain the use of new operator, state the syntax.
The new operator in C++ is used to dynamically
a) What is Encapsulation? allocate memory for variables, arrays, or objects at
Encapsulation is the concept of binding data and the runtime. It returns a pointer to the allocated
functions that manipulate it into a single unit, memory. Syntax: pointer = new data_type; or
typically a class. It restricts direct access to some pointer = new data_type[size];. The allocated
components, which means internal data of an object memory must be released using the delete operator
can only be accessed through member functions. to prevent memory leaks.
h) State the need of virtual keyword. a) Function Overriding
The virtual keyword is used to declare a function Function overriding allows a derived class to
as virtual in a base class, allowing it to be redefine a base class function with the same name
overridden in derived classes. This supports runtime and parameters. The base class function must be
polymorphism, where the call to a function is declared virtual to enable runtime
resolved at runtime based on the type of the object. polymorphism. The function that gets executed is
It ensures the correct function is invoked for derived determined by the type of the object pointed to,
objects using base class pointers. not the pointer. This is useful for achieving dynamic
behavior in inheritance.
i) State user defined data types in C++.
Example: virtual void display(); in base, and
User-defined data types in C++ include class,
overridden in derived class.
struct, union, enum, and typedef/using. These
allow programmers to define their own complex
b) Exception Handling
data types suited to specific problem domains.
Exception handling in C++ is a mechanism to detect
They enhance code modularity, reusability, and
and manage errors during program execution using
readability.
try, throw, and catch. Code that might cause an
exception is enclosed in a try block. When an error
1)What is a class?
occurs, a throw statement sends the control to a
A class in C++ is a user-defined data type that acts
matching catch block. It prevents abnormal
as a blueprint for creating objects. It encapsulates
program termination and provides graceful error
data members (variables) and member functions
recovery. It is essential for handling runtime issues
(methods) into a single unit. It supports object-
like division by zero or file not found.
oriented principles like encapsulation, abstraction,
and inheritance.
c) Call-by-Value and Call-by-Reference
Syntax of a class:
In call-by-value, a copy of the variable is passed to
class ClassName {
the function, so changes made inside the function
private:
do not affect the original value.
// private data members and methods
In call-by-reference, the address or reference of the
variable is passed, allowing the function to modify
public:
the original data directly.
// public data members and methods
Call-by-value is safer, while call-by-reference is
more efficient, especially for large objects.
void display(); // member function
Example: void func(int &x) – reference, void
};
func(int x) – value.

2)Operators which cannot be overloaded in C++:


d) Data Abstraction
:: (Scope resolution operator)
Data abstraction refers to hiding the internal details
. (Member access operator)
of an object and showing only essential features. It
.* (Pointer-to-member operator)
is implemented using access specifiers like private
sizeof (Size operator)
and public in classes. Users interact with the
typeid (Used for RTTI)
object through public functions, while internal data
?: (Ternary/conditional operator)
is hidden for protection. This promotes simplicity
const_cast, dynamic_cast, reinterpret_cast,
and security by reducing complexity. Abstraction is
static_cast (Casting operators)
a key pillar of object-oriented programming.
e) Operator Overloading i) Constructor in Derived Class
Operator overloading allows you to redefine A constructor in a derived class is used to initialize
standard C++ operators for user-defined types such its own members and also call the constructor of
as classes. It makes the code more readable and the base class. If the base class constructor requires
intuitive by enabling operations like +, -, ==, or [] arguments, the derived class must use a
to be used with objects. It is done using special constructor initialization list to pass them.
functions with the operator keyword. However, Example:
certain operators like ::, ., and sizeof cannot be Derived(int x, int y) : Base(x) { b = y; }
overloaded. Example: Complex This ensures proper initialization of all inherited
operator+(Complex); and new members. Constructors are called in the
order of inheritance, from base to derived.
f) Pointer to Object with Example
A pointer to an object is used to store the address a) Solution for Critical Section Problem
of an object and access its members using the -> The critical section problem arises when multiple
operator. This is useful in dynamic memory processes access shared resources, leading to
allocation and when working with arrays of objects inconsistency. A good solution must satisfy three
or polymorphism. conditions:
Example: Mutual Exclusion – Only one process is allowed in
Student obj; the critical section at a time.
Student *ptr = &obj; Progress – If no process is in the critical section,
ptr->display(); others should not be prevented from entering.
Bounded Waiting – A process must not wait
g) Array of Objects indefinitely to enter.
An array of objects is a fixed-size collection of Solutions include Peterson’s Algorithm,
objects of the same class type. It allows grouped Semaphores, and Monitors in modern OS.
management of multiple instances using a single
array name with index access. For example, b) Medium-Term Scheduler
Student s[5]; creates an array of five Student A Medium-Term Scheduler temporarily removes
objects. You can use loops to perform actions like (swaps out) processes from memory to reduce
displaying or modifying data for each object. It is memory load.
useful in programs involving collections like It helps in improving the degree of
employee records or book lists. multiprogramming.
Suspended processes can later be brought back
h) Access Specifier (swapped in) by the scheduler.
Access specifiers in C++ control the visibility and It plays a key role in memory management and
accessibility of class members. There are three handles partially executed processes.
main types: Used in time-sharing systems to manage limited
private: accessible only within the class. memory efficiently.
protected: accessible within the class and derived
classes. c) Indexed Allocation
public: accessible from anywhere in the program. Indexed Allocation is a file storage method where
They support the concept of encapsulation by all block addresses of a file are stored in a separate
hiding data and controlling how it is exposed or index block.
modified. The index block contains pointers to all the data
blocks of the file.
It supports both sequential and direct access to file
blocks.
It eliminates external fragmentation but uses extra
space for the index.
a) Explain operator overloading in C++ with an };
example.
Operator overloading allows user-defined types class Circle : public Shape {
(classes) to use standard operators like +, -, ==, etc., public:
by redefining their behavior. It improves readability void draw() { cout << "Drawing Circle"; }
and enables intuitive operations on objects. The };
operator is overloaded using a special function with
the keyword operator followed by the symbol. Only d) Explain Dynamic Constructor with suitable
certain operators can be overloaded. example.
Example: A dynamic constructor is a constructor that
class Complex { allocates memory dynamically using the new
int real, imag; operator. This is useful when the size of an array or
public: string is not known at compile time. It ensures
Complex(int r = 0, int i = 0) { real = r; imag = i; } memory is allocated as needed during object
Complex operator+(Complex c) { creation.
return Complex(real + c.real, imag + c.imag); Example:
} class String {
void display() { cout << real << "+" << imag << "i"; char *name;
} public:
}; String(const char *str) {
name = new char[strlen(str) + 1]; // Dynamic
b) Explain memory allocation for objects with non- allocation
static and static data members. strcpy(name, str);
In C++, non-static data members are specific to }
each object. Every time an object is created, void display() { cout << name; }
memory is allocated separately for its non-static };
members. In contrast, static data members are
shared among all objects of the class and are a) List and explain advantages of Multiprocessor
stored only once in memory, regardless of the system.
number of objects created. A multiprocessor system has two or more
Example: processors that share memory and work
class Demo { simultaneously. These systems are powerful and
int a; // Non-static: separate memory per commonly used in high-performance computing.
object Advantages:
static int count; // Static: one shared memory Increased Throughput: Multiple processors can
}; perform more tasks in parallel, improving overall
speed.
c) What is pure virtual function? Explain with Reliability: If one processor fails, others can
example. continue to work (fault tolerance).
A pure virtual function is a function declared in a Economy of Scale: Shared resources reduce
base class with no definition and is meant to be hardware costs compared to multiple separate
overridden in derived classes. It is declared by systems.
assigning = 0 in the declaration. A class with one or Efficient Resource Utilization: CPU cycles are used
more pure virtual functions becomes an abstract more effectively, reducing idle time.
class and cannot be instantiated directly. Scalability: More processors can be added as
Example: demand increases.
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
e) What is inheritance and explain the hierarchical class Student {
inheritance. int roll;
Inheritance is an object-oriented feature that public:
allows one class (derived) to acquire properties and Student(int r) { roll = r; }
behavior from another class (base). It promotes void display() { cout << "Roll No: " << roll; }
code reuse and establishes relationships between };
classes.
Hierarchical inheritance occurs when multiple
derived classes inherit from a single base class. b) What is function overloading? Explain with
Example: suitable example.
class Animal { Function Overloading is a feature in C++ where
public: multiple functions can have the same name but
void sound() { cout << "Makes sound"; } differ in the number or types of parameters. It
}; enhances code readability and allows the same
function name to perform different tasks.
class Dog : public Animal { Example:
public: class Math {
void bark() { cout << "Barks"; } public:
}; void add(int a, int b) {
class Cat : public Animal { cout << "Sum: " << a + b;
public: }
void meow() { cout << "Meows"; } void add(float x, float y) {
}; cout << "Sum: " << x + y;
Explain types of inheritance: }
Inheritance allows a class (derived) to reuse };
properties and behaviors of another class (base).
C++ supports several types: d) Explain virtual base class with suitable diagram.
Single Inheritance – One derived class inherits from When multiple derived classes inherit from a
one base class. common base class and another class further
Multiple Inheritance – A class inherits from more inherits from them, the base class gets duplicated.
than one base class. This is known as the diamond problem, and to
Multilevel Inheritance – A class inherits from a resolve it, virtual base classes are used.
derived class. Syntax:
Hierarchical Inheritance – Multiple derived classes class A {
inherit from one base class. public: void show() { cout << "A"; }
Hybrid Inheritance – A combination of two or more };
types (e.g., multiple + multilevel).
class B : virtual public A { };
a) List different types of constructor. Explain any class C : virtual public A { };
one with example. class D : public B, public C { };
Types of constructors in C++: In this structure, class D will have only one instance
Default Constructor of class A, preventing ambiguity.
Parameterized Constructor
Copy Constructor
Dynamic Constructor
Static Constructor (implicitly created)
Parameterized Constructor Example:
A constructor that accepts arguments to initialize
data members.
e) Describe file manipulators with their syntaxes. CPU Registers: Stores temporary data during
File manipulators in C++ are used to control input execution.
and output formatting in file streams. Some Memory Management Info: Base/limit registers,
commonly used manipulators are: page tables.
setw(n) – Sets the field width to n. Accounting Info: CPU usage, time limits, etc.
setprecision(n) – Sets decimal precision to n digits. I/O Status Info: List of I/O devices assigned.
setfill(ch) – Fills the empty spaces with character The OS uses PCB to switch between processes
ch. during context switching, ensuring process
endl – Inserts a newline and flushes the buffer. execution resumes correctly.
flush – Flushes the output buffer without inserting
a newline.
Example:
#include <iomanip>
ofstream fout("data.txt");
fout << setw(10) << setfill('*') << 25 << endl;
This writes *******25 to the file with field width
10 and * as fill character.

c) Explain different methods for recovery from a


deadlock.
Deadlock recovery is essential when a system falls
into a state where processes wait indefinitely for
resources. Recovery methods include:
Process Termination:
Abort all deadlocked processes.
Abort one process at a time until the cycle is
broken.
Resource Preemption:
d) What is Fragmentation? Explain types of
Temporarily take resources from one process and
fragmentation in detail.
assign to another.
Fragmentation is the unusable memory within or
Rollback:
between allocated memory blocks in a system,
Roll back one or more processes to a previous safe
which leads to inefficient memory use.
state and restart.
Types:
Process Priority:
Internal Fragmentation:
Based on priority, choose which process to
Occurs when allocated memory is slightly larger
terminate or preempt.
than requested. The leftover space inside the
Each method has trade-offs in terms of cost, data
allocated block is wasted.
consistency, and system performance.
External Fragmentation:
Happens when free memory is split into small
b) Explain Process Control Block (PCB) in detail.
blocks scattered throughout, making it difficult to
A Process Control Block (PCB) is a data structure
allocate large contiguous memory even if enough
maintained by the operating system for every
total space is available.
process. It stores essential information required for
Solution:
process management and scheduling.
Compaction (for external fragmentation) or using
Contents of PCB:
paging/segmentation can help reduce these issues.
Process ID (PID): Unique identifier.
Process State: Ready, running, waiting, etc.
Program Counter: Address of the next instruction
to execute.
e) Calculate average turn around time and average class. It is declared using the friend keyword inside
waiting time using FCFS algorithm. the class.
Let’s take the following process set with arrival time Characteristics:
= 0 for all: It is not a member of the class but has access to its
Process Burst Time private data.
Can be a global function or a member of another
P1 5
class.
P2 3 It does not use this pointer.
P3 8 Can be declared in multiple classes to access data
P4 6 from more than one.
Example:
FCFS (First-Come, First-Served) execution order: P1
class A {
→ P2 → P3 → P4
int x = 10;
Completion Time:
friend void show(A);
P1 = 5
};
P2 = 5 + 3 = 8
void show(A a) { cout << a.x; }
P3 = 8 + 8 = 16
P4 = 16 + 6 = 22
d) Explain use of any four file opening modes.
Turnaround Time = Completion Time – Arrival Time:
C++ provides various file opening modes using
TAT: P1 = 5, P2 = 8, P3 = 16, P4 = 22
fstream to handle files differently. Four common
Waiting Time = Turnaround Time – Burst Time:
modes are:
WT: P1 = 0, P2 = 5, P3 = 8, P4 = 10
1.ios::in – Opens the file for reading only.
Average TAT = (5+8+16+22)/4 = 51/4 = 12.75
ifstream fin("data.txt", ios::in);
Average WT = (0+5+8+10)/4 = 23/4 = 5.75
2.ios::out – Opens the file for writing; if it exists,
contents are deleted.
b) Explain static data members and static member
ofstream fout("data.txt", ios::out);
functions with example.
3.ios::app – Opens file for appending; writes are
A static data member belongs to the class, not to
added at the end.
any object. Only one copy exists, shared among all
ofstream fout("data.txt", ios::app);
objects. It is initialized outside the class.
4.ios::binary – Opens file in binary mode.
A static member function can access only static
ifstream fin("file.dat", ios::binary);
members and is called using the class name
These modes can be combined using bitwise OR (|)
directly.
like ios::out | ios::app.
Example:
class Test {
a) System Calls related to Process and Job Control
static int count;
System calls related to process and job control
public:
include:
static void show() { cout << "Count: " << count; }
fork(): Used to create a new process by duplicating
};
the parent.
int Test::count = 5;
exec(): Replaces the current process image with a
Advantages:
new process image.
Useful for maintaining common data (like count of
wait(): Suspends execution until one of the child
objects).
processes terminates.
Accessed without creating an object.
exit(): Terminates the current process and returns a
status.
c) What is friend function? Write characteristics of
getpid() and getppid(): Retrieve the process ID of
friend function.
the current or parent process. These calls help
A friend function is a non-member function that
manage creation, termination, and coordination of
can access the private and protected members of a
processes.
b) Multilevel Feedback Queue (MLFQ) Algorithm Page Reference String: 4, 6, 7, 8, 4, 6, 9, 6, 7, 8, 4, 6,
The MLFQ scheduling algorithm uses multiple 7, 9
queues with different priority levels. Number of Frames: 3
Processes start in the highest priority queue and
may move to lower queues if they use too much i) FIFO:
CPU time. Step Pages in Frame Page Fault
Short processes get quick responses, while long
4 4 Yes
CPU-bound ones are downgraded.
It prevents starvation by occasionally boosting 6 4, 6 Yes
lower-priority processes. 7 4, 6, 7 Yes
MLFQ is dynamic, adapting to the behavior of 8 6, 7, 8 Yes
processes.
4 7, 8, 4 Yes
It combines the benefits of FCFS, SJF, and Round
Robin. 6 8, 4, 6 Yes
9 4, 6, 9 Yes
c) Dining Philosopher Problem (Synchronization 6 4, 6, 9 No
Problem)
The Dining Philosopher Problem is a classic 7 6, 9, 7 Yes
synchronization issue illustrating deadlock and 8 9, 7, 8 Yes
resource sharing: 4 7, 8, 4 Yes
Five philosophers sit at a table with a fork between
6 8, 4, 6 Yes
each pair.
To eat, a philosopher needs both the left and right 7 4, 6, 7 Yes
fork. 9 6, 7, 9 Yes
If every philosopher picks up their left fork first, Total Page Faults (FIFO): 12
deadlock can occur as no one can pick the right.
Solutions involve avoiding circular wait or using ii) LRU:
semaphores, monitors, or resource hierarchy.
Step Pages in Frame Page Fault
It highlights challenges in process synchronization
and deadlock avoidance. 4 4 Yes
6 4, 6 Yes
7 4, 6, 7 Yes
e) FCFS Scheduling: Calculate Avg Turnaround &
8 6, 7, 8 Yes
Waiting Time
Burs 4 7, 8, 4 Yes
Proces Arriva t Completio Turnaroun Waitin 6 8, 4, 6 Yes
s l Time Tim n Time d Time g Time 9 4, 6, 9 Yes
e
6 4, 6, 9 No
P2 0 6 6 6 0
7 6, 9, 7 Yes
P4 0 4 10 10 6
8 9, 7, 8 Yes
P1 1 5 15 14 9
4 7, 8, 4 Yes
P3 2 2 17 15 13
6 8, 4, 6 Yes
Average Turnaround Time = (6 + 10 + 14 + 15) / 4 =
7 4, 6, 7 Yes
11.25
Average Waiting Time = (0 + 6 + 9 + 13) / 4 = 7.0 9 6, 7, 9 Yes
Total Page Faults (LRU): 12
f) Page Replacement Schemes (3 Frames)
Programs: cout << id << " " << name << " " << salary <<
1. Swap Two Numbers using Call by Reference: endl;
#include <iostream> }
using namespace std; float getSalary() {
return salary;
class Numbers { }
int a, b; };
public:
void accept() { int main() {
cout << "Enter two numbers: "; int n;
cin >> a >> b; cout << "Enter number of customers: ";
} cin >> n;
void display() { Customer c[n];
cout << "a = " << a << ", b = " << b << endl; for(int i = 0; i < n; i++) c[i].accept();
}
void swap(int &x, int &y) { float maxSal = c[0].getSalary();
int temp = x; int maxIndex = 0;
x = y; for(int i = 1; i < n; i++) {
y = temp; if(c[i].getSalary() > maxSal) {
} maxSal = c[i].getSalary();
void performSwap() { maxIndex = i;
swap(a, b); }
} }
}; cout << "Customer with highest salary:\n";
int main() { c[maxIndex].display();
Numbers n; return 0;
n.accept(); }
n.display();
n.performSwap(); 5. Copy File to Another File
cout << "After swap:\n"; #include <iostream>
n.display(); #include <fstream>
return 0; using namespace std;
}
int main() {
2. Customer with Maximum Salary: ifstream fin("source.txt");
#include <iostream> ofstream fout("destination.txt");
using namespace std; char ch;
while(fin.get(ch)) {
class Customer { fout.put(ch);
int id; }
string name; fin.close();
float salary; fout.close();
public: cout << "File copied successfully.\n";
void accept() { return 0;
cout << "Enter ID, Name, Salary: "; }
cin >> id >> name >> salary;
}
void display() {
3. Factorial using Inline Function: int main() {
#include <iostream> float r;
using namespace std; cout << "Enter radius: ";
cin >> r;
inline int factorial(int n) { cout << "Area = " << area(r) << ", Circumference =
return (n <= 1) ? 1 : n * factorial(n - 1); " << circumference(r) << endl;
} return 0;
int main() { }
int num; 7. Vehicle Hierarchy:
cout << "Enter a number: "; #include <iostream>
cin >> num; using namespace std;
cout << "Factorial: " << factorial(num) << endl;
return 0; class Vehicle {
} public:
4. Count Function Calls Using Static Member void show() { cout << "Generic Vehicle\n"; }
#include <iostream> };
using namespace std; class TwoWheeler : public Vehicle {
public:
class Counter { void show() { cout << "Two Wheeler\n"; }
static int count; };
public: class ThreeWheeler : public Vehicle {
void countCall() { public:
count++; void show() { cout << "Three Wheeler\n"; }
} };
void display() { class FourWheeler : public Vehicle {
cout << "Count called " << count << " times\n"; public:
} void show() { cout << "Four Wheeler\n"; }
}; };
int Counter::count = 0; int main() {
TwoWheeler t;
int main() { ThreeWheeler th;
Counter c; FourWheeler f;
c.countCall(); t.show(); th.show(); f.show();
c.countCall(); return 0;
c.countCall(); }
c.display(); 14. Rectangle Perimeter using Inline Function:
return 0; #include <iostream>
} using namespace std;
6. Area & Circumference using Inline Function:
#include <iostream> inline int perimeter(int l, int w) {
#define PI 3.14 return 2 * (l + w);
using namespace std; }
int main() {
inline float area(float r) { int l, w;
return PI * r * r; cout << "Enter length and width: ";
} cin >> l >> w;
inline float circumference(float r) { cout << "Perimeter = " << perimeter(l, w) << endl;
return 2 * PI * r; return 0;
} }
8. Use of setiosflags and setfill: cin >> pname >> price >> qty;
#include <iostream> }
#include <iomanip> float total() {
using namespace std; return price * qty;
}
int main() { void display() {
cout << setiosflags(ios::right) << setw(10) << 123 cout << pname << " " << price << " " << qty << "
<< endl; = " << total() << endl;
cout << setiosflags(ios::fixed) << setprecision(2) }
<< 12.3456 << endl; };
cout << setfill('*') << setw(10) << 45 << endl;
return 0; int main() {
} int n;
9. Overload == Operator for String Comparison: cout << "Enter number of products: ";
#include <iostream> cin >> n;
#include <string> Product p[n];
using namespace std; for(int i = 0; i < n; i++) p[i].accept();
float grandTotal = 0;
class MyString { for(int i = 0; i < n; i++) {
string str; p[i].display();
public: grandTotal += p[i].total();
void accept() { cin >> str; } }
bool operator==(MyString m) { cout << "Grand Total = " << grandTotal << endl;
return str == m.str; return 0;
} }
};
13. Alphabet Pattern:
int main() { A
MyString s1, s2; BC
cout << "Enter first string: "; s1.accept(); DEF
cout << "Enter second string: "; s2.accept(); GHIJ
if(s1 == s2) #include <iostream>
cout << "Strings are equal.\n"; using namespace std;
else
cout << "Strings are not equal.\n"; int main() {
return 0; char ch = 'A';
} for(int i = 1; i <= 4; i++) {
10. Product Class and Bill: for(int j = 1; j <= i; j++) {
#include <iostream> cout << ch++ << " ";
using namespace std; }
cout << endl;
class Product { }
string pname; return 0;
float price; }
int qty;
public:
void accept() {
cout << "Enter Product Name, Price, Quantity:
";
11. Multilevel Inheritance – Manager with Max cout << "Manager with highest salary:\n";
Salary: m[index].display();
#include <iostream> return 0;
using namespace std; }
12. Function Overloading – Area of Circle, Square,
class Person { Rectangle:
public: #include <iostream>
string name, address; using namespace std;
long phoneno;
void acceptPerson() { float area(float r) {
cout << "Enter name, address, phone: "; return 3.14f * r * r;
cin >> name >> address >> phoneno; }
} int area(int side) {
}; return side * side;
class Employee : public Person { }
public: int area(int l, int b) {
int eno; return l * b;
void acceptEmp() { }
cout << "Enter employee no: "; int main() {
cin >> eno; cout << "Area of Circle (r=2): " << area(2.0f) <<
} endl;
}; cout << "Area of Square (s=4): " << area(4) <<
class Manager : public Employee { endl;
public: cout << "Area of Rectangle (l=3, b=5): " << area(3,
string designation, department; 5) << endl;
float salary; return 0;
void acceptManager() { }
acceptPerson(); a) What is meant by Free Space Management?
acceptEmp(); Define Bit Vector and Grouping.
cout << "Enter designation, department, basic Free Space Management refers to the method used
salary: "; by an operating system to keep track of free disk
cin >> designation >> department >> salary; blocks that are available for data storage. It ensures
} efficient allocation and deallocation of storage
void display() { blocks.
cout << name << " " << designation << " " << Bit Vector (Bitmap): This technique uses a string of
department << " " << salary << endl; bits to represent the free or occupied status of
} blocks on the disk. A bit value of 0 means the block
}; is free, and 1 means it is occupied. It is simple and
fast but requires memory.
int main() { Grouping: In this method, free blocks are stored in
int n; linked groups. The first block contains addresses of
cout << "Enter number of managers: "; a few free blocks, and the last address in that block
cin >> n; points to another block containing more free block
Manager m[n]; addresses. It reduces overhead and is efficient for
for(int i = 0; i < n; i++) m[i].acceptManager(); large disks.
int index = 0;
for(int i = 1; i < n; i++) {
if(m[i].salary > m[index].salary) index = i;
}
b) Define the terms: i) Logical Address ii) Physical e) FCFS Disk Scheduling – Total Head Movement
Address Given:
A Logical Address (also called virtual address) is the Disk tracks: 0 to 199
address generated by the CPU during a program's Initial head position: 25
execution. It is an abstraction used by applications Request queue: 68, 172, 4, 178, 130, 40, 118, 136
and handled by the memory management unit FCFS (First-Come, First-Serve) means requests are
(MMU). served in order received.
A Physical Address is the actual address in the main Calculations:
memory (RAM) where data is stored. It is computed From To Movement
by the MMU using the logical address and the base
25 68 43
address stored in the relocation register.
The logical address is independent of physical 68 172 104
memory size, which allows processes to be 172 4 168
relocated or swapped easily, enhancing memory 4 178 174
utilization and protection.
178 130 48
130 40 90
d) What are the differences between Preemptive 40 118 78
and Non-Preemptive Scheduling? 118 136 18
Preemptive Non-Preemptive
Feature Total 723 tracks
Scheduling Scheduling
Total Head Movement = 723 tracks
CPU can be taken CPU cannot be
Process
away from a taken unless it
Control c) Explain Resource Allocation Graph in detail.
process terminates A Resource Allocation Graph (RAG) is a directed
Can lead to poor graph used to represent the state of system
Response Generally faster
response for resources and processes. It is used to detect and
Time for short tasks
short tasks prevent deadlocks.
Simpler and Nodes are divided into two types: Processes (P1,
More complex to P2, …) and Resources (R1, R2, …).
Complexity easier to
implement A request edge (P → R) indicates that a process is
implement
requesting a resource.
Round Robin, FCFS, SJF (non-
Examples An assignment edge (R → P) means a resource is
SRTF preemptive)
allocated to a process.
Higher, needs If the RAG contains no cycles, the system is in a safe
Starvation Lower compared
aging to prevent state. If it contains a cycle, deadlock may occur
Possibility to preemptive
starvation (certain in single-instance resource systems). It is
Preemptive scheduling is better for time-sharing an important tool in deadlock detection and
systems, while non-preemptive is suitable for batch avoidance mechanisms.
systems.
a) Explain object as function arguments with public:
example A() { x = 10; }
In C++, objects can be passed to functions just like friend void show(A); // Friend function
basic data types. They can be passed in three ways: declaration
Pass by value – A copy of the object is passed. };
Pass by reference – A reference to the original
object is passed. void show(A a) {
Pass by pointer – The memory address of the cout << "Value of x is: " << a.x << endl;
object is passed. }
This helps in performing operations on class data c) What is class Template? Explain syntax of class
members using functions. template with example
Example: A class template allows writing generic classes that
#include <iostream> can handle any data type. It is part of generic
using namespace std; programming in C++. Templates improve code
reusability and type safety.
class Box { Syntax:
int length; template <class T>
public: class ClassName {
Box(int l) { length = l; } T var;
void display(Box b) { public:
cout << "Length: " << b.length << endl; ClassName(T v) { var = v; }
} void show() { cout << var << endl; }
}; };
Example:
int main() { #include <iostream>
Box b1(10); using namespace std;
b1.display(b1); // Object passed as argument
return 0; template <class T>
} class Calculator {
b) Explain different characteristics of friend T a, b;
function public:
A friend function is a non-member function that Calculator(T x, T y) { a = x; b = y; }
has access to the private and protected members T add() { return a + b; }
of a class. It is declared using the friend keyword };
inside the class.
Characteristics: int main() {
Not a class member – It is defined outside the class Calculator<int> c1(5, 10);
but has access to private data. cout << "Sum: " << c1.add() << endl;
Can access private members – Acts as a bridge
between two classes. Calculator<float> c2(5.5, 2.5);
Does not use this pointer – Since it's not a member cout << "Sum: " << c2.add() << endl;
function.
Can be a friend to multiple classes – One friend return 0;
function can access multiple unrelated classes. }
Useful in operator overloading – Especially when
the left operand is not an object of the class.
Example:
class A {
int x;
d) Program to overload binary '+' operator to add try {
two strings if (b == 0)
In C++, operator overloading allows custom throw "Division by zero!";
behavior for operators. To concatenate strings using cout << a / b;
the + operator, we can overload it in a class. }
Program: catch (const char* msg) {
#include <iostream> cout << "Exception: " << msg << endl;
#include <string> }
using namespace std; return 0;
}
class MyString { c) Program to count number of times display() is
string str; called using static data member
public: A static data member is shared by all objects of the
MyString(string s) { str = s; } class and retains its value across function calls. It
can be used to count function calls.
MyString operator+(MyString obj) { Program:
return MyString(str + obj.str); #include <iostream>
} using namespace std;

void display() { class Demo {


cout << str << endl; static int count; // Static data member
} public:
}; void display() {
count++;
int main() { cout << "Display called " << count << " times"
MyString s1("Hello "); << endl;
MyString s2("World!"); }
MyString s3 = s1 + s2; };

s3.display(); // Output: Hello World! // Definition of static member


return 0; int Demo::count = 0;
}
b) Explain try, catch and throw in exception int main() {
handling Demo d1, d2;
In C++, exception handling is used to manage d1.display();
runtime errors or unusual conditions in a program d2.display();
without crashing it. The three key components are: d1.display();
try block: Contains code that may cause an return 0;
exception. }
throw statement: Used to signal the occurrence of Output:
an exception. Display called 1 times
catch block: Handles the exception thrown by the Display called 2 times
throw statement. Display called 3 times
Example:
#include <iostream>
using namespace std;

int main() {
int a = 5, b = 0;
d) What is Destructor? State the importance of creation. This allows flexibility in initializing an
destructor with example object with specific values.
A destructor is a special member function in C++ Example:
that is automatically invoked when an object goes #include <iostream>
out of scope. It has the same name as the class but using namespace std;
is preceded by a tilde (~) and has no return type or
parameters. class Rectangle {
Importance of Destructor: int width, height;
Frees dynamically allocated memory. public:
Closes files or releases system resources. // Parameterized constructor
Prevents memory leaks. Rectangle(int w, int h) {
Example: width = w;
#include <iostream> height = h;
using namespace std; }
void display() {
class Test { cout << "Width: " << width << ", Height: " <<
public: height << endl;
Test() { cout << "Constructor called" << endl; } }
~Test() { cout << "Destructor called" << endl; } };
};
int main() {
int main() { Rectangle rect1(10, 5); // Object creation with
Test obj; values passed to constructor
return 0; rect1.display();
} return 0;
Output: }
Constructor called
Destructor called d) Note on Interrupts
e) What is tokens in C++? Explain in detail Interrupts are signals sent to the processor to gain
Tokens are the smallest meaningful elements of a its attention:
C++ program. The compiler breaks the source code They can be hardware interrupts (from devices like
into tokens during lexical analysis. keyboards) or software interrupts (from programs).
Types of Tokens in C++: The CPU pauses its current task, handles the
Keywords – Reserved words (e.g., int, while, class) interrupt via an interrupt handler, then resumes.
Identifiers – Names for variables, functions, classes Interrupts improve efficiency by allowing the CPU
(e.g., sum, display) to perform other tasks instead of waiting.
Constants – Fixed values (e.g., 10, 'a', 3.14) They are crucial for real-time and multitasking
Operators – Symbols that perform operations (e.g., operating systems.
+, -, *, ==) Examples: Timer interrupts, I/O interrupts, and
Punctuators/Separators – Symbols like ;, ,, {}, () system calls.
Strings/Literals – Sequence of characters inside
double quotes (e.g., "Hello")
Example:
int sum = a + b;
b) Explain parameterized constructor with the
help of a suitable example
A parameterized constructor is a constructor that
takes arguments, allowing different values to be
assigned to the data members at the time of object
c) Explain virtual base class with example
A virtual base class is used in multilevel inheritance template <typename T>
to prevent the diamond problem, where a class is T maximum(T a, T b) {
inherited by multiple classes and those classes are return (a > b) ? a : b;
inherited again. The virtual keyword ensures that a }
base class is shared among all derived classes, int main() {
avoiding multiple instances of the same base class. int x = 10, y = 20;
Example: cout << "Maximum of " << x << " and " << y << "
#include <iostream> is " << maximum(x, y) << endl;
using namespace std;
double p = 3.14, q = 2.71;
class Base { cout << "Maximum of " << p << " and " << q << "
public: is " << maximum(p, q) << endl;
Base() { cout << "Base class constructor" << endl;
} return 0;
}; }
class Derived1 : virtual public Base { e) Write a program to overload the binary plus
public: operator to concatenate two strings
Derived1() { cout << "Derived1 class constructor" Operator overloading allows operators to work
<< endl; } with user-defined data types. We can overload the
}; binary + operator to concatenate two strings in a
class Derived2 : virtual public Base { class.
public: Program:
Derived2() { cout << "Derived2 class constructor" #include <iostream>
<< endl; } #include <string>
}; using namespace std;
class Final : public Derived1, public Derived2 { class MyString {
public: string str;
Final() { cout << "Final class constructor" << endl; public:
} MyString(string s) { str = s; }
};
int main() { // Overload + operator to concatenate two
Final obj; // Only one instance of Base class is strings
created MyString operator+(const MyString& obj) {
return 0; return MyString(str + obj.str);
} }
Output: void display() {
Base class constructor cout << str << endl;
Derived1 class constructor }
Derived2 class constructor };
Final class constructor int main() {
d) Write a C++ program to find the maximum of MyString s1("Hello ");
two integer numbers using function template MyString s2("World!");
Function templates allow a function to work with MyString s3 = s1 + s2; // Using overloaded +
any data type. The compiler generates the code for operator
the specific type when the function is called.
Program: s3.display(); // Output: Hello World!
#include <iostream> return 0;
using namespace std; }
1. What is the ambiguity that arises in multiple 8. What is a file pointer? Write a note on file
inheritance? How can it be overcome? opening and file closing.
In multiple inheritance, ambiguity arises when two A file pointer in C++ is an internal pointer that
or more base classes have methods or data keeps track of the current position within the file. It
members with the same name, and a derived class helps in reading or writing data at specific positions
inherits from them. The compiler cannot decide in a file.
which version of the function or member to call, File Opening:Files are opened using ifstream for
causing confusion. reading, ofstream for writing, and fstream for both.
Virtual Inheritance: This is used in cases of The open() function is used to associate a file with
diamond problem to ensure only one copy of the a file stream object.
base class is inherited by the derived class. File Closing:The close() function is used to close an
Renaming methods: By renaming the functions in open file.It is important to close files to free up
derived classes, we can eliminate name conflicts. system resources.
2. Explain exception handling mechanism in C++ 1. Explain advantages of PHP built-in
Exception handling in C++ allows you to handle functions
runtime errors (exceptions) through a mechanism PHP built-in functions offer predefined solutions for
consisting of three keywords: try, throw, and catch. common tasks such as string manipulation, file
This helps to avoid program termination when an handling, and mathematical operations. They save
error occurs. time, improve reliability, and increase performance
3. Explain class template and function template by being optimized. These functions are thoroughly
In C++, templates enable writing generic code that tested, reducing the likelihood of errors and
works with any data type. Class templates and ensuring code consistency. They also enhance code
function templates are the two main types of readability and make maintenance easier. By using
templates: these functions, developers can focus on more
complex tasks without reinventing the wheel.
1.Class Template: It allows defining a class that can
work with any data type.
2.Function Template: It allows defining a function 2. Explain GET & POST Method
The GET method sends data as part of the URL,
to work with any data type.
making it suitable for retrieving information or
4. Explain namespace
bookmarking, but it has limitations in terms of data
A namespace in C++ is a container used to organize size and security. In contrast, the POST method
and group code into logical units, and prevent sends data in the HTTP request body, which is more
name conflicts. It allows defining variables, secure and capable of handling larger amounts of
functions, and classes that can be referred to using data. While GET is ideal for simple data retrieval,
the namespace name. POST is preferred for submitting sensitive
6. Explain error handling during file operations information, forms, and file uploads. The choice
In C++, errors during file operations can be handled depends on the use case and the amount of data to
using functions like fail(), eof(), bad(), and good() be transmitted.
that are members of the fstream class. These
functions help check if an operation has succeeded 3. List advantages of PHP
or failed. PHP is an open-source, cross-platform scripting
Common error handling functions: language ideal for web development. It integrates
fail(): Returns true if the last operation failed. seamlessly with databases, especially MySQL, and
eof(): Returns true if the end of the file is reached. provides a rich set of built-in functions to simplify
bad(): Returns true if there is an irrecoverable error. development. PHP’s syntax is easy to learn, and it
good(): Returns true if no errors occurred. offers fast performance for dynamic websites. With
strong community support, it is a popular choice for
building robust web applications. PHP’s ability to
work with various web servers like Apache and
Nginx makes it versatile for different environments.

You might also like