0% found this document useful (0 votes)
15 views7 pages

OOP Micro (ONS) For Scoring

The document discusses various concepts in C++ including operator overloading, access specifiers in inheritance, ambiguity in multiple inheritance, namespaces, exception handling, class templates, user-defined exceptions, streams, file operations, and file modes. It explains the importance of operator overloading for improving code readability and polymorphism, and outlines rules for overloading operators. Additionally, it covers error handling during file operations and differences between opening files using constructors and the open() function.

Uploaded by

shantanusable06
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)
15 views7 pages

OOP Micro (ONS) For Scoring

The document discusses various concepts in C++ including operator overloading, access specifiers in inheritance, ambiguity in multiple inheritance, namespaces, exception handling, class templates, user-defined exceptions, streams, file operations, and file modes. It explains the importance of operator overloading for improving code readability and polymorphism, and outlines rules for overloading operators. Additionally, it covers error handling during file operations and differences between opening files using constructors and the open() function.

Uploaded by

shantanusable06
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/ 7

U3

Q1. What is operator overloading? Why is it necessary to overload an operator?

Operator overloading is a feature of C++ that allows us to redefine the way operators work
with user-defined data types such as classes or objects. Normally, operators like +, -, *, ==,
etc., work only with built-in types like int or float. Operator overloading lets these operators
work with objects by giving them new meanings

1. It improves code readability by allowing natural expressions like a + b where a and b


are objects, instead of calling complicated functions.
2. It provides polymorphic behavior so the same operator symbol can do different tasks
based on the operands’ types.
3. It simplifies programming by enabling intuitive operations on objects, making code
easier to understand and maintain.
4. It extends operator functionality to user-defined types, making objects behave like
built-in types.
5. It helps achieve better abstraction and encapsulation by hiding complex operations
behind simple operator symbols.
6. It enhances code reuse and consistency across programs.

Q2. What are the rules for overloading operators?

 Only existing operators can be overloaded; new operators cannot be created.


 Operators like ::, ., .*, ?:, and sizeof cannot be overloaded.
 At least one operand must be a user-defined type (class or struct).
 The number of operands must remain the same (unary or binary).
 Operator precedence and associativity are fixed and cannot be changed by
overloading.
 Operators can be overloaded as member functions or friend functions.
 Operators =, (), [], and -> must be overloaded as member functions.
 Sure, Shiva! Here’s the short answer plus minimized code for friend function:

Q3. What is friend function

A friend function is a function that is not a member of a class but can access its private and
protected members. It is declared inside the class using the keyword friend.

#include <iostream> void show(A obj) {


using namespace std; cout << obj.x << endl;
class A { }
int x;public: int main() {
A(int a) : x(a) {} A obj(10);
friend void show(A);
};
U4 Q Discuss the role of access specifiers in inheritance and show their visibility when
they are inherited as public, private, protected.
Role of Access Specifiers in Inheritance and Their Visibility Access
specifiers in C++ (public, protected, private) control the accessibility of class members.
During inheritance, these specifiers determine how base class members are accessible in
the derived class.
1. Role of Access Specifiers
 Public members: Accessible outside the class and inherited classes depending on
inheritance type.
 Protected members: Accessible within the class and derived classes, not outside.
 Private members: Accessible only within the class; not inherited directly.

2. Visibility of Base Class Members in Derived Class

Inheritance Type Base Class Public Base Class Protected Base Class Private
Members Members Members
Public Public Protected Not accessible
Inheritance
Protected Protected Protected Not accessible
Inheritance
Private Private Private Not accessible
Inheritance

Q Ambiguity in Multiple Inheritance and Its Solution


Ambiguity:
In multiple inheritance, if two base classes have a member (variable or function) with the
same name, the derived class faces ambiguity when accessing that member. The compiler
cannot decide which base class member to use. C How to overcome:
Use scope resolution operator (::) to specify which base class member to access.

