0% found this document useful (0 votes)
13 views40 pages

C++ Solve PYQ

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

C++ Solve PYQ

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

2023

(a) State the important features of object- oriented programming. Compare the object-oriented
programming with procedure-oriented programming.

Important Features of Object-Oriented Programming (OOP)


1. Objects
o Objects are the basic building blocks of OOP.
o They represent real-world entities like a car, a person, or a bank account.
o Each object contains data (attributes) and functions (methods) that operate on
the data.
2. Classes
o Classes are blueprints for creating objects.
o A class defines the structure and behavior (data and methods) that its objects will
have.
3. Encapsulation
o Encapsulation means bundling data (attributes) and methods (functions) together
within a class.
o It protects the data from direct access and only allows controlled access through
methods.
4. Inheritance
o Inheritance allows one class (child) to inherit the properties and methods of
another class (parent).
o It promotes code reuse and helps in building hierarchical relationships.
5. Polymorphism
o Polymorphism allows one function or method to behave differently based on the
object calling it.
o Example: A method named draw() can behave differently for Circle and Square.
6. Abstraction
o Abstraction hides unnecessary details from the user and shows only the
essential features.
o Example: When you drive a car, you don’t need to understand how the engine
works.
7. Message Passing
o Objects communicate with each other by calling methods and passing data, just
like sending messages.

Comparison: Object-Oriented Programming vs. Procedure-Oriented Programming


Procedure-Oriented
Aspect Object-Oriented Programming (OOP)
Programming (POP)
Basic Unit Object (real-world entities). Function (set of instructions).
Focuses on procedures (logic or
Focus Focuses on data and operations on data.
functions).
Procedure-Oriented
Aspect Object-Oriented Programming (OOP)
Programming (POP)
Provides better security through Data is less secure as it is globally
Data Security
encapsulation. accessible.
Code Achieved through inheritance and Reusability is limited; functions
Reusability polymorphism. need to be redefined.
Example C++, Java, Python. C, Pascal, FORTRAN.
Bottom-up approach (focuses on creating Top-down approach (solving the
Approach
reusable components first). problem step by step).
Better suited for complex and large Suitable for small and simple
Scalability
systems. programs.
Real-World Easy to map real-world problems into Difficult to map real-world
Mapping code using objects and classes. problems directly.
In short, OOP is more organized, reusable, and secure compared to POP, making it ideal for
modern programming needs.

(b) Write short notes on the following with cxample:

(i) Message passing ‫د‬

(ii) Access specifiers

(iii) Encapsulation

(iv) Scope resolution operator

Short Notes on C++ Concepts


(i) Message Passing
 Objects in C++ communicate with each other by calling methods and passing data.
 It’s like sending a message to an object to perform a task.
 Example:
 class Car {
 public:
 void start() {
 cout << "Car is starting!" << endl;
 }
 };

 int main() {
 Car myCar;
 myCar.start(); // Message sent to 'myCar' object
 return 0;
 }
(ii) Access Specifiers
 Define how members (data/functions) of a class can be accessed.
 Types:
o Private: Accessible only within the class.
o Protected: Accessible within the class and derived classes.
o Public: Accessible from anywhere.
 Example:
 class Student {
 private:
 int rollNo; // Private
 public:
 void setRollNo(int r) {
 rollNo = r; // Public method to set private data
 }
 int getRollNo() {
 return rollNo;
 }
 };

(iii) Encapsulation
 Combining data (attributes) and methods (functions) into a single unit (class).
 Protects data by restricting direct access and allowing controlled access via methods.
 Example:
 class BankAccount {
 private:
 int balance; // Private data
 public:
 void deposit(int amount) {
 balance += amount; // Controlled access
 }
 int getBalance() {
 return balance;
 }
 };

(iv) Scope Resolution Operator (::)


 Used to define a function outside the class or to access global variables.
 Syntax: ClassName::FunctionName
 Example:
 class Demo {
 public:
 void show(); // Declaration inside class
 };

 void Demo::show() { // Definition outside class
 cout << "Using scope resolution operator!" << endl;
 }

 int main() {
 Demo d;
 d.show();
 return 0;
 }

(c) Explain the role of abstraction in object languages. Compare the features of Classes and
Structure in C++.
Role of Abstraction in Object-Oriented Languages
 Abstraction hides unnecessary details and shows only the essential features of an
object.
 It helps in managing complexity and focusing on what an object does rather than how it
does it.
 In C++, abstraction is achieved using classes and access specifiers (private,
protected, public).
 Example:
 class Car {
 public:
 void drive() { // Only the essential feature is exposed
 cout << "Driving the car!" << endl;
 }
 private:
 void engineDetails() { // Hidden details
 cout << "Engine info hidden." << endl;
 }
 };

Comparison: Classes vs. Structures in C++


Feature Class Structure
Default Access Members are private by default. Members are public by default.
Encapsulation Fully supports encapsulation. Limited support for encapsulation.
Inheritance Can be used for inheritance. Cannot be used for inheritance.
Functionality Can include methods (functions). Can also include methods (like classes).
Used for complex and larger Used for simpler and lightweight
Use Case
programs. programs.
Example
Code Example:
```cpp ```cpp
Feature Class Structure
class MyClass { struct MyStruct {
private: int age;
int data; };
};
(d)what is constructor?
Constructor in C++
A constructor is a special member function in a class that is automatically called when an
object of the class is created. It is used to initialize objects.
Types of Constructors:
1. Default Constructor: A constructor with no parameters. It initializes objects with default
values.
Example:
cpp
Copy code
class Car {
public:
Car() { cout << "Car created" << endl; } // Default constructor
};

