0% found this document useful (0 votes)
3 views

IE II Key

The document provides a comprehensive overview of various C++ programming concepts, including constructors, destructors, method and operator overloading, and UML diagrams. It discusses the advantages and drawbacks of multiple inheritance, the role of pure virtual functions in abstraction, and the definitions and uses of inline, friend, and virtual functions. Additionally, it includes multiple-choice questions with answers and detailed explanations for each concept.

Uploaded by

ak6960
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)
3 views

IE II Key

The document provides a comprehensive overview of various C++ programming concepts, including constructors, destructors, method and operator overloading, and UML diagrams. It discusses the advantages and drawbacks of multiple inheritance, the role of pure virtual functions in abstraction, and the definitions and uses of inline, friend, and virtual functions. Additionally, it includes multiple-choice questions with answers and detailed explanations for each concept.

Uploaded by

ak6960
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/ 14

In brief:

MCQ’s
Q.1 b Q.2 b Q.3 a Q.4 b Q.5 a Q.6 b Q.7 a Q.8 a Q.9 a Q.10 a
Detailed Explanation:
1. Which of the following is NOT a type of constructor in C++?
Answer: (b) Static Constructor
Explanation:
• (a) Default Constructor: A constructor that takes no parameters and initializes an object
with default values.
• (b) Static Constructor (Incorrect): C++ does not have a concept of a "static constructor."
Constructors in C++ are called when an object is created, and there is no mechanism to
create a constructor that is executed only once like in C#.
• (c) Copy Constructor: A constructor that initializes an object using another object of the
same class.
• (d) Parameterized Constructor: A constructor that accepts parameters to initialize an
object with specific values.

2. The primary role of a destructor in C++ is?


Answer: (b) Deallocate resources when an object is destroyed
Explanation:
• (a) Initialize an object (Incorrect): Initializing an object is the job of a constructor, not a
destructor.
• (b) Deallocate resources when an object is destroyed (Correct): The destructor cleans
up memory and resources (such as closing files or releasing heap memory).
• (c) Overload operators (Incorrect): Operator overloading is not related to destructors.
• (d) Create multiple instances of a class (Incorrect): Creating instances is done using
constructors, not destructors.

3. Constructor overloading in C++ is an example of:


Answer: (a) Compile-time polymorphism
Explanation:
• (a) Compile-time polymorphism (Correct): Constructor overloading happens at compile
time, as the compiler determines which constructor to call based on parameters.
• (b) Runtime polymorphism (Incorrect): Runtime polymorphism occurs due to function
overriding, which happens dynamically at runtime using virtual functions.
• (c) Data hiding (Incorrect): Data hiding involves restricting access to class members using
private/protected access specifiers.
• (d) Encapsulation (Incorrect): Encapsulation is about bundling data and methods into a
single unit (class).

4. A UML diagram which is used to show the interaction between objects over time?
Answer: (b) Sequence Diagram
Explanation:
• (a) Activity Diagram (Incorrect): Used to model workflows and processes, not object
interactions over time.
• (b) Sequence Diagram (Correct): Shows the order of interactions between objects over
time.
• (c) Collaboration Diagram (Incorrect): Focuses on the relationships and interactions
between objects but not in a time-sequenced manner.
• (d) State Chart Diagram (Incorrect): Shows the different states of an object and transitions
between them.

5. The primary benefit of method overloading in C++ is?


Answer: (a) It defines multiple methods with the same name but different parameters
Explanation:
• (a) Defines multiple methods with the same name but different parameters (Correct):
Method overloading allows multiple functions with the same name but different parameter
lists, improving code readability and usability.
• (b) Overrides methods in derived classes (Incorrect): This is function overriding, not
overloading.
• (c) Increases execution time of a program (Incorrect): Method overloading does not
inherently increase execution time.
• (d) Restricts access to class members (Incorrect): Access restriction is controlled by
access specifiers, not method overloading.

6. A type of inheritance that allows a single derived class to inherit from multiple base classes
is?
Answer: (b) Multiple Inheritance
Explanation:
• (a) Single Inheritance (Incorrect): Involves only one base and one derived class.
• (b) Multiple Inheritance (Correct): Allows a class to inherit from more than one base class.
• (c) Hierarchical Inheritance (Incorrect): One base class is inherited by multiple derived
classes.
• (d) Hybrid Inheritance (Incorrect): A combination of two or more types of inheritance, but
not necessarily multiple inheritance alone.

