0% found this document useful (0 votes)
22 views19 pages

OOP Insem Oct 2023 PyqSpot

pyqspot Answer key of OOPs

Uploaded by

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

OOP Insem Oct 2023 PyqSpot

pyqspot Answer key of OOPs

Uploaded by

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

Other Subjects: www.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.

2. Abstraction: OOP allows developers to model complex systems in a simplified manner,


making it easier to understand, modify, and extend the code. Abstraction also allows the code
to be modularized, making it easier to reuse and test. Example — Let’s say you are building
a game and you want to represent a player’s attributes, such as health and strength. Instead
of writing separate code for each attribute, you can abstract them into a single class that
represents the player’s overall state.

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.

Other Subjects: www.pyqspot.com


Q1) b) What is polymorphism? How does it relate to function overloading?
Ans:

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects


of different classes to be treated uniformly. It enables flexibility and extensibility in software design.
Let’s dive into the details:
1. Polymorphism:
• Polymorphism means “many forms.” It allows you to use a single interface (method or
function) to represent different types of objects.
• In OOP, polymorphism is achieved through method overriding (inherited methods
with different implementations) and method overloading (multiple methods with the
same name but different parameters).
• The key idea is that you can call the same method on different objects, and the
behaviour will vary based on the actual type of the object.
• Example:
#include <iostream>

class MathOperations {
public:
int add(int a, int b) {
return a + b;
}

float add(float a, float b) {


return a + b;
}
};

int main() {
MathOperations math;

// Example usage
int intResult = math.add(5, 3);
float floatResult = math.add(2.5f, 1.3f);

std::cout << "Integer result: " << intResult << std::endl;


std::cout << "Float result: " << floatResult << std::endl;

return 0;
}

Other Subjects: www.pyqspot.com


2. Function Overloading:
• Function overloading is a form of polymorphism where a class defines multiple
methods with the same name but different parameter lists.
• When you invoke an overloaded function, the appropriate version is selected based on
the number or types of arguments provided.
• For example, consider a class MathOperations with an overloaded method add

3. Relation Between Polymorphism and Function Overloading:


• Function overloading is one way to achieve polymorphism. By having multiple
methods with the same name but different signatures, you allow flexibility in method
calls.
• When you call add on an instance of MathOperations, the appropriate version of add
is chosen based on the argument types.
• Polymorphism extends beyond function overloading to include method overriding
(where subclasses provide their own implementation of inherited methods).

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;
}

Other Subjects: www.pyqspot.com


// Setter methods
void setName(const std::string& newName) {
name = newName;
}

void setRollNumber(int newRollNumber) {


rollNumber = newRollNumber;
}

void setMarks(float newMarks) {


marks = newMarks;
}

// 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);

// Display student information


student1.displayInfo();

// Update attributes
student1.setName("Bob");
student1.setMarks(92.0);

// Display updated information


student1.displayInfo();

return 0;
}

Other Subjects: www.pyqspot.com


Q2) a) State differences between abstraction and encapsulation.
Ans:

ABSTRACTION ENCAPSULATION

1. Abstraction is the process or While encapsulation is the process or method to


method of gaining the information. contain the information.
2. In abstraction, problems are solved While in encapsulation, problems are solved at the
at the design or interface level. implementation level.
3. Abstraction is the method of hiding Whereas encapsulation is a method to hide the data
the unwanted information. in a single entity or unit along with a method to
protect information from outside.
4. We can implement abstraction Whereas encapsulation can be implemented using
using abstract class and interfaces. by access modifier i.e. private, protected and
public.
5. In abstraction, implementation While in encapsulation, the data is hidden using
complexities are hidden using methods of getters and setters.
abstract classes and interfaces.
6. The objects that help to perform Whereas the objects that result in encapsulation
abstraction are encapsulated. need not be abstracted.

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

Other Subjects: www.pyqspot.com


};

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).

Other Subjects: www.pyqspot.com


Q2) c) Write a class “Calculator” with methods for addition, subtraction, multiplication and
division functions. Create a object to perform arithmetic operation.
Ans:
Below is a simple implementation of a Calculator class in C++ with methods for addition,
subtraction, multiplication, and division:
#include <iostream>

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;

Other Subjects: www.pyqspot.com


double num1 = 10.0;
double num2 = 3.0;

std::cout << "Addition: " << myCalculator.add(num1, num2) << std::endl;


std::cout << "Subtraction: " << myCalculator.subtract(num1, num2) << std::endl;
std::cout << "Multiplication: " << myCalculator.multiply(num1, num2) << std::endl;
std::cout << "Division: " << myCalculator.divide(num1, num2) << std::endl;

