Q1.What is Inheritance? Write diff types of inheritance with examples.
Ans:-**Inheritance** is one of the fundamental concepts in **Object-Oriented Programming (OOP)**. It allows a class
(called the **derived class** or **child class**) to **inherit** properties and behaviors (fields and methods) from another
class (called the **base class** or **parent class**).
✅
This helps in **code reusability**, **extensibility**, and **maintainability** of software.
### **Syntax (in C++):** class Base { // base class members };
class Derived : public Base { // derived class members };
### **Types of Inheritance in C++ (and many OOP languages):**
#### 1. **Single Inheritance** * One child class inherits from one parent class.
class Animal { public:
void eat() { cout << "Eating...\n"; } };
class Dog : public Animal { public:
void bark() { cout << "Barking...\n"; } };
> `Dog` inherits `eat()` function from `Animal`.
#### 2. **Multiple Inheritance*** A class inherits from more than one base class.
class Father {
public:
void skills() { cout << "Father's skills\n"; } };
class Mother {
public:
void talent() { cout << "Mother's talent\n"; } };
class Child : public Father, public Mother {
// inherits from both Father and Mother };
> `Child` class has access to both `skills()` and `talent()`.
#### 3. **Multilevel Inheritance*** A class is derived from another derived class (i.e., a chain of inheritance).
class Animal {public:
void eat() { cout << "Eating...\n"; } };
class Mammal : public Animal {public:
void walk() { cout << "Walking...\n"; } };
class Dog : public Mammal {public:
void bark() { cout << "Barking...\n"; } };
> `Dog` inherits both `eat()` and `walk()` from `Mammal` and `Animal`.
#### 4. **Hierarchical Inheritance*** Multiple classes inherit from a single base class.
class Animal {public:
void eat() { cout << "Eating...\n"; } };
class Dog : public Animal {public:
void bark() { cout << "Barking...\n"; } };
class Cat : public Animal {
public:
void meow() { cout << "Meowing...\n"; } };
> Both `Dog` and `Cat` inherit the `eat()` function from `Animal`.
#### 5. **Hybrid Inheritance*** A combination of two or more types of inheritance (e.g., multiple + multilevel).
class A {public:
void msgA() { cout << "Class A\n"; } };
class B : public A {public:
void msgB() { cout << "Class B\n"; } };
class C {public:
void msgC() { cout << "Class C\n"; } };
class D : public B, public C {
// Hybrid of multilevel and multiple inheritance };
> `D` inherits `msgA()` from `A` via `B` and also `msgC()` from `C`.
Q3.What is Abstraction? Write a program for demonstration of abstraction mechanism using a pure
virtual function.
Ans:-**Abstraction** is one of the **four main pillars of Object-Oriented Programming (OOP)**. It refers to **hiding the
internal implementation details** and showing only the **essential features** of an object.
%
In simple words, abstraction allows you to focus on **what an object does**, rather than **how it does it**.
### **Why Abstraction?**
* To **reduce complexity**.
* To **increase security** by hiding unnecessary details.
* To provide a **clear interface** to interact with objects.
## ✅ **How is Abstraction implemented in C++?**
There are two main ways:
1. Using **Abstract Classes**
2. Using **Interfaces** (in C++, these are usually abstract classes with only pure virtual functions)
### **Abstract Class**:An abstract class is a class that contains at least **one pure virtual function**.
virtual void functionName() = 0;
Such classes **cannot be instantiated directly**.
## **Example Program: Abstraction using Pure Virtual Function**
#include<iostream>
using namespace std;
// Abstract class
class Shape {
public:
// Pure virtual function
virtual void draw() = 0;
void display() {
cout << "This is a shape.\n"; } };
// Derived class
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a Circle.\n";
}
};
// Another derived class
class Rectangle : public Shape {
public:
void draw() override {
cout << "Drawing a Rectangle.\n"; } };
int main() {
Shape* s1; // Pointer to base class
Circle c;
Rectangle r;
s1 = &c;
s1->draw(); // Output: Drawing a Circle.
s1 = &r;
s1->draw(); // Output: Drawing a Rectangle.
return 0; }
### **Explanation:**
* `Shape` is an **abstract class** because it contains a **pure virtual function** `draw()`.
* `Circle` and `Rectangle` are **concrete classes** that provide implementation of `draw()`.
* We use a **base class pointer (`Shape*`)** to point to derived class objects, achieving **runtime polymorphism**.
Q5.What are various restrictions of Operator Overloading.
Ans:-**Operator overloading** in C++ is a powerful feature that allows you to define the behavior of operators for
**user-defined types (classes and structures)**.
However, to maintain the **integrity**, **readability**, and **consistency** of the language, there are certain **restrictions**
!
and **rules** applied to operator overloading.
"
## **Restrictions / Rules of Operator Overloading in C++**
### 1. **Cannot Create New Operators** * You can **only overload existing C++ operators**.
✅
* You **cannot define** new symbols like `**`, `<=>`, or `%%`.
Allowed:
❌
```c++ operator+, operator-, operator== ```
Not Allowed:
"
```cpp operator**, operator%% (Not valid operators in C++) ```
### 2. **Certain Operators Cannot Be Overloaded**
The following operators **cannot be overloaded**:
| Operator | Description |
| -------------------------------------------------------------------------------------------- | -------------------- |
| `::` | Scope resolution |
| `.` | Member access |
| `.*` | Pointer-to-member |
| `sizeof` | Object size operator |
| `typeid` | Run-time type info |
| `?:` | Ternary conditional |
"
| `alignof`, `noexcept`, `static_cast`, `dynamic_cast`, `const_cast`, `reinterpret_cast`, etc. | |
### 3. **Overloading Preserves Precedence and Associativity**
* The **precedence and associativity** of overloaded operators **cannot be changed**.
"
* For example, `*` will always have **higher precedence** than `+`, even after overloading.
### 4. **Operator Arity Cannot Be Changed**
* You **cannot change the number of operands** an operator takes.
"
* A binary operator (`+`) must have two operands, and a unary operator (`!`) must have one.
### 5. **At Least One Operand Must Be a User-Defined Type**
* You **can’t overload an operator** for built-in types only.
Allowed:
```cpp
❌
Complex + int // One user-defined type ```
Not Allowed:
```cpp
int + float // Both are built-in types
"
```
### 6. **Assignment (=), Subscript (\[]), Function Call (()), and Arrow (->) Must Be Member Functions**
"
These **four special operators** can **only be overloaded as member functions**, not as non-member or friend functions.
### 7. **Return Type Is Not Considered for Overloading**
* You cannot overload operators **only by changing their return type**.
* There must be a difference in the **parameter list**.
### Example (Valid Overloading): ```cpp
class Complex {
public:
int real, imag;
Complex operator+(const Complex& obj) {
Complex temp;
temp.real = real + obj.real;
temp.imag = imag + obj.imag;
return temp; } };
This is a **valid binary operator overloading** for the `+` operator.
Q7. Describe the features of procedural programming and object oriented programming.
Ans:-## **What is Procedural Programming?**
**Procedural Programming** is a programming paradigm based on the concept of **procedure calls** or **routines
(functions)**. Programs are organized into a set of functions or procedures, and data is usually **shared globally** among
these procedures.
%
Examples: C, Pascal, FORTRAN
### **Key Features of Procedural Programming:**
| Feature | Description |
| ---------------------------------------------- | ------------------------------------------------------------------------------------- |
| **Procedure-based** | Code is divided into functions/procedures. |
| **Top-down approach** | Program design starts from the top (main function) and breaks into smaller
functions. |
| **Global data sharing** | Functions often share and modify global variables. |
| **Function calls** | Functions are called with parameters and return results. |
| **Modularity** | Programs are broken into reusable procedures. |
| **Reusability** | Functions can be reused across the program. |
| **Ease of understanding (for small programs)** | Simple logic flow makes it easier to understand.
### **Example (in C):**
#include<stdio.h>
void greet() {
printf("Hello, User!\n");
}
int main() {
greet(); // Function call
return 0;
}
## **What is Object-Oriented Programming (OOP)?**
**Object-Oriented Programming** is a paradigm based on **"objects"** — entities that contain **data (attributes)** and
**functions (methods)**. It focuses on **modelling real-world systems** using classes and objects.
%
Examples: C++, Java, Python, C#
### **Key Features of OOP:**
| Feature | Description |
| -------------------- | ----------------------------------------------------------------- |
| **Class and Object** | Classes define templates; objects are instances. |
| **Encapsulation** | Data and methods are bundled together in classes. |
| **Abstraction** | Hides implementation and shows only essential features. |
| **Inheritance** | Classes can inherit from other classes (code reuse). |
| **Polymorphism** | Same function/operator behaves differently in different contexts. |
| **Modularity** | Programs are divided into objects/modules. |
| **Message Passing** | Objects communicate by calling each other’s methods. |
| **Dynamic Binding** | Functions are resolved at runtime via virtual functions. |
### **Example (in C++):**
#include<iostream>
using namespace std;
class Person {
public:
void greet() {
cout << "Hello, User!" << endl; } };
int main() { Person p; p.greet(); // Method call on object
✅
return 0; }
## Conclusion:
***Procedural Programming** is best for simple, linear tasks and smaller applications.
* **OOP** is better for large, complex systems where **modularity, reuse, and maintenance** are critical.
Q9. Write a program for copying contents of file to another file.
Ans:-### ✅ **C++ Program to Copy Contents of a File to Another File**
#include <iostream>
#include <fstream>
using namespace std;
int main() {
string sourceFile, targetFile;
// Get source and destination file names from user
cout << "Enter source file name: ";
cin >> sourceFile;
cout << "Enter destination file name: ";
cin >> targetFile;
// Open source file in read mode
ifstream source(sourceFile);
if (!source) {
cerr << "Error: Cannot open source file." << endl;
return 1;
}
// Open destination file in write mode
ofstream destination(targetFile);
if (!destination) {
cerr << "Error: Cannot open destination file." << endl;
return 1;
}
// Copy content character by character
char ch;
while (source.get(ch)) {
destination.put(ch);
}
cout << "File copied successfully!" << endl;
// Close files
source.close();
destination.close();
return 0;
}
### **Example Run:**
Enter source file name: input.txt
Enter destination file name: output.txt
File copied successfully!
### **Explanation:**
* `ifstream` is used to read from the source file.
* `ofstream` is used to write to the destination file.
* `source.get(ch)` reads one character at a time from the file.
* `destination.put(ch)` writes the character to the new file.
* File closing is done to free resources.
---
Let me know if you want a version that copies **line by line** instead of character by character.
Q11.Write a program to sort a list of 10 names in descending order.
Ans:- ### ✅ **C++ Program to Sort 10 Names in Descending Order**
#include <iostream>
#include <string>
using namespace std;
// Function to sort names in descending order
void sortDescending(string names[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (names[i] < names[j]) { // For descending order
string temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
}
int main() {
const int SIZE = 10;
string names[SIZE];
// Input 10 names
cout << "Enter 10 names:\n";
for (int i = 0; i < SIZE; i++) {
cout << "Name " << i + 1 << ": ";
getline(cin, names[i]);
}
// Sort names in descending order
sortDescending(names, SIZE);
// Display sorted names
cout << "\nNames in Descending Order:\n";
for (int i = 0; i < SIZE; i++) {
cout << names[i] << endl;
}
return 0;
}
### **Sample Output:**
Enter 10 names:
Name 1: Rohit
Name 2: Anjali
Name 3: Meena
Name 4: Zoya
Name 5: Babita
Name 6: Chetan
Name 7: Lakshmi
Name 8: Omkar
Name 9: Yash
Name 10: Tara
Names in Descending Order: Zoya Yash Tara Rohit Omkar Meena Lakshmi Chetan Babita Anjali
### **Explanation:**
* It uses **Bubble Sort** logic on `string` arrays.
* `getline()` is used for input to allow full names (with spaces).
* Comparison is done using `<` for **descending** order.
Q13. Explain :-##
### '
✅ 1. **Default Argument Constructor**
Definition:A **default argument constructor** is a constructor that provides **default values** for its parameters.
º
This allows it to be called with **fewer arguments** or even **no arguments**.
### **Example:**
```cpp
#include <iostream>
using namespace std;
class Student {
string name;
int age;
public:
// Constructor with default arguments
Student(string n = "Unknown", int a = 0) {
name = n;
age = a;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
Student s1; // Uses both default values
Student s2("Anjali"); // Uses default age
Student s3("Rohit", 20); // No defaults used
s1.display();
s2.display();
s3.display();
return 0;
}
### Output:
Name: Unknown, Age: 0
Name: Anjali, Age: 0
Name: Rohit, Age: 20
##
###
'2. **Access Specifiers**
Definition:**Access specifiers** control the **visibility** or **accessibility** of class members (variables and
ý
functions).
### **Types of Access Specifiers:**
| Specifier | Accessible within class | Accessible outside class | Accessible in derived class |
❌ ¡
| ----------- | ----------------------- | ------------------------ | --------------------------- |
✅ ¡ ✅
| `private` | Yes | No | No |
| `protected` | Yes | No | Yes |
º
| `public` | Yes | Yes | Yes |
### **Example:**
```cpp
class Example {
private:
int secret;
protected:
int semiSecret;
public:
int open;
##
###
✅'4. **Exception Handling**
Definition:
º
Exception handling in C++ is a mechanism to **detect and handle runtime errors** using `try`, `catch`, and `throw`.
### **Syntax:**
```cpp
try {
// Code that may throw exception
if (divisor == 0)
throw "Division by zero error!";
}
catch (const char* msg) {
// Code to handle exception
cout << "Error: " << msg << endl;
&
}
### **Example:**
```cpp
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
try {
if (b == 0)
throw "Cannot divide by zero!";
cout << "Result: " << a / b << endl;
}
catch (const char* errMsg) {
cout << "Exception caught: " << errMsg << endl;
}
return 0;
}
```
---
###
Output:
```
Enter two numbers: 10 0
Exception caught: Cannot divide by zero!
Q14.Parameterized Constructor:-### $ **What is a Parameterized Constructor?**
A **parameterized constructor** is a constructor that **accepts arguments/parameters** to initialize an object with specific
values **at the time of its creation**.
### **Syntax:**
```cpp
class ClassName {
public:
ClassName(data_type parameter1, data_type parameter2, ...) {
// constructor body
}
2 This is done using:
* **Inheritance** +
* **Function Overriding** +
✅
* **Virtual functions**
### **Key Features of Run-time Polymorphism:**
| Feature | Description |
| --------------- | ------------------------------------------------------------------ |
| **Achieved by** | Function overriding using **virtual functions** |
| **Resolved at** | **Run-time** using **vtable** (virtual table) |
| **Requirement** | Base class pointer or reference must point to derived class object |
| **Use case** | When behavior varies depending on the object type |
### **Basic Example:**
```cpp
#include <iostream>
using namespace std;
class Animal {
public:
// Virtual function
virtual void sound() {
cout << "Animal makes a sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Dog barks" << endl;
}
};
class Cat : public Animal {
public:
void sound() override {
cout << "Cat meows" << endl;
}
};
int main() {
Animal* a; // base class pointer
Dog d;
Cat c;
a = &d;
a->sound(); // Output: Dog barks
a = &c;
a->sound(); // Output: Cat meows
return 0;
}
}
int main() {
Box b;
displayLength(b); // Friend function accessing private member
return 0;
}
✅%2. **Static Keyword**
```
##
### Uses in C++:
| Usage | Description |
| ------------------------------- | -------------------------------------------------------------- |
| **Static variable in function** | Retains its value between function calls. |
| **Static data member** | Shared among all objects of the class (common memory). |
| **Static function** | Can be called without an object. Only accesses static members. |
### % Example 1: Static Variable (in function)
```cpp
#include <iostream>
using namespace std;
void counterFunction() {
static int count = 0; // Initialized only once
count++;
cout << "Count: " << count << endl;
}
int main() {
counterFunction(); // Output: 1
counterFunction(); // Output: 2
counterFunction(); // Output: 3
return 0;
}
%
```
### Example 2: Static Data Member
```cpp
#include <iostream>
using namespace std;
class Student {
public:
static int count;
Student() {
count++;
}
static void showCount() {
cout << "Total Students: " << count << endl;
}
};
int Student::count = 0;
int main() {
Student s1, s2, s3;
Student::showCount(); // Output: Total Students: 3