7. An abstract class in C++ must contain:


Answer: (a) At least one pure virtual function
Explanation:
• (a) At least one pure virtual function (Correct): An abstract class is defined by having at
least one pure virtual function (virtual void func() = 0;).
• (b) Only private data members (Incorrect): Private members do not define an abstract
class.
• (c) At least one constructor (Incorrect): Constructors can exist in abstract classes, but
they are not required.
• (d) No member functions (Incorrect): An abstract class must contain at least one member
function, specifically a pure virtual function.

8. A friend function in C++ is used to:


Answer: (a) Access private and protected members of a class
Explanation:
• (a) Access private and protected members of a class (Correct): A friend function is
declared with the friend keyword and can access private and protected members of the
class.
• (b) Modify only public members of a class (Incorrect): Public members are already
accessible without friend.
• (c) Create multiple instances of a class (Incorrect): Instance creation is done via
constructors, not friend functions.
• (d) Delete objects dynamically (Incorrect): Dynamic memory management is done using
delete, not friend functions.

9. A UML diagram used to model the dynamic behavior of a system is?


Answer: (a) State Chart Diagram
Explanation:
• (a) State Chart Diagram (Correct): Shows different states of an object and transitions
between them, representing dynamic behavior.
• (b) Class Diagram (Incorrect): Represents the static structure of a system, showing
classes and their relationships.
• (c) Use Case Diagram (Incorrect): Represents interactions between actors and use cases
but does not model dynamic behavior.
• (d) Collaboration Diagram (Incorrect): Focuses on object interactions, but does not model
system behavior dynamically.

10. The primary purpose of a virtual function in C++ is?


Answer: (a) To enable function overriding in derived classes
Explanation:
• (a) To enable function overriding in derived classes (Correct): A virtual function allows a
derived class to override a base class function dynamically at runtime.
• (b) To prevent inheritance in derived classes (Incorrect): final is used to prevent
inheritance, not virtual functions.
• (c) To allow multiple constructors in a class (Incorrect): Multiple constructors are
allowed through overloading, not virtual functions.
• (d) To restrict access to private members (Incorrect): Access control is managed by
private, protected, and public access specifiers, not virtual functions.

SECTION B

1. Analyze the impact of constructor overloading and method overloading in C++. How do they
contribute to code reusability and flexibility in software design?
Impact of Constructor Overloading:
• Constructor overloading allows multiple constructors in a class with different parameter
lists, enabling object initialization in various ways.
• It enhances code flexibility, as objects can be created with different initial values without
modifying the class definition.
• It improves code reusability, as a single class can accommodate different initialization
scenarios.
Example of Constructor Overloading:
#include <iostream>
using namespace std;
class Rectangle {
int length, width;
public:
// Default Constructor
Rectangle() {
length = width = 1;
}
// Parameterized Constructor
Rectangle(int l, int w) {
length = l;
width = w;
}
void display() {
cout << "Length: " << length << ", Width: " << width << endl;
}
};
int main() {
Rectangle r1; // Calls default constructor
Rectangle r2(10, 5); // Calls parameterized constructor
r1.display();
r2.display();
return 0;
}
Impact of Method Overloading:
• Method overloading allows multiple functions with the same name but different parameter
types or numbers.
• It improves code readability and maintainability, as related functionalities are grouped
under the same function name.
• It contributes to flexibility in function usage, as the appropriate version is selected based
on parameters.
Example of Method Overloading:
#include <iostream>
using namespace std;

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

double add(double a, double b) {


return a + b;
}
};

int main() {
Math obj;
cout << "Sum (int): " << obj.add(3, 4) << endl;
cout << "Sum (double): " << obj.add(2.5, 3.8) << endl;
return 0;
}
Conclusion:
Both constructor and method overloading significantly enhance code reusability by allowing
different behaviors without rewriting the logic. They also increase flexibility in object instantiation
and function calls.

2. Explain the differences between operator overloading and method overloading in C++. How
does operator overloading enhance code readability and usability?
Feature Operator Overloading Method Overloading
Redefining operators for user-defined Defining multiple methods with the same name
Definition
types. but different parameters.
Enhances usability of objects with Improves flexibility by allowing different
Purpose
standard operators. behaviors for a method.
Syntax Uses operator keyword. Uses function overloading rules.
Allows custom behavior for operators Allows multiple functions with the same name
Flexibility
like +, -, etc. but different signatures.
Example of Operator Overloading:
#include <iostream>
using namespace std;

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