int main() {
Car c; // Calls the default constructor
return 0;
}
2. Parameterized Constructor: A constructor that takes arguments to initialize an object
with specific values.
Example:
cpp
Copy code
class Car {
private:
int speed;
public:
Car(int s) { speed = s; } // Parameterized constructor
void display() { cout << "Speed: " << speed << endl; }
};

int main() {
Car c(100); // Calls parameterized constructor
c.display(); // Output: Speed: 100
return 0;
}
3. Copy Constructor: A constructor that initializes an object by copying values from
another object of the same class.
Example:
cpp
Copy code
class Car {
private:
int speed;
public:
Car(int s) { speed = s; }
Car(const Car &c) { speed = c.speed; } // Copy constructor
void display() { cout << "Speed: " << speed << endl; }
};

int main() {
Car c1(100);
Car c2 = c1; // Calls copy constructor
c2.display(); // Output: Speed: 100
return 0;
}

2. (a) Describe, what do you mean by nesting of classes. Also explain briefly how Friend
Function is important in C++.
Nesting of Classes
 Definition: Nesting of classes means defining one class inside another class.
 Purpose: It helps in logically grouping related classes to improve code organization and
access control.
 The inner class has access to the private members of the outer class.
Example:
class Outer {
class Inner { // Nested class
public:
void show() {
cout << "This is the nested class!" << endl;
}
};
public:
void display() {
Inner obj; // Accessing nested class
obj.show();
}
};

int main() {
Outer obj;
obj.display();
return 0;
}

Friend Function in C++


 Definition: A friend function is a function that is not a member of a class but can access
its private and protected members.
 Importance:
o Provides controlled access to private data.
o Useful for operator overloading and cases where two classes need to share data.
Example:
class Box {
private:
int width;
public:
Box(int w) : width(w) {}
friend void showWidth(Box b); // Friend function declaration
};

void showWidth(Box b) {
cout << "Width: " << b.width << endl; // Accessing private member
}

int main() {
Box b(10);
showWidth(b); // Calling friend function
return 0;
}
Key Point: Friend functions break encapsulation slightly but are essential for specific use
cases.

(b) What happens if we have the following two functions?

Int Area (int width, int length = 1); Int Area (int Size); Will these overloads? There are a different
number of parameters, but the first one has a default value.(Code based function Overloading)

(c) Define inline functions. Mention the situations where declaration of a function as inline is not
recommended. Write a C++ program with an inline function to add 3 numbers.

Inline Functions in C++


 Definition:
An inline function is a function whose code is directly inserted at the point of the function
call during compilation, avoiding the overhead of a function call.
o Use the keyword inline before the function definition.
 Purpose:
Inline functions are used to improve performance, especially for small functions.

When Not to Use Inline Functions


1. Complex Functions:
Avoid using inline for large or complex functions because it increases code size (causes
code bloat).
2. Loops and Recursions:
Functions with loops, recursion, or static variables should not be declared as inline.
3. Frequent Changes:
If the function's code changes often, making it inline can lead to slower recompilation.

Example: Inline Function to Add 3 Numbers


#include <iostream>
using namespace std;

inline int add(int a, int b, int c) {


return a + b + c; // Inline function to add 3 numbers
}

int main() {
int x = 10, y = 20, z = 30;
cout << "Sum: " << add(x, y, z) << endl; // Inline function call
return 0;
}
Output:
Sum: 60
Key Point: Inline functions are ideal for small, frequently used functions to reduce function call
overhead.

(d) What is Polymorphism ? Explain the types of polymorphism with example


Polymorphism in C++
Polymorphism is a concept in object-oriented programming (OOP) where a function or an
object behaves in multiple ways based on the context. It allows methods to perform different
tasks based on the type of object or the number of parameters passed.
There are two main types of polymorphism in C++:

1. Compile-time Polymorphism (Static Polymorphism)


This type of polymorphism is resolved during the compilation of the program. It is achieved
through function overloading and operator overloading.
Function Overloading:
When multiple functions with the same name perform different tasks depending on the number
or types of parameters.
Example:
#include <iostream>
using namespace std;

class Print {
public:
void display(int a) {
cout << "Integer: " << a << endl;
}

void display(double a) {
cout << "Double: " << a << endl;
}
};

int main() {
Print p;
p.display(10); // Calls display(int)
p.display(3.14); // Calls display(double)
return 0;
}
 Explanation: The function display() is overloaded to handle both int and double types.
Operator Overloading:
When you define a custom behavior for operators like +, -, *, etc., for objects of a class.
Example:
#include <iostream>
using namespace std;

class Complex {
public:
int real, imag;

Complex(int r, int i) : real(r), imag(i) {}

Complex operator + (Complex const &other) {


return Complex(real + other.real, imag + other.imag);
}

void display() {
cout << real << " + " << imag << "i" << endl;
}
};

int main() {
Complex c1(3, 4), c2(1, 2);
Complex c3 = c1 + c2; // Calls overloaded + operator
c3.display(); // Output: 4 + 6i
return 0;
}
 Explanation: The + operator is overloaded to add two Complex numbers.

2. Run-time Polymorphism (Dynamic Polymorphism)


This type of polymorphism is resolved during program execution. It is achieved through
inheritance and virtual functions.
Virtual Functions and Inheritance:
A function is declared as virtual in the base class, and it can be overridden in the derived class.
The correct function is called based on the type of the object at runtime.
Example:
#include <iostream>
using namespace std;

class Animal {
public:
virtual void sound() { cout << "Animal makes a sound" << endl; } // Virtual function
};

class Dog : public Animal {


public:
void sound() override { cout << "Dog barks" << endl; } // Overridden function
};

class Cat : public Animal {


public:
void sound() override { cout << "Cat meows" << endl; } // Overridden function
};