#include<iostream> public:
using namespace std; void display(){
class Base1{ Base1::show();
public: Base2::show();
void show(){cout<<"Base1 show"<<endl;} }
}; };
class Base2{ int main(){
public: Derived d;
void show(){cout<<"Base2 show"<<endl;} d.display();
}; return 0;}
class Derived:public Base1,public Base2{
U5 Q. Explain Namespace in C++ with example.

Definition: Namespace in C++ groups variables, functions, classes, etc., under a unique
name to avoid naming conflicts.
Namespace in C++ is a way to group related variables, functions, and classes under a
unique name to prevent naming conflicts in large programs. It allows different parts of a
program or different libraries to use the same names without confusion. Namespaces help
organize code better and avoid errors caused by duplicate names. You access elements
inside a namespace using the scope resolution operator ::.
Advantages: Prevents naming conflicts, organizes code, useful in large projects.
Types: 1. Named 2. Unnamed 3. Nested
Example:

#include<iostream>
using namespace std;
namespace MySpace {
int x = 10;
void show() { cout << "Value: " << x << endl; }
}
int main() {
MySpace::show();
return 0;
}
Output: Value: 10

Q. Exception Handling in C++:

Exception handling is used to manage errors that occur during program execution without
crashing the program. It uses try block to write the code that may cause an error, throw to
raise an exception, and catch to handle that exception. When an error occurs inside try,
control transfers to catch to handle it smoothly.

#include<iostream> cin >> a >> b; }

using namespace try { catch (const char*


std; msg) {
if (b == 0)
int main() { cout << "Error: " <<
throw "Cannot divide msg << endl;
int a, b; by zero!";
}return 0 ;
cout << "Enter two cout << "Result = " <<
numbers: "; (float)a / b << endl; }
U5 Explain class template using multiple parameters?
Class template lets you create a class that works with any data type. When you use
multiple parameters, the class can handle two or more different types at once. For example,
it can store one integer and one float together. This makes your code flexible and reusable
because you don’t need to write separate classes for each type. You just give the types
when you use the class.

#include<iostream> };
using namespace std; int main(){
template<class T1,class T2> Pair<int,float> p1(10,15.5);
class Pair{ Pair<string,int> p2("Age",25);
T1 first; T2 second; p1.display();
public: p2.display();
Pair(T1 a,T2 b){ first=a; second=b; return 0;
}
}
void display(){ cout<<"First:
"<<first<<", Second:
"<<second<<endl; }
--output= First: 10, Second: 15.5 First: Age, Second: 25

Q: What is a user-defined exception? Write down the scenario where we require user-
defined exceptions.

A user-defined exception is a custom error type created by the programmer to handle


specific error conditions that are not covered by standard exceptions in C++. It allows more
precise and meaningful error handling in programs.
Scenario for using user-defined exceptions:
When the built-in exceptions like std::runtime_error or std::out_of_range do not describe
the error properly, we create user-defined exceptions. For example, in a banking
application, if a user tries to withdraw an amount greater than the account balance, a
custom exception like InsufficientFundsException can be defined to handle this specific
error clearly.

Q: What is stream? Explain types of streams available in C++.

A stream in C++ is a flow of data used to perform input and output operations. It connects
the program with devices like keyboard, screen, and files. Streams help in reading data into
the program and writing data out of the program. Types of
streams in C++:

1. Input Stream: Reads data into the program. Example: cin reads from keyboard.
2. Output Stream: Sends data out of the program. Example: cout displays on screen.
3. File Stream: Used to read from and write to files.
o ifstream: Input file stream for reading files.
o ofstream: Output file stream for writing files.
o fstream: For both reading and writing files.
U6 Q. Write a program using the open(), eof(), and getline() member functions to open and
read a file content line by line.

In C++, we can read a file line by line using the ifstream class with the member functions
open(), eof(), and getline(). The open() function is used to open the file, eof() checks whether
the end of the file is reached, and getline() reads one line at a time from the file.

#include <iostream> string line;


#include <fstream> while (!file.eof()) {
using namespace std; getline(file, line);
int main() { if (file)
cout << line << endl;
ifstream file;
}
file.open("example.txt"); file.close();
if (!file) { return 0;
cout << "Error opening file." << endl; }
return 1;
}

Q. Explain error handling during file operation.

In file handling, errors can occur while opening, reading, or writing files. To avoid program
crashes and unexpected behavior, error handling is important.

1. Checking if file is opened:


Use ifstream or ofstream object’s open() function to open a file. Immediately check if
the file opened successfully by using the condition:
if (!file) or if (!file.is_open())
If the file fails to open (e.g., file does not exist or permission denied), handle the error
by displaying a message or taking alternative action.
2. Checking end of file:
Use eof() function to detect the end of the file during reading. It prevents reading
beyond file content.
3. Using fail() and bad() functions:
o fail() checks if an input/output operation failed (e.g., wrong format).
o bad() detects serious errors like hardware failure.
4. Exception handling:
File stream classes can throw exceptions on errors if enabled using exceptions()
function. Catching exceptions using try-catch blocks provides robust error handling.
ifstream file("data.txt");
if (!file) {
cout << "Error opening file." << endl;
}
U6 What is File Mode? Explain any Four File Modes Supported by C++.

File Mode:
File mode defines how a file is opened and accessed in C++. It specifies the purpose of file
operation such as reading, writing, appending, or binary mode. File modes determine
whether the file is opened for input, output, or both, and how the data is handled.

Common File Modes in C++:

1. ios::in
Opens the file for reading (input). The file must exist. Example:

ifstream file("data.txt", ios::in);


2. ios::out
Opens the file for writing (output). If the file exists, its content is deleted (truncated). If
it does not exist, a new file is created. Example:

ofstream file("data.txt", ios::out);


3. ios::app
Opens the file in append mode. All data written to the file is added at the end. The file
is created if it does not exist. Example:

ofstream file("data.txt", ios::app);


4. ios::binary
Opens the file in binary mode. Data is read/written as raw bytes, not formatted text.
Used for binary files like images or executables. Example:

fstream file("data.bin", ios::in | ios::binary);

Q Difference between Opening a File with Constructor and open() Function in C++

Aspect Using Constructor Using open() Function


When to File is opened immediately when File is opened after the object is created
open file the file stream object is created. by calling open() explicitly.
Syntax ifstream file("data.txt"); ifstream file; file.open("data.txt");
Less flexible as file must be More flexible, file can be opened or
Flexibility
opened at object creation time. reopened anytime after object creation.
Error Need to check if file is opened
Can check after calling open().
Handling right after creation.
When file name is known at the When file name is decided later or file
Use Case
time of object creation. needs to be reopened multiple times.
https://chat.whatsapp.com/Fef4yqNtVZ50NpXhXmOhx9

You might also like