// Overloading the + operator


Complex operator+(const Complex& obj) {
return Complex(real + obj.real, imag + obj.imag);
}

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

int main() {
Complex c1(3, 4), c2(1, 2);
Complex c3 = c1 + c2; // Using overloaded operator
c3.display();
return 0;
}
How Operator Overloading Enhances Code Readability and Usability:
• Natural Syntax: Users can use +, -, *, etc., instead of complex function calls like add(c1,
c2).
• Improves Intuitiveness: Makes user-defined classes work like primitive data types.
• Enhances Maintainability: Reduces redundant function names and improves readability.
Example Without Operator Overloading (Less Readable Code):
Complex c3 = c1.add(c2); // Less intuitive
Example With Operator Overloading (More Readable Code):
Complex c3 = c1 + c2; // More intuitive

3. Compare and contrast UML Sequence Diagram and UML Collaboration Diagram. Provide an
example where these diagrams are useful.
Feature UML Sequence Diagram UML Collaboration Diagram
Represents the sequence of interactions Represents object interactions with a
Purpose
between objects over time. focus on relationships.
Focus Time-ordering of messages. Structural organization of objects.
Uses vertical lifelines and horizontal Uses numbered arrows to represent
Representation
messages. messages.
Useful for understanding message flow Useful for understanding object
Usage
over time. relationships.
Example Use Case:
• Sequence Diagram: Useful in modeling login authentication, where each step (user input,
validation, database check) happens sequentially.
• Collaboration Diagram: Useful in designing ATM transactions, where multiple objects
(User, ATM, Bank Server) interact to complete a process.

Example of a UML Sequence Diagram (Login Process):


User LoginManager Database
| | |
|----enter()--> | |
| |--validate()--> |
| |<--response()--|
|<--success()-- | |
• Shows how a user initiates login, the login manager validates, and the database responds.

Example of a UML Collaboration Diagram (ATM Transaction):


[ATM] ---> (1) request transaction ---> [Bank Server]
(2) verify balance <--->
(3) approve/reject --->
• Focuses on how objects interact rather than time sequence.

Conclusion:
• Sequence Diagrams are better for analyzing message flow over time.
• Collaboration Diagrams are better for understanding structural interactions among
objects.
• Both are important for software design and system modeling.
SECTION C

1. Analyze the advantages and potential drawbacks of multiple inheritance in C++.


Advantages of Multiple Inheritance:
1. Code Reusability – A derived class can inherit features from multiple base classes,
reducing redundancy.
2. Enhanced Functionality – Allows a class to inherit diverse behaviors, improving
modularity.
3. Flexibility in Design – Helps model real-world entities more effectively by inheriting
from multiple sources.
Example of Multiple Inheritance:
#include <iostream>
using namespace std;
class A {
public:
void displayA() { cout << "Class A\n"; }
};
class B {
public:
void displayB() { cout << "Class B\n"; }
};
class C : public A, public B { // Multiple Inheritance
public:
void displayC() { cout << "Class C\n"; }
};
int main() {
C obj;
obj.displayA();
obj.displayB();
obj.displayC();
return 0;
}
Drawbacks of Multiple Inheritance:
1. Ambiguity Issue – If two base classes have a method with the same name, the compiler
gets confused about which one to call.
2. class A { public: void show() { cout << "A"; } };
3. class B { public: void show() { cout << "B"; } };
4. class C : public A, public B {};
5. int main() { C obj; obj.show(); } // ERROR: Ambiguous Call
Solution: Use scope resolution operator (obj.A::show();).
6. Increased Complexity – Managing dependencies between multiple base classes
becomes difficult.
7. Diamond Problem – Occurs when a class inherits from two classes that derive from the
same base class.
o Solution: Use virtual inheritance to ensure only one copy of the base class
exists.

2. Discuss the role of pure virtual functions in achieving abstraction.