int main() {
Animal* animal;
Dog d;
Cat c;

animal = &d;
animal->sound(); // Output: Dog barks

animal = &c;
animal->sound(); // Output: Cat meows

return 0;
}
 Explanation: The function sound() is a virtual function in the base class Animal, and it's
overridden in both Dog and Cat. The function call depends on the actual object (either
Dog or Cat) at runtime.

Summary:
Type of
Explanation Example
Polymorphism
Compile-time Resolved at compile-time. Achieved through Function overloading,
(Static) function and operator overloading. operator overloading.
Run-time Resolved at runtime. Achieved through Virtual functions and
(Dynamic) inheritance and virtual functions. inheritance.
 Compile-time Polymorphism: Function and operator overloading.
 Run-time Polymorphism: Virtual functions and inheritance. The appropriate function is
chosen based on the object type during execution.
Polymorphism allows flexibility and reusability in code, where the same interface can represent
different underlying forms.

3. (a) A shopkeeper wants to maintain the stock database category wise (electronics
appliances, food items, clothing, milk product, kitchen product). Specify all the classes and
functions as per the relation between different products.
(Diagram)

PERSON Name code

ACCOUNT

ADMIN experience

MASTER Name

code Experience pay

Does this type inheritance lead to ambiguity? If yes, discuss by putting up a suitable scenario
how it can be removed

b. Coding
(i) Write names of member functions, which are accessible from the objects of class Gamma.

(ii) Write the name of the data members, which are accessible from the member function of
class Beta.

(iii) Name the base class and the derived class of class Beta.
(iv) Name the base class and derived class of class Gamma.

(c) Create a class named complex with two members real and imaginary of float data type.
Show how we can perform the following operation: C=C+C using operator overloading.

(d) What are various file opening modes? Write a pro in C++ for creating file.
File Opening Modes in C++
In C++, when working with files, we use different file opening modes to specify how the file
should be opened (e.g., for reading, writing, appending, etc.).
Here are the common file opening modes:
Mode Description
ios::in Open for reading (file must exist).
ios::out Open for writing (creates a new file or truncates an existing file).
ios::app Open for appending (data is written at the end of the file).
ios::ate Open and move to the end of the file (but allows writing at any position).
ios::trunc Truncate the file (remove existing content) when opened for writing.
ios::binary Open in binary mode (for non-text files like images, etc.).

Example Program to Create a File in C++


This program demonstrates how to create and write to a file using ios::out mode.
#include <iostream>
#include <fstream> // For file handling
using namespace std;

int main() {
// Creating an object of ofstream to write to a file
ofstream myfile("example.txt");

// Check if the file was successfully created


if (myfile.is_open()) {
// Writing some data to the file
myfile << "Hello, this is a sample file.\n";
myfile << "This file is created using C++.\n";
myfile << "We are using the ios::out mode to create the file.\n";

// Close the file after writing


myfile.close();
cout << "File created and data written successfully!" << endl;
} else {
cout << "Unable to open the file!" << endl;
}

return 0;
}
Explanation:
 ofstream myfile("example.txt"): This line opens a file named "example.txt" in output
mode (ios::out).
 If the file is successfully opened, it writes text into the file using the << operator.
 myfile.close(): Closes the file after writing.

Summary of File Opening Modes:


 ios::in: Open for reading.
 ios::out: Open for writing (creates/truncates the file).
 ios::app: Open for appending (adds to the end).
 ios::ate: Open for writing, but start at the end.
 ios::trunc: Truncate the file (remove old content).
 ios::binary: Open in binary mode.
These modes help determine how you interact with files in C++.

4.(a) Explain virtual base class, abstract classes, virtual function and pure virtual function
Summary:
Feature Description Purpose
Virtual Base Avoids ambiguity in multiple Ensures one instance of the base class.
Class inheritance.
Abstract Class Cannot be instantiated. Serves as a blueprint for derived classes.
Resolves at runtime (dynamic
Virtual Function Enables runtime polymorphism.
binding).
Pure Virtual Forces derived classes to Makes the class abstract, ensures specific
Function implement it. behavior.

Virtual base class


#include <iostream>
using namespace std;

class A {
public:
void show()
{
cout << "Hello from A \n";
}
};

class B : public virtual A {


};
class C : public virtual A {
};

class D : public B, public C {


};

int main()
{
D object;
object.show();
}

Virtual Base Class


A virtual base class prevents multiple copies of a base class when using multiple
inheritance. It ensures only one instance of the base class is shared by all derived classes.
Example:
#include <iostream>
using namespace std;

class A {
public:
void show() { cout << "Base class A\n"; }
};

class B : virtual public A {}; // Virtual inheritance


class C : virtual public A {};
class D : public B, public C {};

int main() {
D obj;
obj.show(); // No ambiguity
return 0;
}

Abstract Class
An abstract class is a class that cannot be instantiated. It is created to be a base class and
must contain at least one pure virtual function.
Example:
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
class Circle : public Shape {
public:
void draw() { cout << "Drawing Circle\n"; }
};

Virtual Function
A virtual function allows runtime polymorphism. It ensures that the derived class's function is
called when accessed through a base class pointer.
Example:
#include <iostream>
using namespace std;

class Base {
public:
virtual void display() { cout << "Base class\n"; }
};

class Derived : public Base {


public:
void display() override { cout << "Derived class\n"; }
};

int main() {
Base* b;
Derived d;
b = &d;
b->display(); // Calls Derived class method
return 0;
}

Pure Virtual Function


A pure virtual function is declared by assigning = 0 in the base class. It forces derived classes
to provide their implementation.
Example:
#include <iostream>
using namespace std;

class Animal {
public:
virtual void sound() = 0; // Pure virtual function
};

class Dog : public Animal {


public:
void sound() { cout << "Bark\n"; }
};