return 0;
}

Other Subjects: www.pyqspot.com


Q3) a) Define function overloading and write a program for swapping two integer numbers,
two float numbers and two characters using function overloading.
Ans:
Function overloading allows you to define multiple functions with the same name but different
parameters. These functions can perform similar operations but on different data types or with
different numbers of arguments.

#include <iostream>

// Function to swap two integers


void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}

// Function to swap two floats


void swap(float& a, float& b) {
float temp = a;
a = b;
b = temp;
}

// Function to swap two characters


void swap(char& a, char& b) {
char temp = a;
a = b;
b = temp;
}

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);

Other Subjects: www.pyqspot.com


std::cout << "Swapped floats: " << float1 << ", " << float2 << std::endl;

// Swap characters
swap(char1, char2);
std::cout << "Swapped characters: " << char1 << ", " << char2 << std::endl;

return 0;
}

Q3) b) What is the use of ‘this pointer’ Explain with example.


Ans:
The this pointer in C++ is a special pointer that represents the address of the current object inside a
member function. It serves several purposes:
1. Accessing Object Members:
• When a member function is called on an object, the this pointer implicitly points to
that object.
• You can use this to access the object’s attributes (data members) and methods
(member functions).
2. Avoiding Ambiguity:
• In cases where local variables have the same names as class attributes, this helps
differentiate between them.
• It ensures that you’re referring to the class-level attribute, not the local variable.
3. Passing the Current Object:
• this is automatically passed as a hidden argument to all non-static member function
calls.
• It allows methods to operate on the correct object.

Here’s an example demonstrating the use of this:


#include <iostream>

class MyClass {
private:
int value;

public:
MyClass(int val) : value(val) {}

void displayValue() {
std::cout << "Value from this object: " << this->value << std::endl;

Other Subjects: www.pyqspot.com


}

void setValue(int newVal) {


this->value = newVal;
}
};

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
};

class PublicDerived : public Base {


// x is public in PublicDerived

Other Subjects: www.pyqspot.com


};

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
};

class ProtectedDerived : protected Base {


// prot is protected in ProtectedDerived
};

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
};

class PrivateDerived : private Base {


// pub is private in PrivateDerived
};

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 {

Other Subjects: www.pyqspot.com


public:
void grandParentMethod() {
std::cout << "Method in the grand parent class" << std::endl;
}
};

class Child : protected GrandParent {


// Child inherits protectedly from GrandParent
};

int main() {
Child childObj;
// childObj.grandParentMethod(); // Error: grandParentMethod is not accessible here

return 0;
}

Other Subjects: www.pyqspot.com


Q4) a) Define function overriding in c++ and write the program to demonstrate the same.
Ans:
Function overriding in C++ allows you to redefine a function from the base class (parent class) in
the derived class (child class). The function name and signature (return type and parameters) remain
the same in both classes, but the derived class provides a different function definition that overrides
the base class function. Here’s an example program demonstrating 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;
}

Other Subjects: www.pyqspot.com


Q4) b) What are the types of inheritance. Explain them with the syntax.
Ans:
In C++, inheritance allows a class to derive properties and characteristics from another class. There
are five types of inheritance based on the relationship between the derived class and the base class:

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 {

Other Subjects: www.pyqspot.com


// Derived2 class members
};

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 Child : public Parent {


public:
int id_c;
void printID_c() {
cout << "Child ID: " << id_c << endl;
}
};

7. Accessing Inherited Members:

class Base {
public:
int publicVar;
void display() {
cout << "Value of publicVar: " << publicVar;
}
};

class Derived : public Base {


public:
void displayMember() {
display();
}

Other Subjects: www.pyqspot.com


void modifyMember(int pub) {
publicVar = pub;
}
};

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.

1. Syntax for Declaring a Function Pointer:


• To declare a function pointer, use the following syntax:return_type
(*FuncPtr)(parameter_type, ...);

▪ return_type: The return type of the function.


▪ FuncPtr: The name of the function pointer.
▪ parameter_type, ...: The types of parameters the function takes (if any).
2. Referencing and Dereferencing:
• Referencing: Assign the address of a function to the function pointer.FuncPtr =
function_name;

• 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 multiply(int a, int b) {


return a * b;
}

int main() {
int (*func)(int, int); // Declare a function pointer
func = multiply; // Point func to the multiply function

Other Subjects: www.pyqspot.com


int prod = func(15, 2); // Call multiply using func
cout << "The value of the product is: " << prod << endl;
return 0;
}

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.

Other Subjects: www.pyqspot.com

You might also like