OOP Insem Oct 2023 PyqSpot
OOP Insem Oct 2023 PyqSpot
com
Q1) a) What are the advantages of object oriented programming over procedural oriented
programming?
Ans:
1. Encapsulation: One of the key concepts of OOP is encapsulation, which allows data to be
hidden and protected from unauthorized access. This helps to prevent errors, improves
security, and makes code easier to maintain. Example — Suppose you are building a
program to manage user data, and you want to ensure that the user’s password is hidden
from other parts of the program. Using OOP, you can encapsulate the password data within
a class and only allow authorized code to access it.
3. Inheritance: In OOP, classes can inherit properties and methods from other classes, reducing
the amount of code that needs to be written. This helps to reduce code duplication and
improve code readability. Example — Consider a program that represents different types of
vehicles, such as cars and trucks. Instead of writing separate code for each type of vehicle,
you can create a parent class for “Vehicle” and then create child classes for “Car” and
“Truck” that inherit properties and methods from the parent class.
4. Polymorphism: OOP allows for polymorphism, which means that objects can be used in
different ways depending on the context. This improves code flexibility and makes it easier
to write code that is reusable and extensible. Example — Imagine a program that needs to
calculate the area of different shapes, such as squares and circles. Using OOP, you can
create a parent class for “Shape” and then create child classes for “Square” and “Circle”
that each implement a unique “area” method.
5. Code Reusability: OOP promotes code reusability by allowing developers to create classes
and objects that can be reused in different parts of the code. This saves time and effort, and
also makes it easier to maintain the code over time. Example — Suppose you are building a
program that needs to access data from a database. Using OOP, you can create a class that
handles the database connections and queries, and then reuse this class in different parts of
the program to access and manipulate the data.
class MathOperations {
public:
int add(int a, int b) {
return a + b;
}
int main() {
MathOperations math;
// Example usage
int intResult = math.add(5, 3);
float floatResult = math.add(2.5f, 1.3f);
return 0;
}
Q1) c) What a class “Student” with attributes like name, roll number and marks. Include
member functions to set and display these attributes?
Ans:
Below is an example of a Student class in C++ with attributes for name, roll number, and marks,
along with member functions to set and display these attributes:
#include <iostream>
#include <string>
class Student {
private:
std::string name;
int rollNumber;
float marks;
public:
// Constructor to initialize attributes
Student(const std::string& studentName, int studentRollNumber, float studentMarks) {
name = studentName;
rollNumber = studentRollNumber;
marks = studentMarks;
}
// Display method
void displayInfo() {
std::cout << "Student Name: " << name << std::endl;
std::cout << "Roll Number: " << rollNumber << std::endl;
std::cout << "Marks: " << marks << std::endl;
}
};
int main() {
// Create a Student object
Student student1("Alice", 101, 85.5);
// Update attributes
student1.setName("Bob");
student1.setMarks(92.0);
return 0;
}
ABSTRACTION ENCAPSULATION
Q2) b) What are c++ access specifiers? Write down their significance.
Ans:
In C++, access specifiers are keywords that determine the visibility and accessibility of class
members. They play a crucial role in encapsulation, which is the principle of hiding
implementation details and exposing only necessary interfaces. Let’s explore the different access
specifiers:
1. Public:
• Members declared as public are accessible from outside the class.
• They can be accessed and modified directly by code outside the class.
• Example:
class MyClass {
public:
int x; // Public attribute
6. Private:
• Members declared as private cannot be accessed (or viewed) from outside the class.
• They are hidden from external code.
• Example:
class MyClass {
private:
int y; // Private attribute
};
7. Protected:
• Members declared as protected are similar to private members.
• They cannot be accessed from outside the class, but they can be accessed in inherited
classes (during inheritance).
• Useful for implementing inheritance relationships.
• You’ll learn more about inheritance later.
• Example:
class Base {
protected:
int z; // Protected attribute
};
class Derived : public Base {
// Can access 'z' here
};
Significance:
• Encapsulation: Access specifiers allow you to control the visibility of class members. By
keeping data private, you prevent accidental misuse and ensure proper data handling.
• Security: Private members protect sensitive data from external interference.
• Good Practice: Declaring attributes as private reduces the risk of code errors and promotes
better software design.
• Interface vs. Implementation: Access specifiers separate the interface (what users see) from
the implementation (internal details).
class Calculator {
public:
// Addition
double add(double a, double b) {
return a + b;
}
// Subtraction
double subtract(double a, double b) {
return a - b;
}
// Multiplication
double multiply(double a, double b) {
return a * b;
}
// Division
double divide(double a, double b) {
if (b != 0) {
return a / b;
} else {
std::cerr << "Error: Division by zero!" << std::endl;
return 0.0; // Handle division by zero gracefully
}
}
};
int main() {
Calculator myCalculator;
return 0;
}
#include <iostream>
int main() {
int int1 = 10, int2 = 20;
float float1 = 3.14f, float2 = 2.71f;
char char1 = 'A', char2 = 'B';
// Swap integers
swap(int1, int2);
std::cout << "Swapped integers: " << int1 << ", " << int2 << std::endl;
// Swap floats
swap(float1, float2);
// Swap characters
swap(char1, char2);
std::cout << "Swapped characters: " << char1 << ", " << char2 << std::endl;
return 0;
}
class MyClass {
private:
int value;
public:
MyClass(int val) : value(val) {}
void displayValue() {
std::cout << "Value from this object: " << this->value << std::endl;
int main() {
MyClass obj1(42);
MyClass obj2(99);
obj1.displayValue(); // Displays 42
obj2.displayValue(); // Displays 99
obj1.setValue(55);
obj1.displayValue(); // Displays 55
return 0;
}
Q3) c) Explain public, private and protected inheritance and give an example of protected
Inheritance with explaination.
Ans:
In C++, inheritance allows you to create a child class (derived class) from a base class. The three
types of inheritance access modes are:
1. Public Inheritance:
• In public inheritance, the public members of the base class become public members in
the derived class, and the protected members of the base class remain protected in the
derived class.
• Public inheritance is the most common type and models an “is-a” relationship.
• Example:
class Base {
public:
int x; // Public member
};
2. Protected Inheritance:
• In protected inheritance, both public and protected members of the base class become
protected in the derived class.
• It is less common and often used for specific scenarios.
• Example:
class Base {
private:
int pvt; // Private member
protected:
int prot; // Protected member
};
3. Private Inheritance:
• In private inheritance, both public and protected members of the base class become
private in the derived class.
• It is rarely used and typically for implementation details.
• Example:
class Base {
public:
int pub; // Public member
};
Example of Protected Inheritance: Suppose we have a GrandParent class with a protected method
called grandParentMethod. We create a Child class that inherits from GrandParent using protected
inheritance:
#include <iostream>
class GrandParent {
int main() {
Child childObj;
// childObj.grandParentMethod(); // Error: grandParentMethod is not accessible here
return 0;
}
#include <iostream>
using namespace std;
class Parent {
public:
void GeeksforGeeks_Print() {
cout << "Base Function" << endl;
}
};
int main() {
Child Child_Derived;
Child_Derived.GeeksforGeeks_Print();
return 0;
}
1. Single Inheritance:
• In single inheritance, a derived class inherits from only one base class.
• Syntax:
class Derived : public Base {
// Derived class members
};
2. Multiple Inheritance:
• In multiple inheritance, a derived class inherits from more than one base class.
• Syntax:
class Derived : public Base1, public Base2 {
// Derived class members
};
3. Hierarchical Inheritance:
• In hierarchical inheritance, multiple derived classes inherit from a single base class.
• Syntax:
class Base {
// Base class members
};
class Derived1 : public Base {
// Derived1 class members
};
class Derived2 : public Base {
// Derived2 class members
};
4. Multilevel Inheritance:
• In multilevel inheritance, a derived class becomes the base class for another class.
• Syntax:
class Base {
// Base class members
};
class Derived1 : public Base {
// Derived1 class members
};
class Derived2 : public Derived1 {
5. Hybrid Inheritance:
• Hybrid inheritance combines multiple types of inheritance (e.g., single, multiple,
hierarchical, or multilevel) in a single program.
• Syntax: Depends on the specific combination of inheritance types.
Examples:
6. Simple Inheritance:
class Parent {
public:
int id_p;
void printID_p() {
cout << "Base ID: " << id_p << endl;
}
};
class Base {
public:
int publicVar;
void display() {
cout << "Value of publicVar: " << publicVar;
}
};
Q4) c) Define function pointers? Give its syntax of declaration Referencing and Dereferencing.
Write a program for it in c++.
Ans:
Function pointers in C++ are pointers that store the memory address of a function. They allow you
to invoke a function indirectly by using the pointer. Function pointers can also be used to pass
functions as arguments to other functions, enabling powerful features like callbacks.
• Dereferencing: Use the (*) operator to get the value stored in the pointer.data_type x
= *FuncPtr;
3. Example Program: Let’s create a simple program that demonstrates function pointers:
#include <iostream>
using namespace std;
int main() {
int (*func)(int, int); // Declare a function pointer
func = multiply; // Point func to the multiply function
In this example, we declare a function multiply that multiplies two integers. Instead of directly
calling the function, we use the function pointer func to achieve the same result.
4. Passing a Function Pointer as a Parameter: You can pass a function pointer to another
function, making it useful for implementing callbacks and dynamic behavior.