Definition:
A pure virtual function in C++ is a function that has no implementation in the base class and
must be implemented by derived classes. It enforces abstraction by ensuring derived classes
define their own versions of the function.
Syntax:
class AbstractClass {
public:
virtual void display() = 0; // Pure virtual function
};
Role in Abstraction:
1. Encapsulation of Common Behavior – The base class provides a blueprint without an
implementation.
2. Forces Derived Classes to Implement – Ensures subclasses provide concrete behavior.
3. Achieves Polymorphism – Enables runtime method overriding.
Example:
#include <iostream>
using namespace std;
class Shape {
public:
virtual void area() = 0; // Pure virtual function
};
class Circle : public Shape {
public:
void area() override { cout << "Area of Circle = πr²\n"; }
};
class Square : public Shape {
public:
void area() override { cout << "Area of Square = side²\n"; }
};
int main() {
Shape* s1 = new Circle();
Shape* s2 = new Square();
s1->area();
s2->area();
delete s1; delete s2;
return 0;
}
Conclusion:
• Pure virtual functions enable abstraction by ensuring that derived classes provide their
own specific implementations.
• They are essential for interface-based programming and achieving polymorphism in
C++.

3. Explain with suitable examples the concept of Inline, Friend, and Virtual Functions.
(a) Inline Functions
Definition: Inline functions are expanded at compile-time instead of executing a function call,
reducing function call overhead.
Usage: Suitable for small, frequently used functions.
Syntax:
#include <iostream>
using namespace std;
class Demo {
public:
inline void show() { cout << "Inline Function\n"; } // Compiler expands this directly
};
int main() {
Demo d;
d.show();
return 0;
}
Advantages: Faster execution for small functions.
Disadvantages: Increases code size if overused.

(b) Friend Functions


Definition: A friend function can access private and protected members of a class, without
being a member of that class.
Usage: Used when an external function needs access to private data.
Syntax:
#include <iostream>
using namespace std;
class Test {
int a;
public:
Test(int x) { a = x; }
friend void show(Test t); // Friend function declaration
};
void show(Test t) { // Friend function definition
cout << "Private member: " << t.a << endl;
}
int main() {
Test obj(10);
show(obj); // Accessing private data
return 0;
}
Advantages: Allows controlled access to private data.
Disadvantages: Violates encapsulation if misused.

(c) Virtual Functions


Definition: A virtual function enables runtime polymorphism by allowing function overriding in
derived classes.
Usage: Used when the derived class must provide a specific implementation of a base class
function.
Syntax:
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() { cout << "Base Class\n"; } // Virtual function
};
class Derived : public Base {
public:
void show() override { cout << "Derived Class\n"; } // Overriding function
};
int main() {
Base* b;
Derived d;
b = &d;
b->show(); // Calls Derived class function (runtime binding)
return 0;
}
Advantages: Achieves dynamic dispatch and runtime polymorphism.
Disadvantages: Slightly increases memory overhead due to vtable (virtual table).

Conclusion:
• Inline functions improve execution speed by eliminating function calls.
• Friend functions allow access to private members but should be used cautiously.
• Virtual functions enable polymorphism, allowing behavior to be determined at
runtime.
Each function type serves a unique purpose in C++ Object-Oriented Programming.
SECTION D
Here are detailed 12-mark answers for both sets of questions, ensuring clarity, depth, and
proper examples with code where required.

(A) Different Types of Constructors in C++ and Their Role in Polymorphism


