OOPs important questions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

OOPS Important Questions

Ques 1. What is class and object?


A class is a fundamental concept in object-oriented programming that
defines a blueprint for creating objects. It encapsulates data (attributes)
and methods (functions) into a single unit, enabling modularity and reuse
of code. A class provides the structure and behaviour that objects created
from it will inherit.

An object is an instance of a class. It represents a real-world entity and has


its own unique set of attributes and behaviours as defined by its class.
Objects interact with one another by calling methods or exchanging data.

Ques 2. Define Data abstraction.

Data abstraction is a concept in object-oriented programming that


involves hiding the internal implementation details of a system and
exposing only the necessary functionalities to the user. It is achieved by
defining abstract classes, interfaces, or access specifiers (public,
protected, private) that separate the interface from the
implementation.

Ques 3. What do you understand by OOP?

Object-Oriented Programming (OOP) is a programming paradigm based on


the concept of objects, which represent real-world entities or abstract
concepts. It organizes code into classes (blueprints) and objects
(instances) to encapsulate data and behaviour. The core principles of OOP
are:

1. Encapsulation: Bundling data and methods together, restricting


direct access to internal details.
2. Inheritance: Enabling one class to inherit properties and methods
from another.
3. Polymorphism: Allowing entities to take multiple forms, such as
method overloading or overriding.
4. Abstraction: Hiding complex details and exposing only essential
features.

Ques 4. Tell the advantage of OOP.


• Modularity: OOP promotes code organization into classes and
objects, making it easier to manage and maintain.
• Reusability: Inheritance allows developers to reuse existing code in
new applications, reducing redundancy.
• Encapsulation: Protects data by restricting direct access and
exposing functionality through controlled interfaces.
• Scalability: Classes and objects can be easily extended, making
systems more adaptable to change.
• Improved Debugging and Testing: Encapsulation and modular
design simplify error detection and resolution.
• Real-World Modelling: It helps model real-world things (like cars,
animals) in a natural way.
• Code Maintenance: Promotes clear structure, reducing complexity
and simplifying updates.

Ques 5. What types of operation we can performed on OOP?

• Object Creation: Creating instances of a class to represent real-


world entities.
• Example: Car myCar;
• Data Access and Modification: Accessing or changing object
properties through methods.
• Example: myCar.setSpeed(60);
• Method Invocation: Calling functions defined in the class.
• Example: myCar.start();
• Inheritance Operations: Using and extending functionalities of a
parent class.
• Example: A SportsCar class inherits from Car.
• Polymorphic Operations: Using functions in different ways (e.g.,
method overriding or overloading).
• Example: vehicle->move(); works differently for Car and Bike.
• Encapsulation Enforcement: Controlling access to object data
through public, private, and protected access specifiers.
• Abstraction: Interacting with objects using only essential features
without worrying about their internal implementation.
• Operator Overloading: Defining custom behaviour for standard
operators.
• Example: Complex c3 = c1 + c2;
• Runtime Operations: Performing dynamic binding or type-checking
during execution.
• Example: Using dynamic_cast to check object types.

Ques 6. What is Procedural programming language?

A procedural programming language is a type of programming language


that follows a sequence of well-defined steps or procedures (also called
functions or routines) to perform a task. It focuses on procedures or
actions that manipulate data, rather than on the data itself. In procedural
programming, programs are structured as a series of instructions that are
executed in a step-by-step manner, often in the form of functions or
procedures that can be reused.

Key Features:

1. Sequence: Instructions are executed in a specific order.


2. Modularity: Code is divided into functions or procedures for reuse.
3. State: Data is manipulated by passing it between functions.
4. Top-Down Approach: Programs are typically designed from top to
bottom, starting with high-level procedures.
Ques 7. Difference between object oriented and Procedural
programming language?

Object Oriented programming Procedure Oriented Programming

Focuses on objects (real-world entities) Focuses on procedures or functions and


and data encapsulation. step-by-step tasks.
Data and methods are bundled together Data is separate from functions; data is
in classes and objects. passed between functions.
Follows a bottom-up approach, Follows a top-down approach, writing
organizing code into objects. functions to process data.
Encapsulation, Inheritance,
Functions, Variables, Control Flow.
Polymorphism, Abstraction.
Encourages code reuse through Reusability is achieved through function
inheritance and polymorphism. reuse.
Encapsulation protects data by
Data is directly accessible and can be
controlling access with access
modified freely
specifiers (private, public).
Programs are structured around objects Programs are structured around
and classes. procedures or functions.
C++, Java, Python, Ruby. C, Fortran, Pascal, Assembly.
Easier to maintain and extend due to Can become more difficult to maintain as
modularity and inheritance. the code grows.
Better suited to model real-world Less effective for modelling real-world
entities (e.g., a Car, Person). systems compared to OOP.