int main() {
Dog d;
d.sound(); // Calls Dog's implementation
return 0;
}

Comparison: Virtual Base Class, Abstract Class, Virtual Function, and Pure Virtual
Function
Virtual Base Pure Virtual
Feature Abstract Class Virtual Function
Class Function
Prevents multiple
copies of a base A function declared
A class that has at A virtual function
class when with the virtual
Definition least one pure with = 0 in the base
multiple keyword in the
virtual function. class.
inheritance is base class.
used.
Solves the Serves as a
Allows runtime Ensures derived
"diamond blueprint for
polymorphism classes must
Purpose problem" in derived classes
(function implement the
multiple and cannot be
overriding). function.
inheritance. instantiated.
Can have data Can have both
Can have an Cannot have an
members and implemented and
Implementation implementation in implementation in
functions like any pure virtual
the base class. the base class.
normal class. functions.
Makes the base
Does not restrict
Can be Cannot be class abstract and
Instantiation instantiation of the
instantiated. instantiated. prevents
base class.
instantiation.
Used with virtual
Used as a base Can be overridden Mandatory to
keyword to share
Inheritance class for other in derived classes, override in derived
a single instance
derived classes. but not mandatory. classes.
of a base class.
Defines an
Useful in complex
interface or Provides optional Provides mandatory
multiple
Use Case common behavior overriding capability overriding capability
inheritance
for all derived for derived classes. for derived classes.
scenarios.
classes.
Example class Derived : class Abstract virtual void func() { } virtual void func() =
Virtual Base Pure Virtual
Feature Abstract Class Virtual Function
Class Function
virtual public Base { virtual void func()
Syntax 0;
{ }; = 0; };

4. (a) Justify the following statement as a suitable example:


"In a class hierarchy of several levels, if we want a function at any level to be called through a
base class pointer, then the function must be declared as virtual in the base class."

Justification of the Statement


In a class hierarchy, if a base class pointer is used to call a function, and the derived class
overrides that function, the base class function will be called unless the function is declared as
virtual. Declaring the function as virtual ensures that the derived class's function is called
instead.

Key Points:
1. Virtual Function:
o A virtual function in the base class allows the derived class to override it.
o The function called is determined at runtime (dynamic binding).
2. Why Use Virtual Functions?
o Ensures correct function execution when using base class pointers to refer to
derived class objects.

(b) (i) What is Abstract Class? What is the significance of pure virtual function in a class? How
are they different from normal functions?
What is an Abstract Class?
 An abstract class is a class that cannot be instantiated (you can’t create objects from
it).
 It serves as a blueprint for derived classes.
 It usually contains at least one pure virtual function.
Example:
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};

What is a Pure Virtual Function?


 A pure virtual function is a function declared in a class but not defined in it.
 Syntax:
 virtual void functionName() = 0;
 Derived classes must override the pure virtual function.
Example:
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};

class Circle : public Shape {


public:
void draw() override {
cout << "Drawing a Circle" << endl;
}
};

Significance of Pure Virtual Functions


1. Enforcing Overriding:
Ensures that derived classes implement the function.
2. Supports Polymorphism:
Allows handling of multiple derived classes through a base class pointer.
3. Code Reusability:
Shared functionality can be implemented in the abstract class.

Difference Between Normal and Pure Virtual Functions


Feature Normal Function Pure Virtual Function
Definition in Base Defined and implemented in the Declared but not implemented in the
Class base class. base class.
Override in Derived
Optional to override. Must be overridden.
Class
Instantiation Can create objects of the class. Cannot create objects of the class.

Example Program:
#include <iostream>
using namespace std;

class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};

class Circle : public Shape {


public:
void draw() override {
cout << "Drawing Circle" << endl;
}
};
int main() {
Shape* shape = new Circle();
shape->draw(); // Calls the overridden function
delete shape;
return 0;
}
Output:
Drawing Circle
Key Point: Abstract classes and pure virtual functions enable polymorphism and enforce
implementation in derived classes.

(ii) Write a program to illustrate runtime polymorphism using virtual function.


Runtime Polymorphism in C++ using Virtual Function
 Runtime polymorphism allows the program to decide which function to call at runtime
(not compile-time), based on the object type.
 This is achieved using virtual functions.

Example Program:
#include <iostream>
using namespace std;

// Base class
class Animal {
public:
// Virtual function
virtual void sound() {
cout << "Animal makes a sound" << endl;
}
};

// Derived class
class Dog : public Animal {
public:
// Overriding the virtual function
void sound() override {
cout << "Dog barks" << endl;
}
};

// Another derived class


class Cat : public Animal {
public:
// Overriding the virtual function
void sound() override {
cout << "Cat meows" << endl;
}
};

int main() {
Animal* animalPtr; // Base class pointer

Dog dog;
Cat cat;

// Runtime polymorphism: The function call depends on the object type


animalPtr = &dog;
animalPtr->sound(); // Calls Dog's sound()

animalPtr = &cat;
animalPtr->sound(); // Calls Cat's sound()

return 0;
}

Explanation:
 Base class Animal has a virtual function sound().
 Derived classes Dog and Cat override the sound() function.
 At runtime, the correct sound() function (Dog's or Cat's) is called based on the actual
object type, even though the base class pointer is used.

Output:
Dog barks
Cat meows

Key Point:
 Virtual functions ensure the function call is resolved at runtime (dynamic binding).

(c) With the help of an example program, differentiate between the following:

(i) Overloading vs. Overriding


Differences Between Overloading and Overriding
Feature Overloading Overriding
Same function name with Same function name and parameters in
Definition
different parameters. base and derived class.
Function Signature Different function signatures Same function signature in both base and
Feature Overloading Overriding
(parameters). derived class.
Must be the same in base and derived
Return Type Can be the same or different.
classes.
Compile-time or
Compile-time polymorphism. Runtime polymorphism.
Runtime
Not required, can be in the
Inheritance Required, must be in a derived class.
same class.
Access to Function selected at compile
Function selected at runtime (via virtual).
Function time.