Types of Constructors in C++:
1. Default Constructor: A constructor with no parameters, initializing objects with default
values.
2. Parameterized Constructor: Accepts arguments to initialize objects with specific
values.
3. Copy Constructor: Creates a new object as a copy of an existing object.
4. Move Constructor: Transfers ownership of resources instead of copying, improving
efficiency.
5. Destructor (Special Case): Though not a constructor, it ensures proper resource
cleanup when an object is destroyed.
Role in Polymorphism:
Constructor Overloading and Method Overloading are examples of compile-time (static)
polymorphism because the function to be executed is determined at compile time.
Example Code for Constructor Overloading & Method Overloading:
#include <iostream>
using namespace std;
class Shape {
int length, width;
public:
// Default Constructor
Shape() { length = width = 0; }
// Parameterized Constructor
Shape(int l, int w) { length = l; width = w; }
// Copy Constructor
Shape(const Shape &s) { length = s.length; width = s.width; }
// Method Overloading: area()
int area() { return length * width; }
int area(int scale) { return (length * width) * scale; } // Overloaded version
void display() { cout << "Length: " << length << ", Width: " << width << endl; }
};
int main() {
Shape rect1; // Default Constructor
Shape rect2(10, 5); // Parameterized Constructor
Shape rect3(rect2); // Copy Constructor
cout << "Area: " << rect2.area() << endl;
cout << "Scaled Area: " << rect2.area(2) << endl; // Method overloading
return 0;
}
Conclusion:
• Constructor Overloading provides flexibility in initializing objects differently.
• Method Overloading allows multiple functions with the same name but different
parameters.
• Both contribute to polymorphism, enhancing code reusability and maintainability.
(B) C++ Code to Add Two Complex Numbers Using Operator Overloading
#include <iostream>
using namespace std;
class Complex {
int real, imag;

public:
Complex(int r = 0, int i = 0) { real = r; imag = i; }
// Overloading the + operator
Complex operator+(const Complex &c) {
return Complex(real + c.real, imag + c.imag);
}
void display() { cout << real << " + " << imag << "i" << endl; }
};
int main() {
Complex c1(3, 4), c2(1, 2);
Complex c3 = c1 + c2; // Calls overloaded operator
cout << "Sum: ";
c3.display();
return 0;
}
Explanation:
• The + operator is overloaded using operator+ to add two complex numbers.
• The function returns a new Complex object containing the sum.
• This enhances code readability and usability by allowing natural arithmetic
expressions.

(A) Comparison of Single, Multilevel, and Multiple Inheritance


1. Single Inheritance:
• A derived class inherits from a single base class.
• Simple and easy to maintain.
• Example: A Car class inheriting from a Vehicle class.
class Vehicle {
public:
void show() { cout << "This is a Vehicle" << endl; }
};

class Car : public Vehicle {


public:
void display() { cout << "This is a Car" << endl; }
};

2. Multilevel Inheritance:
• A derived class is inherited from another derived class.
• Increases complexity if the hierarchy is deep.
• Example: ElectricCar inherits from Car, which inherits from Vehicle.
class ElectricCar : public Car {
public:
void showBattery() { cout << "Battery Powered" << endl; }
};

3. Multiple Inheritance:
• A derived class inherits from two or more base classes.
• More powerful but introduces complexity (e.g., diamond problem).
• Example: StudentAthlete inherits from Student and Athlete.
class Student {
public:
void study() { cout << "Studying" << endl; }
};

class Athlete {
public:
void train() { cout << "Training" << endl; }
};

class StudentAthlete : public Student, public Athlete {


public:
void show() { cout << "Student Athlete" << endl; }
};

Comparison Summary Table:


Feature Single Inheritance Multilevel Inheritance Multiple Inheritance
Complexity Low Medium High
Maintainability Easy Moderate Difficult
Code Reuse Limited More Reuse High
Performance Best Slower due to depth Slower due to multiple base classes
Conclusion:
• Single inheritance is the easiest to maintain.
• Multilevel inheritance allows gradual extension but increases dependencies.
• Multiple inheritance offers maximum reusability but can lead to ambiguity issues.

(B) C++ Program to Display a Student’s Mark Sheet Using Multiple Inheritance
#include <iostream>
using namespace std;
class Student {
protected:
string name;
int rollNumber;
public:
void setStudent(string n, int r) {
name = n;
rollNumber = r;
}
void displayStudent() {
cout << "Name: " << name << "\nRoll Number: " << rollNumber << endl;
}
};
class Marks {
protected:
int math, science, english;
public:
void setMarks(int m, int s, int e) {
math = m;
science = s;
english = e;
}
void displayMarks() {
cout << "Math: " << math << "\nScience: " << science << "\nEnglish: " << english << endl;
}
};
class Result : public Student, public Marks {
public:
void displayResult() {
displayStudent();
displayMarks();
int total = math + science + english;
float percentage = total / 3.0;
cout << "Total: " << total << "\nPercentage: " << percentage << "%" << endl;
}
};
int main() {
Result student1;
student1.setStudent("John Doe", 101);
student1.setMarks(85, 90, 88);
student1.displayResult();
return 0;
}
Explanation:
1. Class Student stores student details.
2. Class Marks stores subject marks.
3. Class Result inherits from both Student and Marks using multiple inheritance.
4. Displays complete mark sheet.
Output:
Name: John Doe
Roll Number: 101
Math: 85
Science: 90
English: 88
Total: 263
Percentage: 87.67%

You might also like