Ques 8. What is Data Hiding?

Data hiding is a principle in object-oriented programming that restricts


access to the internal state of an object. It ensures that the internal details
or implementation of a class are not directly accessible or modifiable from
outside the class. Instead, access is provided through controlled
interfaces like getter and setter methods. This is achieved using access
specifiers such as private, protected, and public.

Purpose:

1. To protect the integrity of data by preventing unauthorized access or


modification.
2. To maintain encapsulation and ensure better security and control
over how data is used.

Ques 9. Define Polymorphism.


Polymorphism is a fundamental concept in object-oriented programming
that allows objects or methods to take on multiple forms. It enables the
same operation or method name to behave differently based on the
context, such as the type of object or the parameters passed.
Polymorphism is achieved through method overloading (compile-time
polymorphism) and method overriding (runtime polymorphism),

Ques 10. Define Encapsulation.


Encapsulation is a principle of object-oriented programming that binds
data (attributes) and methods (functions) together within a class and
restricts direct access to them from outside the class. It hides the internal
details and only exposes specific functionality through public methods.
This is achieved using access specifiers like private, protected, and
public. Encapsulation ensures data security, modularity, and better
control over how data is accessed or modified. For example, attributes of a
class can be accessed and modified only through getter and setter
methods, preventing unauthorized or unintended changes.

Ques 11. What is inline function? How they are different from other
function?
An inline function is a special type of function in C++ where the compiler
attempts to expand the function's code directly at the place of the function
call, instead of executing a normal function call. This eliminates the
overhead of function call mechanisms like stack operations and context
switching. Inline functions are declared using the inline keyword before
the function definition.
Syntax for inline function:
inline int square(int x) {
//function body;
}
Difference Between Inline Functions and Regular Functions:

• Execution:
o Inline Function: The function code is inserted directly at the
point of the function call, avoiding the overhead of a function
call.
o Regular Function: The function is executed via a standard
function call, involving stack operations and context switching.
• Overhead:
o Inline Function: No overhead of function calls (e.g., stack
usage), but can increase the program size if overused.
o Regular Function: Includes overhead due to function call
mechanisms like pushing and popping values on the stack.
• Program Size:
o Inline Function: Can increase program size if used
excessively, as the code is duplicated at every call site.
o Regular Function: No increase in program size, as the function
code exists only once in memory.
• Usage:
o Inline Function: Best for small, simple functions (e.g.,
getters/setters, small calculations).
o Regular Function: Suitable for both simple and complex
functions, especially those that involve multiple operations or
recursion.
• Recursion:
o Inline Function: Cannot be used with recursive functions.
o Regular Function: Supports recursion naturally.
• Compiler Behaviour:
o Inline Function: The inline keyword is a suggestion to the
compiler, which may ignore it for large or complex functions.
o Regular Function: The function is always treated as a normal
function, regardless of its complexity.
Ques 12. Write a program to multiply two matrices.

Ques 13. What is array of structure?


