C++ Solve PYQ
C++ Solve PYQ
(a) State the important features of object- oriented programming. Compare the object-oriented
programming with procedure-oriented programming.
(iii) Encapsulation
(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;
}
};
(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;
}
};
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;
}
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.
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.
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.
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;
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.
class Animal {
public:
virtual void sound() { cout << "Animal makes a sound" << endl; } // Virtual 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)
ACCOUNT
ADMIN experience
MASTER Name
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.).
int main() {
// Creating an object of ofstream to write to a file
ofstream myfile("example.txt");
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.
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.
class A {
public:
void show()
{
cout << "Hello from A \n";
}
};
int main()
{
D object;
object.show();
}
class A {
public:
void show() { cout << "Base class A\n"; }
};
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"; }
};
int main() {
Base* b;
Derived d;
b = &d;
b->display(); // Calls Derived class method
return 0;
}
class Animal {
public:
virtual void sound() = 0; // Pure virtual function
};
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; };
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
};
Example Program:
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
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;
}
};
int main() {
Animal* animalPtr; // Base class pointer
Dog dog;
Cat cat;
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:
int main() {
int a = 5;
double b = 5.5;
class Parent {
public:
void GeeksforGeeks_Print()
{
cout << "Base Function" << endl;
}
};
int main()
{
Child Child_Derived;
Child_Derived.GeeksforGeeks_Print();
return 0;
}
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).
(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.
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.
. (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:
class Rectangle {
public:
int length, width;
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.
class Rectangle {
public:
int length, width;
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.
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;
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.
// 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.
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.
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 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.
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);
};
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.
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.
(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.).
int main() {
// Creating an object of ofstream to write to a file
ofstream myfile("example.txt");
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.
(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
(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:
(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 in simple words and easy way to understand in 300 to 400 words