Overloading Using Different Number of Parameters


#include <iostream>
using namespace std;

// function with 2 parameters


void display(int var1, double var2) {
cout << "Integer number: " << var1;
cout << " and double number: " << var2 << endl;
}

// function with double type single parameter


void display(double var) {
cout << "Double number: " << var << endl;
}

// function with int type single parameter


void display(int var) {
cout << "Integer number: " << var << endl;
}

int main() {

int a = 5;
double b = 5.5;

// call function with int type parameter


display(a);

// call function with double type parameter


display(b);

// C++ program to demonstrate compile time function overriding


#include <iostream>
using namespace std;

class Parent {
public:
void GeeksforGeeks_Print()
{
cout << "Base Function" << endl;
}
};

class Child : public Parent {


public:
void GeeksforGeeks_Print()
{
cout << "Derived Function" << endl;
}
};

int main()
{
Child Child_Derived;
Child_Derived.GeeksforGeeks_Print();
return 0;
}

(ii) Early binding vs. Late binding


Feature Early Binding Late Binding
The method call is resolved at compile- The method call is resolved at
Definition
time. runtime.
Also Known
Static binding or Compile-time binding. Dynamic binding or Runtime binding.
As
Function overriding (with virtual
Example Function overloading.
functions).
The compiler knows which function to The compiler does not know which
Binding
call based on the function signature at function to call; it is determined during
Process
compile-time. execution.
Faster, since the function call is Slower, due to the decision-making
Performance
resolved during compilation. process at runtime.
Used for virtual functions in
Usage Used for non-virtual functions.
polymorphism.
Less flexible, since the function cannot More flexible, allows for dynamic
Flexibility
be changed at runtime. behavior changes.
5. (a) What is Template ? Differentiate between function template and class template. Write a
function template for finding the maximum value in an array.
What is a Template in C++?
A template is a feature in C++ that allows writing generic functions or classes. It enables the
creation of functions or classes that work with any data type.
Templates are used to define functions or classes that can operate on different data types
without being rewritten for each type.

Difference Between Function Template and Class Template


Feature Function Template Class Template
A function template is used to create a A class template is used to create a
Definition
function that can work with any data type. class that can work with any data type.
Usage Defines a function for multiple data types. Defines a class for multiple data types.
Syntax template <typename T> before a function. template <typename T> before a class.

Function Template Example: Finding Maximum Value in an Array


#include <iostream>
using namespace std;

// Function template for finding the maximum value


template <typename T>
T findMax(T arr[], int size) {
T max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}

int main() {
int intArr[] = {3, 5, 2, 8, 1};
double doubleArr[] = {3.5, 2.1, 8.3, 1.9};

cout << "Max of int array: " << findMax(intArr, 5) << endl; // Calls findMax with int
cout << "Max of double array: " << findMax(doubleArr, 4) << endl; // Calls findMax with
double

return 0;
}
Output:
Max of int array: 8
Max of double array: 8.3

Summary:
 Function Template: Used to define functions that can work with different data types
(like the findMax function).
 Class Template: Used to define classes that can work with different data types.

(b) What is Stream? Explain the hierarchy of C++ Stream classes. Write a C++ program to get
employee id and salary of an employee of a Water Treatment Chemical Company from the user
and store these details into a file called 'employee.dat'. Also read the details from the file and
display the data.
What is a Stream in C++?
A stream in C++ is a flow of data. It is used to perform input and output (I/O) operations.
Streams are used to read from or write to different devices, like files or the console.
 Input Stream: Used to read data (e.g., cin).
 Output Stream: Used to write data (e.g., cout).

Hierarchy of C++ Stream Classes


Here is the hierarchy of C++ stream classes:
arduino
Copy code
iostream (Base Class)
├── istream (Input Stream)
│ └── ifstream (File Input Stream)
├── ostream (Output Stream)
│ └── ofstream (File Output Stream)
└── fstream (File Stream - Both Input and Output)
 iostream: The base class for input and output.
 istream: Handles input operations.
 ostream: Handles output operations.
 fstream: Used for both input and output operations with files.

(c) What are exceptions? How is an exception handled in C++? What is the need of exception
handling? Write a program that throws an arithmetic exception as and when a number input is a
negative number.
What are Exceptions in C++?
An exception is an unexpected event or error that occurs during the execution of a program.
When an exception occurs, the normal flow of the program is interrupted, and it tries to handle
the error gracefully instead of crashing.

How is an Exception Handled in C++?


C++ provides a mechanism to handle exceptions using the try, throw, and catch blocks:
 try block: Contains the code that may cause an exception.
 throw statement: Used to throw an exception when an error occurs.
 catch block: Catches and handles the exception.

Need for Exception Handling


 To prevent the program from crashing due to runtime errors.
 To provide a way to handle errors and continue execution of the program.
 To separate error-handling code from regular code.

C++ Program to Throw an Arithmetic Exception for Negative Input


#include <iostream>
#include <stdexcept> // For throwing standard exceptions
using namespace std;

int getNumber() {
int num;
cout << "Enter a positive number: ";
cin >> num;
if (num < 0) {
throw std::invalid_argument("Negative number entered!"); // Throw an exception
}
return num;
}

int main() {
try {
int num = getNumber(); // Call the function that may throw an exception
cout << "You entered: " << num << endl;
}
catch (std::invalid_argument& e) { // Catch the thrown exception
cout << "Error: " << e.what() << endl; // Handle the exception
}
return 0;
}

Explanation:
 getNumber(): Prompts the user to enter a number. If the number is negative, it throws
an exception.
 throw: Used to raise an exception when a negative number is entered.
 catch: Catches the thrown exception and displays an error message.

Output:
Enter a positive number: -5
Error: Negative number entered!

Summary:
 Exception: An unexpected event that disrupts the normal flow of the program.
 Exception Handling: Uses try, throw, and catch to handle errors and prevent program
crashes.
 Need: Helps in gracefully handling errors and continuing program execution without
crashes.

Or

What is STL? What are its components ? Differentiate between Map and Vector
What is STL (Standard Template Library) in C++?
STL (Standard Template Library) is a collection of template classes and functions in C++ that
provides useful data structures and algorithms. It helps in efficient handling of data and
simplifies tasks like sorting, searching, and manipulating collections of data.

Components of STL:
STL consists of four main components:
1. Containers: Store data (e.g., vector, map, list).
2. Algorithms: Perform operations on data stored in containers (e.g., sorting, searching).
3.  Examples: Sorting, searching, counting, transforming.
4.  Examples: sort(), find(), reverse(), max(), min().
5. Iterators: Provide a way to access and traverse data in containers.
Iterators:
 Purpose: Used to access and traverse through elements in containers.
 Types:
o Input Iterator: Reads data.
o Output Iterator: Writes data.
o Forward Iterator: Reads and writes in a forward direction.
o Bidirectional Iterator: Reads and writes in both directions.
o Random Access Iterator: Can access elements randomly.

6. Functors: Function objects that can be used with algorithms to define custom
operations.
Example: Custom operations to use with algorithms, like custom sorting.

Difference Between Map and Vector:


Feature Map Vector
Definition A collection of key-value pairs. A dynamic array (sequence container).
Stores data in sorted order based on Stores elements in the order they are
Order
keys. inserted.
Data Access Access elements by key. Access elements by index.
Feature Map Vector
Duplicate
Does not allow duplicate keys. Allows duplicate values.
Keys
Performance Faster for searching by key. Faster for random access.
Suitable for mapping one value to Suitable for storing lists of elements
Use Case
another (e.g., phone book). (e.g., a collection of items).

. (a) Differentiate between Outside the class definition and inside the class definition of member
example. function with proper

Difference Between Outside the Class Definition and Inside the Class Definition of
Member Functions in C++
In C++, member functions of a class can be defined inside or outside the class definition.
Here's a simple explanation of both:

1. Inside the Class Definition:


 Definition: Member functions are defined directly inside the class body.
 Syntax: You can define the function directly in the class declaration.
 No need for separate definition outside the class.
Example (Inside Class Definition):
#include <iostream>
using namespace std;

class Rectangle {
public:
int length, width;

// Member function inside the class definition


void setDimensions(int l, int w) {
length = l;
width = w;
}

int area() {
return length * width;
}
};

int main() {
Rectangle rect;
rect.setDimensions(5, 3);
cout << "Area: " << rect.area() << endl; // Output: Area: 15
return 0;
}
 Advantages:
o Simple and compact.
o The function definition is immediately available when reading the class.

2. Outside the Class Definition:


 Definition: Member functions are defined outside the class body, after the class
declaration.
 Syntax: You must define the function separately, using the scope resolution operator (::)
to associate it with the class.
Example (Outside Class Definition):
#include <iostream>
using namespace std;

class Rectangle {
public:
int length, width;

// Member function declared inside the class


void setDimensions(int l, int w);
int area();
};

// Function definitions outside the class


void Rectangle::setDimensions(int l, int w) {
length = l;
width = w;
}

int Rectangle::area() {
return length * width;
}

int main() {
Rectangle rect;
rect.setDimensions(5, 3);
cout << "Area: " << rect.area() << endl; // Output: Area: 15
return 0;
}
 Advantages:
o The class definition remains clean and focuses only on declarations.
o Useful when the function implementation is large or in separate files.
Here’s the expanded table with more key differences between defining member functions
inside and outside the class definition:
Feature Inside Class Definition Outside Class Definition
Defined outside the class,
Definition Location Defined within the class body
using :: (scope resolution)
Used for larger, complex
Function Size Used for small, simple functions
functions
Code Readability Compact and easier to read Keeps the class definition clean
Suitable for short member Suitable for separating
Usage
functions implementation from declaration
May have slightly more overhead No inline expansion unless
Performance
due to inline expansion explicitly marked as inline
Easier to maintain for simple Easier to manage in larger
Maintenance
classes projects by separating concerns
Less flexible for large programs, More flexible, allows better
Flexibility
as all logic is in the header organization and modularity
Can be defined directly where the Must be defined outside the
Definition Scope
class is defined class, usually in a .cpp file
Readability in Large Can clutter the class definition Keeps the class declaration
Codebases with too many details minimal and focused
Very common in template
Less common, unless templates
Usage in Templates classes (functions can be defined
are specialized
inline)

Summary:
 Inside the class definition: Ideal for small and simple functions, especially in
templates, but can make the class definition bulky in large programs.
 Outside the class definition: Helps in better code organization and management,
especially for large and complex projects. It also helps separate interface from
implementation.

4.

(a) Write a short note by using suitable example:


static
This.

1. static Keyword in C++


 Definition: The static keyword in C++ is used to extend the lifetime of variables and
functions.
 Usage:
o Inside a function: It makes a variable retain its value between function calls.
o Outside a function: It limits the scope of the variable or function to the file where
it's defined.
Example 1: Static Variable Inside a Function
#include <iostream>
using namespace std;

void counter() {
static int count = 0; // Retains its value between function calls
count++;
cout << "Count: " << count << endl;
}

int main() {
counter(); // Output: Count: 1
counter(); // Output: Count: 2
counter(); // Output: Count: 3
return 0;
}
 Explanation: The variable count is declared as static, so its value persists across
function calls. Each time counter() is called, the value of count increases.
Example 2: Static Variable Outside a Function
#include <iostream>
using namespace std;

static int globalVar = 100; // Visible only within this file

void display() {
cout << "Global Variable: " << globalVar << endl;
}

int main() {
display(); // Output: Global Variable: 100
return 0;
}
 Explanation: globalVar is declared static, so it is limited to the file where it's declared
and cannot be accessed by other files.

2. this Pointer in C++


 Definition: this is a special pointer in C++ that points to the current object of the class.
 Usage: It allows access to the calling object's members and is implicitly passed to all
non-static member functions.
Example: Using this Pointer
#include <iostream>
using namespace std;
class Rectangle {
public:
int length, width;

// Constructor
Rectangle(int l, int w) {
this->length = l; // Using 'this' pointer
this->width = w;
}

// Display function
void display() {
cout << "Length: " << this->length << ", Width: " << this->width << endl;
}
};

int main() {
Rectangle rect(10, 5);
rect.display(); // Output: Length: 10, Width: 5
return 0;
}
 Explanation: The this pointer refers to the current object rect and is used to distinguish
between member variables and parameters when they have the same name.

Summary:
 static: Retains the value of a variable across function calls and limits the scope of
variables/functions to a file.
 this: A pointer that refers to the current object inside non-static member functions. It
helps differentiate member variables from function parameters.

(b)What is the need of Default Argument in function?

Local & Global Variable

1. Default Arguments in Functions


 Definition: Default arguments are values assigned to function parameters in case the
caller does not provide them.
 Need: They make functions more flexible by allowing them to be called with fewer
arguments. If an argument is not passed, the default value is used.
Example: Using Default Arguments
#include <iostream>
using namespace std;
void display(int a, int b = 10) { // 'b' has a default value of 10
cout << "a: " << a << ", b: " << b << endl;
}

int main() {
display(5); // Output: a: 5, b: 10 (b takes the default value)
display(5, 20); // Output: a: 5, b: 20 (b takes the provided value)
return 0;
}
 Explanation: In the function display(), the parameter b has a default value of 10. If not
provided, b uses the default value.

2. Local and Global Variables


 Local Variables:
o Definition: Variables declared inside a function or block. They are only
accessible within that function/block.
o Lifetime: Exist only during the function's execution.
Example: Local Variable
#include <iostream>
using namespace std;

void show() {
int x = 5; // Local variable
cout << "x = " << x << endl;
}

int main() {
show(); // Output: x = 5
// cout << x; // Error: 'x' is not accessible here
return 0;
}
 Explanation: x is a local variable inside the show() function. It cannot be accessed
outside that function.

 Global Variables:
o Definition: Variables declared outside any function, usually at the top of the
program. They are accessible from any function in the program.
o Lifetime: Exist for the entire duration of the program.
Example: Global Variable
#include <iostream>
using namespace std;

int x = 10; // Global variable


void show() {
cout << "x = " << x << endl; // Accessing global variable
}

int main() {
show(); // Output: x = 10
x = 20; // Modifying global variable
show(); // Output: x = 20
return 0;
}
 Explanation: x is a global variable and can be accessed and modified by any function in
the program.

Summary:
 Default Arguments: Allow functions to be called with fewer arguments by using a
predefined value when not provided.
 Local Variables: Defined inside functions or blocks, accessible only within them, and
exist temporarily.
 Global Variables: Defined outside functions, accessible globally throughout the
program, and exist for the entire program’s duration.

(c)Difference between inline function and friend function with example


Difference Between Inline Function and Friend Function
Feature Inline Function Friend Function
A function defined inside the class A function declared outside the class but has
Definition
or with the inline keyword. access to private/protected members.
Direct access to class members Can access private/protected members of
Access
(variables and functions). the class.
Used for small functions to improve Used when a function needs to access
Usage performance by reducing function private data of a class but is not a member of
call overhead. the class.
Definition Defined inside the class or with Defined outside the class with the friend
Location inline keyword outside the class. keyword.
Scope Limited to the function itself. Can access multiple classes' private data.
inline int add(int a, int b) { return a +
Example friend void displayData(MyClass obj);
b; }

Example:
Inline Function:
#include <iostream>
using namespace std;
class MyClass {
public:
inline int square(int x) { return x * x; } // Inline function
};

int main() {
MyClass obj;
cout << "Square of 5 is: " << obj.square(5); // Function call
return 0;
}
Friend Function:
#include <iostream>
using namespace std;

class MyClass {
private:
int secret = 42;

public:
// Declaring the friend function
friend void showSecret(MyClass obj);
};

void showSecret(MyClass obj) {


cout << "The secret is: " << obj.secret; // Access private member
}

int main() {
MyClass obj;
showSecret(obj); // Calling friend function
return 0;
}
Key Differences:
 Inline: Used to define small functions to optimize performance.
 Friend: Used when a function outside the class needs access to private/protected
members of the class.

(d) Write short notes on the following:


(i) Abstract Class
(ii) Access Specifiers
(iii) Virtual Base Class
(iv) Local & Global Variable
(i) Abstract Class
An abstract class is a class that cannot be instantiated (objects cannot be created from it). It is
used as a base class for other classes. It can have pure virtual functions (functions without
implementation) that must be overridden in derived classes.
Example:
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
 A class containing at least one pure virtual function is abstract.
 You cannot create an object of an abstract class.

(ii) Access Specifiers


Access specifiers control the access to the members (variables, functions) of a class. They
define whether other classes or functions can access or modify those members.
1. public: Members are accessible from outside the class.
2. private: Members are only accessible within the class.
3. protected: Members are accessible within the class and by derived classes.
Example:
class MyClass {
public:
int x; // Public member
private:
int y; // Private member
};

(iii) Virtual Base Class


A virtual base class is used in multiple inheritance to ensure that a base class is only inherited
once, even if it appears multiple times in the inheritance chain. It avoids ambiguity.
Example:
class A {
public:
int a;
};

class B : virtual public A {}; // Virtual inheritance


class C : virtual public A {};

class D : public B, public C {


public:
void display() {
cout << a; // No ambiguity, a is inherited only once
}
};
 Virtual base classes prevent multiple copies of a base class when inherited by different
derived classes.

(iv) Local & Global Variables


1. Local Variable: A variable that is declared inside a function or block. It is only
accessible within that function/block and is destroyed once the function ends.
Example:
void myFunction() {
int localVar = 5; // Local variable
}
2. Global Variable: A variable declared outside of all functions. It can be accessed by any
function in the program, and its lifetime lasts for the entire program execution.
Example:
int globalVar = 10; // Global variable

void myFunction() {
cout << globalVar; // Accessing global variable
}
 Key Difference:
o Local variables are limited to the function/block they are declared in.
o Global variables are accessible from anywhere in the program.

2019

1.
(a) Explain briefly character of OOPS language and mention advantages of OOPs approach
over procedural programming.

(b) What is constructor? Explain various types of constructor with example.

(c) Difference between function overloading and function overriding with example.

2.
(a) What is Polymorphism ? Explain the types of polymorphism with example

(b) Difference between inline function and friend function with example.

(c) Does multiple inheritance lead to ambiguity ? If yes, discuss by putting up suitable example
how it can be removed
3.
(a) Write a program to overload a unary minus operator in C++ language.

(b) What are various file opening modes? Write a pro in C++ for creating file.
File Opening Modes in C++
In C++, when working with files, we use different file opening modes to specify how the file
should be opened (e.g., for reading, writing, appending, etc.).
Here are the common file opening modes:
Mode Description
ios::in Open for reading (file must exist).
ios::out Open for writing (creates a new file or truncates an existing file).
ios::app Open for appending (data is written at the end of the file).
ios::ate Open and move to the end of the file (but allows writing at any position).
ios::trunc Truncate the file (remove existing content) when opened for writing.
ios::binary Open in binary mode (for non-text files like images, etc.).

Example Program to Create a File in C++


This program demonstrates how to create and write to a file using ios::out mode.
#include <iostream>
#include <fstream> // For file handling
using namespace std;

int main() {
// Creating an object of ofstream to write to a file
ofstream myfile("example.txt");

// Check if the file was successfully created


if (myfile.is_open()) {
// Writing some data to the file
myfile << "Hello, this is a sample file.\n";
myfile << "This file is created using C++.\n";
myfile << "We are using the ios::out mode to create the file.\n";

// Close the file after writing


myfile.close();
cout << "File created and data written successfully!" << endl;
} else {
cout << "Unable to open the file!" << endl;
}

return 0;
}
Explanation:
 ofstream myfile("example.txt"): This line opens a file named "example.txt" in output
mode (ios::out).
 If the file is successfully opened, it writes text into the file using the << operator.
 myfile.close(): Closes the file after writing.

Summary of File Opening Modes:


 ios::in: Open for reading.
 ios::out: Open for writing (creates/truncates the file).
 ios::app: Open for appending (adds to the end).
 ios::ate: Open for writing, but start at the end.
 ios::trunc: Truncate the file (remove old content).
 ios::binary: Open in binary mode.
These modes help determine how you interact with files in C++.

(c) What is pure virtual functions in C++? Explain with the help of a program.

4.
(a) Explain dynamic memory management? Write a C++ program that shows the use of new
and delete operators.

(b) What is exception handling? What is the sequence of events when exception occurs?

(c) What is Inheritance ? Explain various types of Inheritance and also discuss the advantages
of the inheritance.

5.
(a) Write short notes on the following:
(i) Abstract Class

(ii) Access Specifiers

(iii) Virtual Base Class

(iv) Local & Global Variable

(b) Explain class and function templet using suitable example in C++ programming.

(c) Explain the steps involved in reading and writing a file in a C++ program

2018

1.
(a) Explain all the characteristics of object oriented programming
b) Difference between the following:

(i) Procedural approach. VS. Object oriented

(ii) Structure vs. Class

(c) Explain the use of default argument. Also write a program in C++ to calculate power(p) of a
number(n) using default argument. If power(p) is not given by use then calculate the square of a
number(n).

2.
(a) Explain with example different types of access specifier used in C++. Write a C++ program
in which a private member function is called inside another member function of same class.

(b) Write a program in C++ to add two complex numbers using the concept of passing objects
as arguments.

(c) How pointers are declare and initialize in C++? Also explain pointers to objects and this
pointer using example

3.
(a) Explain the concept of polymorphism with example to overload the unary operator.

(b) Explain Inheritance and types of inheritance used in C++ with proper syntax. Also explain
the concept of visibility mode.

(c) Write a program in C++ to explain the concept of parametrized constructor in multiple
inheritance.

4.
(a) Explain virtual base class, abstract classes, virtual function and pure virtual function.

(b) Write a C++ program that shows the ambiguity resolution in hybrid inheritance through
virtual base class.

(c) Explain the concept of exceptional handling. Also write a program containing a exception.
Use a try block to throw it and a catch block to handle it properly.

5.
(a) Explain generic programming, class template and function template with syntax

(b) Write a C++ program to create a swap() function template that will swap two values of given
types of data.
(c) Explain the concept of file streams in C++.

Write a program in C++ to copy one file into another.

Write in simple words and easy way to understand in 300 to 400 words

You might also like