An array of structures is a data structure in C++ that combines arrays and
structures. It is used to store multiple structures of the same type in a
single array.
Syntax:
struct structure_name{
data_type member1;
data_type member2;
};
int main(){
structure_name arr_name[size];
Sample programm:
#include <iostream>
using namespace std;
struct myStruct{
int age;
string name;
};
int main() {
myStruct st[2];
st[0].name = "shiva verma";
st[1].name = "mayank";
st[0].age = 18;
st[1].age = 19;
for(int i = 0;i<2;i++){
cout<<st[i].name<<endl<<st[i].age<<endl;
}
return 0;
}

Ques 14. What is void pointer? Where it will use.


A void pointer is a special type of pointer in C and C++ that can point to
any data type. It is declared using the void* keyword. Since a void pointer
does not have a specific type, it cannot be directly dereferenced without
casting it to a specific data type.

Syntax: void* ptr;

Used when the type of data is not known in advance or when a function
needs to handle different types of data.

• Example: In dynamic memory allocation (malloc or calloc), the


returned pointer is of type void*.

Ques 15. Define different types of operator in OOP.

Types of Operators in OOP:

In Object-Oriented Programming (OOP), operators are special symbols


used to perform operations on operands. These operators can be
categorized based on their functionality and the number of operands they
operate on. Here are the main types:

1. Arithmetic Operators:

Used for performing mathematical calculations.


• Examples: + (addition), - (subtraction), * (multiplication), /
(division), % (modulus).

2. Relational (Comparison) Operators:

Used to compare two values or objects.

• Examples: == (equal to), != (not equal to), < (less than), > (greater
than), <= (less than or equal to), >= (greater than or equal to).

3. Logical Operators:

Used to perform logical operations.

• Examples: && (logical AND), || (logical OR), ! (logical NOT).

4. Assignment Operators:

Used to assign values to variables or objects.

• Examples: = (assignment), += (add and assign), -= (subtract and


assign), *= (multiply and assign), /= (divide and assign).

5. Bitwise Operators:

Used to perform bit-level operations.

• Examples: & (AND), | (OR), ^ (XOR), ~ (complement), << (left shift),


>> (right shift).

6. Unary Operators:

Operate on a single operand to modify its value or state.


• Examples: ++ (increment), -- (decrement), - (unary minus), + (unary
plus), ! (logical NOT).

7. Ternary Operator:

A shorthand for if-else conditions.

• Syntax: condition ? expr1 : expr2


• Example: int result = (a > b) ? a : b;

8. Special Operators:

Used for specific purposes in OOP.

• Examples:
o sizeof: To get the size of a data type or object.
o :: (scope resolution): To access a global variable or a class
member.
o . and ->: To access members of a class or structure.
o new and delete: For dynamic memory allocation and
deallocation.

9. Type Cast Operators:

Used to convert one data type to another.

• Examples: static_cast, dynamic_cast, const_cast, reinterpret_cast.

10. Input/Output Operators:

Used for input and output operations.

• Examples: >> (extraction), << (insertion).

Ques 16. What is scope resolution operator?


The scope resolution operator (::) in C++ is used to specify and access
variables, functions, or class members that are defined in a particular
scope. It resolves ambiguity when identifiers in different scopes (like global
and local) have the same name. It is also used for defining class methods
outside the class, accessing static members, and working with
namespaces.

Use of :: (Scope Resolution Operator) in OOP:

1. Access Global Variables:

Used to differentiate between global and local variables with


the same name.

Example:

int x = 10; // Global variable


class Test {
int x; // Local variable
public:
void show() {
cout << "Global x: " <<::x << endl;
}
};

2. Define Class Member Functions Outside the Class:

Allows defining member functions outside the class definition.

class Test {
public:
void display();
};
void Test::display() { // Defined outside
using ::
cout << "This is a member function!" << endl;
}

3. Access Static Members of a Class:

Used to access or define static members of a class.

class Test {
public:
static int count;
};
int Test::count = 0; // Define static member
using ::

4. Invoke Base Class Methods in Derived Classes:

Enables access to overridden base class methods from a derived


class.

class Base {
public:
void display() { cout << "Base class
function" << endl; }
};
class Derived : public Base {
public:
void display() { cout << "Derived class
function" << endl; }
void callBase() { Base::display(); } // Call
base class function
};

5. Work with Namespaces:

Used to access variables, functions, or classes within a specific


namespace.
namespace MyNamespace {
int num = 100;
}
void display() {
cout << MyNamespace::num << endl; // Access
namespace member
}

Ques 17. What is function overloading? explain with the example.

Function overloading is a feature in C++ that allows multiple functions to


have the same name but with different parameter lists (type, number, or
order of parameters). The compiler differentiates between these functions
based on their signatures. This improves code readability and reuse.

• The return type of the function is not considered for overloading.


• The functions must differ in their parameter list to avoid ambiguity

Example:

#include <iostream>

using namespace std;

class funcOverloading{

public:

void sum(int x,int y){

cout<<"sum of x and y is: "<<x+y<<endl;

void sum(int x,int y,int z){

cout<<"sum of x, y and z is: "<<x+y+z<<endl;

}
void sum(double x,double y){

cout<<"sum of x and y is: "<<x+y<<endl;

void sum(double x,int y){

cout<<"sum of x and y is: "<<x+y<<endl;

void sum(int x,double y){

cout<<"sum of x and y is: "<<x+y<<endl;

};

int main() {

funcOverloading obj;

obj.sum(10,20);

obj.sum(10,20,30);

obj.sum(12.34,34.21);

obj.sum(12.32,12);

obj.sum(12,23.56);

return 0;

Output :

sum of x and y is: 30

sum of x, y and z is: 60


sum of x and y is: 46.55

sum of x and y is: 24.32

sum of x and y is: 35.56

Ques 18. What is recursive function?

A recursive function is a function in programming that calls itself directly


or indirectly to solve a problem. It breaks the problem into smaller
instances of the same problem until it reaches a base condition, which
stops further recursion. This approach is commonly used for problems that
can be defined in terms of simpler, smaller subproblems, such as
factorials, Fibonacci series, and tree traversals.

Note: Each recursive function must have a terminating condition.

Ques 19. What is constructor? Explain its types with the help of
program.

A constructor is a special member function in C++ that is automatically


invoked when an object of a class is created. Its purpose is to initialize the
object's data members. The constructor has the same name as the class
and does not have a return type.

Types of Constructors:

1. Default Constructor:
a. A constructor that takes no arguments.
b. Automatically called when an object is created without
passing arguments.
c. If no constructor is explicitly defined in the class, the compiler
provides a default constructor.
2. Parameterized Constructor:
a. A constructor that takes arguments to initialize object data
members with specific values.
3. Copy Constructor:
a. A constructor that creates a new object as a copy of an existing
object.
Example:
#include <iostream>
using namespace std;
class Example{
public:
Example(){
cout<<"default constructor\n";
}
Example(int x){
cout<<"parametrized constructor\n";
}
Example(const Example& obj){
cout<<"copy constructor\n";
}
};
int main() {
Example obj;
Example obj1(10);
Example obj2 = obj1;
return 0;
}
Output:

default constructor

parametrized constructor
copy constructor

Ques 20. Types of constructor in details.

Same as Ques 19.

Ques 21. What is new and delete operator?

In C++, new and delete are operators used for dynamic memory
management, allowing programmers to allocate and deallocate memory
during runtime.

1. new Operator:

• The new operator is used to dynamically allocate memory for


variables, arrays, or objects on the heap.
• It returns a pointer to the allocated memory.
• Automatically calls the constructor if the memory allocated is for an
object.
Syntax for new:

pointer = new data_type; // Allocates memory for a single variable

pointer = new data_type[size]; // Allocates memory for an array

2. delete Operator:

• The delete operator deallocates memory allocated by new and frees


it for reuse.
• It is essential to avoid memory leaks by releasing dynamically
allocated memory.
• For arrays, use delete[].
Syntax for delete:

delete pointer; // deallocate memory for single variable


delete[] pointer; // deallocate memory for array

Ques 21. Define Destructor.

A destructor is a special member function in C++ that is automatically


invoked when an object goes out of scope or is explicitly deleted. Its
primary purpose is to release resources such as memory or file handles
allocated to the object during its lifetime. A destructor has the same name
as the class but is prefixed with a tilde (~) and does not take arguments or
return a value.

• Automatically called when an object is destroyed.


• Cannot be overloaded.
• Used to clean up resources and prevent resource leaks
• There will be one and only one destructor for each class.
Syntax:
~class_name(){
// destructor body
}

Ques 23. What is characteristics of Constructor?

A constructor is a special member function in C++ designed to initialize


objects when they are created. Below are its key characteristics:

1. Same Name as the Class:


a. The constructor's name must exactly match the class name.
2. No Return Type:
a. Constructors do not have a return type, not even void.
3. Automatic Invocation:
a. A constructor is automatically called when an object of the
class is created.
4. Overloading is Allowed:
a. You can define multiple constructors in the same class with
different parameter lists (constructor overloading).
5. No Explicit Calls:
a. You cannot explicitly call a constructor; it is invoked
automatically during object creation.
6. Default Constructor:
a. If no constructor is defined, the compiler provides a default
constructor.
7. Can Initialize Members:
a. Constructors are used to initialize data members of the class,
either with default or user-specified values.
8. Can Use Initialization Lists:
a. Constructors can use initialization lists to initialize data
members directly.
9. Cannot Be Virtual:
a. Constructors cannot be declared as virtual.

Ques 24. What is friend function? explain with help of example.

In C++, a friend function is a function that is not a member of a class but is


allowed to access the private and protected members of that class. A
friend function is declared in the class definition by using the friend
keyword.

• It is not a member of the class.


• It can access private and protected data members of the class.
• It is defined outside the class but declared inside the class using the
friend keyword.
Example:

#include <iostream>

using namespace std;

class Complex {

private:

int real;
int imag;

public:

Complex(int r = 0, int i = 0) : real(r), imag(i) {}

friend Complex addComplex(const Complex& c1, const Complex& c2);

void display() const {

cout << real << " + " << imag << "i" << endl;

};

Complex addComplex(const Complex& c1, const Complex& c2) {

return Complex(c1.real + c2.real, c1.imag + c2.imag);

int main() {

Complex c1(3, 4), c2(1, 2);

Complex c3 = addComplex(c1, c2); // Calling the friend function

cout << "Complex Number 1: ";

c1.display();

cout << "Complex Number 2: ";

c2.display();

cout << "Sum: ";

c3.display();

return 0;

}
Ques 25. What do you mean by dynamic memory allocation?

Dynamic memory allocation refers to the process of allocating memory


during the execution (runtime) of a program, rather than at compile time. It
allows a program to request memory as needed and release it when it is no
longer required.

In C++, the new operator is used to allocate memory, and the delete
operator is used to deallocate it.

Common Operations in Dynamic Memory Allocation (C++):

1. Allocation: Requesting memory from the system during runtime.


2. Deallocation: Releasing the allocated memory back to the system.

Ques 26. What is This pointer? Explain with example.

In C++, this pointer is a special pointer available in non-static member


functions of a class. It points to the current object (the object that invoked
the member function). Using the this pointer, you can access members of
the current object or resolve naming conflicts between class data
members and function parameters or local variable.

• It is implicitly passed to all non-static member functions of a class.


• It is not available in static member functions because they are not
tied to any specific object.
• It can be used to return the current object from a member function.

Example:

#include <iostream>

using namespace std;

class Rectangle{

int length,breadth;

public:
Rectangle(int length,int breadth){

this->length = length;

this->breadth = breadth;

void area(){

cout<<"Area of rectangle is: "<<length*breadth<<endl;

};

int main() {

Rectangle rec(4,5);

rec.area();

return 0;

Output:

Area of rectangle is: 20

Ques 27. What is copy constructor?

A copy constructor in C++ is a special constructor used to create a new


object as a copy of an existing object. It initializes a new object with the
values of an existing object of the same class.

The copy constructor is invoked in the following scenarios:

1. When an object is initialized using another object of the same class


(e.g., ClassName obj2 = obj1;).
2. When an object is passed by value to a function.
3. When an object is returned by value from a function.
Ques 28. Define Inheritance concept with the help of example.
Inheritance is a fundamental concept in object-oriented programming that
allows a class (called the derived class) to inherit properties and
behaviours (data members and member functions) from another class
(called the base class). This promotes code reusability and establishes a
hierarchical relationship between classes.

Key Concepts of Inheritance

1. Base Class: The class whose properties are inherited.


2. Derived Class: The class that inherits from the base class.
3. Access Specifiers: Determine how members of the base class are
accessible in the derived class (public, protected, private).

Types of Inheritance

1. Single Inheritance: A derived class inherits from a single base class.


2. Multiple Inheritance: A derived class inherits from more than one
base class.
3. Multilevel Inheritance: A derived class inherits from a base class,
and then another class inherits from the derived class.
4. Hierarchical Inheritance: Multiple classes inherit from a single base
class.
5. Hybrid Inheritance: A combination of more than one type of
inheritance.
Ques 29. Categories the types of Inheritance.

Ques 30. Define multiple inheritance with the help of suitable program.
Multiple inheritance is a type of inheritance in which a derived class
inherits from two or more base classes. It allows the derived class to
access and combine the properties and methods of multiple base classes.
1. Derived Class Access: The derived class inherits all accessible
members (depending on the access specifiers) from the multiple
base classes.
2. Ambiguity: If two base classes have members with the same name,
ambiguity can arise, which must be resolved explicitly using the
scope resolution operator or virtual base class.
Syntax:
class Base1 {
// Members of Base1
};
class Base2 {
// Members of Base2
};
class Derived : public Base1, public Base2 {
// Members of Derived
};

Ques 31. What is virtual base class? Explain.


A virtual base class is a concept in C++ that helps to resolve ambiguity in
inheritance when a derived class indirectly inherits the same base class
through multiple paths. It is used primarily to prevent duplicate copies of
the base class when there is diamond-shaped inheritance.

Diamond Problem in Inheritance

Consider the following inheritance hierarchy:

1. Class A is a base class.


2. Class B and Class C inherit from Class A.
3. Class D inherits from both Class B and Class C.
4. This creates a diamond structure where Class D ends up with two
copies of Class A. This duplication can lead to ambiguity.

Solution to resolve this Ambiguity:


To resolve this issue, virtual inheritance is used. Declaring Class A as a
virtual base class ensures that only one shared copy of Class A exists,
regardless of how many paths lead to it.
Syntax:
class A{
// body of class A;
};
class B:public class A{
// body of class B;
};
class C:public class A{
// body of class C;
};
class D:public class B,public class C{
//body of class D
};
Example program:
#include <iostream>
using namespace std;
class A{
public:
void show(){
cout<<"Base class A\n";
}
};
class B:virtual public A{};
class C:virtual public A{};
class D:public B,public C{};
int main() {
D obj;
obj.show();
return 0;
}

Ques 33. Difference between Static and Dynamic binding.


In C++, binding refers to the process of linking a function call to its
definition. Based on the timing of this linkage, binding is categorized as
static binding or dynamic binding.

1. Static Binding

Definition:

Static binding, also known as early binding, occurs at compile time. The
compiler determines which function to call based on the type of the object
at compile time.

Key Features:

• Faster execution as the decision is made during compilation.


• Associated with normal function calls and function overloading.
• Uses the type of the pointer or object for determining the function
call.
• The final function called cannot be overridden by derived classes.
Example:
#include <iostream>
using namespace std;

class Base {
public:
void display() { // Normal function
cout << "Display from Base class (Static Binding)" << endl;
}
};

class Derived : public Base {


public:
void display() { // Overrides Base class display
cout << "Display from Derived class" << endl;
}
};

int main() {
Base obj; // Object of Base class
obj.display(); // Calls Base::display() (static binding)

return 0;
}

2. Dynamic Binding

Definition:

Dynamic binding, also known as late binding, occurs at runtime. The


decision of which function to call is made based on the type of the object
that the pointer or reference is pointing to.

Key Features:

• Slower than static binding due to runtime overhead.


• Achieved using virtual functions in C++.
• The function to call is determined by the actual object type, not the
pointer type.
• Enables polymorphism, where derived class methods override base
class methods.
Example:
#include <iostream>
using namespace std;

class Base {
public:
virtual void display() { // Virtual function
cout << "Display from Base class (Dynamic Binding)" <<
endl;
}
};

class Derived : public Base {


public:
void display() override { // Overrides Base class display
cout << "Display from Derived class" << endl;
}
};

int main() {
Base* objPtr; // Pointer to Base class
Derived derivedObj; // Object of Derived class
objPtr = &derivedObj; // Base class pointer points to Derived
class object

objPtr->display(); // Calls Derived::display() (dynamic


binding)

return 0;
}

Ques 34. What do you mean by Pure virtual function?

A pure virtual function in C++ is a virtual function that is declared in a


base class but has no implementation in that class. Instead, it must be
overridden by all derived classes. It acts as a placeholder, enforcing that
the derived classes provide their own version of the function.

Syntax:

class Base{

public:

virtual void func_name()=0; //this is a pure virtual function


}

• Abstract Class: Any class containing at least one pure virtual


function becomes an abstract class. Abstract classes cannot be
instantiated directly.
• Mandatory Override: All derived classes must provide an
implementation for the pure virtual function. Otherwise, the derived
class itself also becomes abstract.
• Polymorphism: Pure virtual functions enable runtime
polymorphism, as the derived class implementation is called based
on the type of the object.

Example:

#include<iostream>

using namespace std;

class shape{

public:

virtual void draw()=0;

virtual double area()=0;

};

class Rectangle:public shape{

int l,b;

public:

Rectangle(int l,int b){

this->l = l;

this->b = b;

}
double area(){

return l*b;

void draw(){

cout<<"Drawing a rectangle\n";

};

int main(){

shape* c = new Circle(3);

shape* rec = new Rectangle(5,3);

Rec->draw();

cout<<"Area of rectangle is: "<<rec->area()<<endl;

C->draw();

cout<<"Area of circle is: "<<c->area()<<endl;

return 0;

Output:

Drawing a rectangle

Area of rectangle is: 15

Drawing a circle

Area of circle is: 28.26


Ques 35. Define abstract class.

An abstract class in C++ is a class that is designed to be a base class and


cannot be instantiated directly. It is used to define a common interface for
its derived classes. An abstract class typically contains at least one pure
virtual function.

Syntax:

class AbstractClass {

public:

virtual void pureVirtualFunction() = 0; // Pure virtual function

};

Example: Example is same as ques 34.

Ques 36. What are Typecasting?

Typecasting is the process of converting a variable from one data type to


another. In C++, it allows the programmer to explicitly or implicitly change
the type of a variable during program execution.

Typecasting in C++

Typecasting is the process of converting a variable from one data type to


another. In C++, it allows the programmer to explicitly or implicitly change
the type of a variable during program execution.

Types of Typecasting in C++

1. Implicit Typecasting (Type Conversion):


a. Performed automatically by the compiler.
b. Happens when data is converted from a smaller data type to a
larger data type or when no loss of data occurs.
Example:
int a = 5;

double b = a; // Implicit typecasting from int to double

cout << b; // output 5.0

2. Explicit Typecasting (Type Conversion):

• Done manually by the programmer.


• The programmer specifies the desired type explicitly using casting
operators.
• This is required when converting data might result in information
loss or is not automatic.

Example:

double a = 5.7;

int b = (int)a; // Explicit typecasting from double to int

cout << b; // output 5

Ques 37. What is exception handling?

An exception is an abnormal condition that occurs during the execution


of a program, disrupting its normal flow. Exceptions typically arise due to
unforeseen situations, such as invalid input, division by zero, file not
found, or out-of-memory errors.

Exception handling is a mechanism in C++ used to handle runtime errors


or unexpected conditions in a program gracefully without causing it to
crash. It separates error-handling code from regular code, making
programs more robust and easier to maintain.

Exception handling is achieved throw try catch block:

• try: the code that might throw error is placed inside try block.
• throw: Used to throw an exception when an error is detected.
• catch: Defines a block of code to handle the exception.

Ques 38. Tell the types of exception handling?

In C++, exception handling can be categorized into several types based on


how exceptions are thrown, caught, and handled. These can be classified
into:

1. Synchronous Exceptions

• Definition: These exceptions occur when the program executes


code that explicitly throws an exception, typically caused by logical
errors or specific conditions in the program.
• Examples:
o Division by zero
o Array index out-of-bounds
o Invalid input (such as non-numeric values when expecting
integers)

2. Asynchronous Exceptions

• Definition: These exceptions are not directly triggered by the


program's logic but are instead caused by external events like
hardware failures or system-level issues.
• Examples:
o Interrupts or signals (e.g., a segmentation fault).
o Memory access violations.
o Stack overflow.

3. Standard Exception Types

• C++ provides a hierarchy of standard exceptions under the


<exception> header. These are used to represent common errors
and can be caught using catch blocks.

Common Standard Exception Types:


• std::exception: Base class for all exceptions.
• std::logic_error: For errors in logic (e.g., invalid arguments).
• std::runtime_error: For runtime errors (e.g., out of memory).
• std::out_of_range: For accessing out-of-bounds elements.
• std::overflow_error: For arithmetic overflow.
• std::underflow_error: For arithmetic underflow.

In C++, exception handling can be categorized into several types based on


how exceptions are thrown, caught, and handled. These can be classified
into:

1. Synchronous Exceptions

• Definition: These exceptions occur when the program executes


code that explicitly throws an exception, typically caused by logical
errors or specific conditions in the program.
• Examples:
o Division by zero
o Array index out-of-bounds
o Invalid input (such as non-numeric values when expecting
integers)

Example:

cpp
Copy code
try {
int a = 10, b = 0;
if (b == 0) {
throw "Division by zero error"; // Synchronous
exception
}
cout << a / b;
} catch (const char* msg) {
cout << "Exception: " << msg << endl;
}
2. Asynchronous Exceptions

• Definition: These exceptions are not directly triggered by the


program's logic but are instead caused by external events like
hardware failures or system-level issues.
• Examples:
o Interrupts or signals (e.g., a segmentation fault).
o Memory access violations.
o Stack overflow.

Note: Asynchronous exceptions are typically managed by the operating


system or hardware and are not commonly handled with C++ exception
handling mechanisms (i.e., try, catch, throw).

3. Standard Exception Types

• C++ provides a hierarchy of standard exceptions under the


<exception> header. These are used to represent common errors
and can be caught using catch blocks.

Common Standard Exception Types:

• std::exception: Base class for all exceptions.


• std::logic_error: For errors in logic (e.g., invalid arguments).
• std::runtime_error: For runtime errors (e.g., out of memory).
• std::out_of_range: For accessing out-of-bounds elements.
• std::overflow_error: For arithmetic overflow.
• std::underflow_error: For arithmetic underflow.

Example:

#include <iostream>
#include <stdexcept>

using namespace std;

int main() {
try {
throw runtime_error("This is a runtime error.");
} catch (const runtime_error& e) {
cout << "Caught exception: " << e.what() << endl;
}
return 0;
}

Output:

Caught exception: This is a runtime error.

4. User-Defined Exceptions

• Definition: C++ allows you to create custom exception classes to


handle specific errors in your application.
• How to Implement: You define a new class that inherits from
std::exception (or any other exception class) and override the
what() method to provide custom error messages.

Example:

#include <iostream>
#include <exception>

using namespace std;

class MyException : public exception {


public:
const char* what() const noexcept override {
return "My custom exception occurred!";
}
};

int main() {
try {
throw MyException();
} catch (const MyException& e) {
cout << "Caught exception: " << e.what() << endl;
}
return 0;
}

Output:

Caught exception: My custom exception occurred!

5. Nested Exceptions

• Definition: It is possible for one exception to throw another


exception within a catch block. This is known as nested exception
handling.

Example:
#include <iostream>
using namespace std;

void function1() {
try {
throw "Exception from function1";
} catch (const char* msg) {
cout << "Caught in function1: " << msg << endl;
throw; // Rethrow exception
}
}

void function2() {
try {
function1(); // This function may throw an exception
} catch (const char* msg) {
cout << "Caught in function2: " << msg << endl;
}
}

int main() {
try {
function2();
} catch (const char* msg) {
cout << "Caught in main: " << msg << endl;
}
return 0;
}

Ques 39. Write various I/O operation on file.

In C++, file I/O operations allow you to read from and write to files. The
standard C++ library provides classes such as ifstream, ofstream, and
fstream for handling file input and output. These classes are defined in
the <fstream> header file.

Basic File I/O Operations in C++

1. Opening a File: To perform file I/O operations, you first need to open
the file using one of the file stream classes (ifstream, ofstream, or
fstream).
2. Reading from a File: You can use ifstream to read data from a file.
3. Writing to a File: You can use ofstream to write data to a file.
4. Closing a File: After performing the required operations, the file
should be closed using the .close() function to free resources.
5. Checking if the File is Open:You can check if a file has been
successfully opened using the .is_open() method.

File Modes

When opening a file, you can specify different file modes by passing flags.
These flags can be combined using the bitwise OR operator (|).
Here are the most commonly used file modes:

• ios::in: Open file for reading.


• ios::out: Open file for writing.
• ios::app: Open file in append mode (write at the end of the file).
• ios::ate: Open file for writing, and set the pointer to the end of the
file.
• ios::binary: Open file in binary mode.
• ios::trunc: Open file for writing and truncate it (erase content if file
already exists).

File Operations in C++

1. Opening a File for Writing (ofstream)

This creates a file if it does not exist or truncates it if it already exists.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstream outFile("example.txt"); // Open for writing
if (!outFile) {
cout << "Error opening file!" << endl;
return 1;
}

outFile << "Hello, World!" << endl;


outFile << "This is a file writing example." << endl;

outFile.close(); // Close the file


cout << "Data written to the file successfully." <<
endl;
return 0;
}
2. Opening a File for Reading (ifstream)

You can read data from a file using ifstream.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
ifstream inFile("example.txt"); // Open for reading
if (!inFile) {
cout << "Error opening file!" << endl;
return 1;
}

string line;
while (getline(inFile, line)) { // Read line by line
cout << line << endl;
}

inFile.close(); // Close the file


return 0;
}

3. Opening a File for Both Reading and Writing (fstream)

You can use fstream to read and write to a file.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
fstream file("example.txt", ios::in | ios::out); //
Open for reading and writing
if (!file) {
cout << "Error opening file!" << endl;
return 1;
}

// Writing to the file


file << "Adding a new line of text.\n";

// Moving file pointer to the beginning


file.seekg(0, ios::beg); // Move to the beginning of
the file

string line;
while (getline(file, line)) { // Read and print each
line
cout << line << endl;
}

file.close(); // Close the file


return 0;
}

4. Appending Data to a File

Use the ios::app mode to append data to the end of an existing file.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstream outFile("example.txt", ios::app); // Open
for appending
if (!outFile) {
cout << "Error opening file!" << endl;
return 1;
}
outFile << "This line is appended to the file.\n";
outFile.close(); // Close the file
cout << "Data appended successfully." << endl;
return 0;
}

5. Binary File I/O

For reading and writing binary files, use the ios::binary mode. This is
useful when dealing with non-text data (e.g., images, audio).

#include <iostream>
#include <fstream>
using namespace std;

struct Person {
char name[50];
int age;
};

int main() {
Person p1 = {"John Doe", 30};

// Writing binary data to file


ofstream outFile("person.dat", ios::binary); // Open
in binary mode
if (!outFile) {
cout << "Error opening file!" << endl;
return 1;
}

outFile.write(reinterpret_cast<char*>(&p1),
sizeof(p1)); // Write struct to file
outFile.close();

// Reading binary data from file


Person p2;
ifstream inFile("person.dat", ios::binary); // Open
in binary mode
if (!inFile) {
cout << "Error opening file!" << endl;
return 1;
}

inFile.read(reinterpret_cast<char*>(&p2), sizeof(p2));
// Read struct from file
inFile.close();

cout << "Name: " << p2.name << ", Age: " << p2.age <<
endl;
return 0;
}

6. File Checking Functions

• .is_open(): Check if a file is open.


• .eof(): Check if the end of the file has been reached.
• .fail(): Check if a file operation failed.
• .clear(): Reset any error state (e.g., after EOF or fail).

You might also like