Ques: Explain Oops Concepts in Detail With Example
Ques: Explain Oops Concepts in Detail With Example
Ques: Explain Oops Concepts in Detail With Example
Ans. : OOPs concepts in C++ are based on the concept of objects, which can contain data and methods that operate on
that data.
In this article, we will discuss the OOPS concepts in C++. We will discuss what is OOPS, what classes and objects in OOPS
are, and the 4 pillars of OOPS in C++. So, let’s get started by learning what is Object-Oriented Programming.
What is OOPS?
The programming paradigm known as "Object-Oriented Programming" works with objects and classes. In a subsequent
section of this article, we will talk about objects and classes. For the time being, we can state that object-oriented
programming is a style of programming that, by emphasizing real-world elements (called objects), greatly simplifies
programming.
1. Inheritance
2. Polymorphism
3. Abstraction
4. Encapsulation
Examples
Objects : An object is an instance of a Class. This is the formal definition of an Object. However, let us talk about the
actual meaning of an object first as we don’t know what a Class is for now. An object is a real-world entity. It has states
i.e. its properties and behaviors i.e. its functions.
We could claim, for example, that a car is an object. This is due to the states (properties) that it will have, such as the
model name, brand name, color, and type (SUV or Sidan, etc.). Additionally, it will perform actions like speeding up (a
car can speed up), braking (when stopping), etc.
A pen is yet another example of an object. It has states describing its color, brand, etc.
It has functions like writing, scribbling, etc.
Classes : A Class is a blueprint of an Object. It will tell us what properties an object will have and what functions it can
perform. However, the values of those properties can vary from object to object. For instance, a Car is a class that may
have properties like color, brand name, model name, etc. Now, there can be a car whose name is “Swift” whose brand
name is “Maruti Suzuki” and whose color is “Grey”. Also, there can be another car whose model name is “Polo” and
the brand name is “Volkswagen” and whose color is “Red.”
A Class is a collection of properties (or states, like size, color, etc.) and behavior (or functions, like writing, reading,
walking, talking, etc.).
The different objects have varying values for these attributes, and all of them or some of them carry out some or all of
the functions listed in a class.
Now that we know what Classes and Objects are, let us now create a Class and its Objects.
Class and Object Example Program :
// Default argument
#include <bits/stdc++.h>
class Student {
public:
string name;
int roll_no;
int marks;
this->name = name;
this->roll_no = roll_no;
void printData() {
};
int main() {
Student s1;
s1.setData("Guneet",2,95);
s1.printData();
So, in the program above, a class Student is created that has these 3 data members: name, marks, and roll_no.
Also, it has functions called member functions in C++. The functions are setData() and printData().
So, now that we have understood how to create Classes and Objects in C++, let us move to Constructors in C++.
Ques: What is constructor & destructor? Explain different types of constructor in detail?
Ans. : Constructor: A constructor is a special member function with the same name as the class, and it is automatically
called when an object of the class is created. Its main purpose is to initialize the data members of the class and perform
any necessary setup operations. Constructors do not have a return type, not even void, and are invoked automatically
whenever an object is created.
(a) Default Constructor : A default constructor is a constructor that takes no arguments. If a class does not define any
constructors, the compiler generates a default constructor automatically. Its role is to initialize the class members to
their default values, typically zero or null.
(b) Parameterized Constructor : A parameterized constructor is a constructor that takes one or more arguments. It allows
you to pass specific values to initialize the object's data members during object creation.
(c) Copy Constructor : A copy constructor is a constructor that creates a new object as a copy of an existing object of the
same class. It is invoked when a new object is created from an existing object, either explicitly or implicitly (such as
when passing objects by value to functions).
(d) Constructor Overloading : Constructor overloading is the ability to define multiple constructors within a class, each
with a different set of parameters. This allows objects to be created and initialized in various ways depending on the
arguments provided.
Destructor : A destructor is a special member function with the same name as the class, preceded by a tilde (~). It is
automatically called when an object goes out of scope or is explicitly deleted using the delete keyword. The main purpose
of the destructor is to release any resources or memory allocated by the object during its lifetime.
(a) Single Inheritance : In single inheritance, a class inherits from only one base class. This is the most common type of
inheritance.
// Base class
class Shape {
public:
void draw() {
// Draw the shape
}
};
// Base class
class Person {
public:
void introduce() {
};
class Programmer {
public:
void code() {
// Write code
};
public:
void debug() {
// Debug code
};
(c) Multilevel Inheritance : In multilevel inheritance, a class derives from another class, which itself is derived from a
base class. It forms a chain of inheritance.
// Base class
class Animal {
public:
void eat() {
// Animal eats
};
// Derived class (inherits from Animal)
public:
void run() {
// Mammal runs
};
public:
void bark() {
// Dog barks
};
(d) Hierarchical Inheritance : In hierarchical inheritance, multiple derived classes inherit from the same base class. This
creates a hierarchy of classes.
// Base class
class Vehicle {
public:
void drive() {
// Vehicle drives
};
public:
void honk() {
// Car honks } };
public:
void ringBell() {
Due to its complex nature and potential ambiguity, C++ does not directly support hybrid inheritance. However, you can
achieve similar functionality through interfaces or virtual inheritance.
// Base class
class Animal {
public:
void move() {
// Animal moves
};
class Bird {
public:
void fly() {
// Bird flies
};
public:
void chirp() {
// FlyingBird chirps
};
In C++, inheritance is a powerful mechanism that enables code reuse and promotes a hierarchical organization of
classes, resulting in cleaner and more maintainable code. However, it's essential to use inheritance judiciously and
carefully design class hierarchies to avoid potential pitfalls like the diamond problem in multiple inheritance.
Ans. : In C++, there are three visibility modes that control the access of class members within derived classes. These
visibility modes are used when inheriting a base class into a derived class. The visibility mode is specified in the base
class during the derivation, and it determines how the members of the base class will be accessible in the derived class.
Public Inheritance : In public inheritance, the public members of the base class remain public in the derived class, and
the protected members remain protected. However, the private members of the base class are not directly accessible in
the derived class.
Ex. :
class Base {
public:
int publicMember;
void publicFunction() {
protected:
int protectedMember;
void protectedFunction() {
private:
int privateMember;
void privateFunction() {
};
public:
void example() {
};
Protected Inheritance : In protected inheritance, the public and protected members of the base class become protected
in the derived class. The private members of the base class are not directly accessible in the derived class.
Ex. :
class Base {
public:
int publicMember;
void publicFunction() {
protected:
int protectedMember;
void protectedFunction() {
private:
int privateMember;
void privateFunction() {
};
public:
void example() {
};
Private Inheritance : In private inheritance, the public and protected members of the base class become private in the
derived class. The private members of the base class are not directly accessible in the derived class.
Ex. :
class Base {
public:
int publicMember;
void publicFunction() {
protected:
int protectedMember;
void protectedFunction() {
private:
int privateMember;
void privateFunction() {
};
public:
void example() {
};
Ques : Write short note
(1) Friend function : In C++, a friend function is a special function that is not a member of a class but has access to the
private and protected members of that class. It is declared as a friend of the class, allowing it to access the private
and protected members as if it were a member of that class. Friend functions are commonly used to allow specific
non-member functions or other classes to access the private data of a class without breaking encapsulation.
Declaration : The friend function is declared inside the class definition with the friend keyword.
Not a Member Function : A friend function is not a member of the class but can access its private and protected
members.
Access to Private and Protected Members : A friend function can access the private and protected data members of the
class, which are otherwise not accessible from outside the class.
Not Inherited : Friendship is not inherited, meaning that friend functions of a class do not automatically become friends
of its derived classes.
(2) Virtual base class : In C++, a virtual base class is used to avoid ambiguity and the "diamond problem" that arises in
multiple inheritance. The "diamond problem" occurs when a derived class inherits from two or more base classes that
share a common base class. This can lead to ambiguity in accessing shared data members and methods, resulting in
errors or unexpected behavior.
To resolve this problem, C++ introduces the concept of a virtual base class. A virtual base class is a base class that is marked
as "virtual" when it is inherited by derived classes. When a class is marked as virtual, only one instance of the virtual base
class is shared among all the classes in the inheritance hierarchy. This ensures that the shared base class is not duplicated,
and the ambiguity is eliminated.
(a) Virtual base classes help in avoiding duplicate copies of shared base class members in the inheritance hierarchy.
(b) The syntax for virtual inheritance is achieved by using the keyword virtual before the access specifier while
inheriting the base class.
(c) Virtual inheritance is most commonly used to resolve the "diamond problem" that arises in multiple inheritance
scenarios.
(d) In the case of virtual inheritance, the most derived class is responsible for constructing the virtual base class.
(3) Reference Variable : In C++, a reference variable is an alias or alternative name for an existing variable. It allows you
to access the same memory location and value as the original variable. Reference variables provide a way to work with
data indirectly, making it easier to modify and manipulate data without creating unnecessary copies.
(a) Declaration : A reference variable is declared using an ampersand (&) symbol after the data type, followed by the
reference name.
(b) Initialization : Reference variables must be initialized at the time of declaration. Once initialized, they cannot be
changed to refer to another variable. They are essentially an alias for the same variable throughout their lifetime.
(c) No memory allocation : Unlike pointers, references do not create new memory locations. They simply refer to the
memory location of an existing variable. As a result, references cannot be null, and they must always be associated
with a valid variable.
(4) Scope resolution Operator : The Scope Resolution Operator (::) in C++ is used to access members (variables, functions,
or types) of a class or namespace that are defined outside the class or namespace's scope. It allows you to specify the
exact location of the member you want to use, avoiding any naming conflicts or ambiguities.
Ques: a) What is an exception and explain use of +try catch & throw with example?
Ans. : An exception in C++ is an event that occurs during the execution of a program that disrupts the normal flow of
instructions. It typically arises when an unexpected condition or error occurs, making it difficult or impossible to
continue executing the program as planned. Exceptions allow the program to handle such errors or exceptional
situations gracefully by providing a mechanism to transfer control to an exception handler.
(a) try: The try block contains the code that may throw an exception. It is followed by one or more catch blocks.
(b) catch: A catch block is used to handle a specific type of exception. It is responsible for catching and handling the
exceptions that are thrown inside the corresponding try block.
(c) throw: The throw statement is used to trigger an exception explicitly. It allows you to specify the type of the
exception that will be thrown, and optionally, you can provide additional information in the form of an object or
value.
Ex.:
#include <iostream>
#include <string>
if (denominator == 0)
int main() {
try {
return 0;
}
b) What are functions calling mechanisms supported by C++?
Ans. : C++ supports several mechanisms for function calling. These mechanisms define how parameters are passed, how
the return value is handled, and how the function call stack is managed. The main function calling mechanisms
supported by C++ are:
Pass by Value:
(a) In this mechanism, the function parameters are passed by creating a copy of the actual arguments. Any modifications
made to the parameters inside the function do not affect the original values of the arguments outside the function.
(b) It is the default mechanism used in C++. Simple data types like int, float, char, etc., are typically passed by value.
Pass by Reference:
(a) In pass by reference, a reference to the actual argument is passed to the function instead of creating a copy. Any
changes made to the parameters inside the function affect the original arguments.
(b) To pass by reference, you use the ampersand (&) symbol in the function's parameter list.
(c) Pass by reference is useful when you want to modify the original arguments or when you want to avoid unnecessary
copying of large objects.
Pass by Pointer:
(a) In pass by pointer, the function receives a pointer to the actual argument. Like pass by reference, any changes made
to the parameters inside the function affect the original arguments.
(b) To pass by pointer, you use pointers in the function's parameter list.
(c) Pass by pointer is useful when you want to allow passing a null value or when you need to perform pointer arithmetic.
Return Value:
(a) C++ functions can return values of different data types, including built-in types, user-defined types, and even
pointers or references.
(b) The return value can be passed by value, reference, or pointer, depending on the function's signature and
the calling context.
(a) C++ manages function calls using a call stack. Each function call creates a new stack frame that stores function
parameters, local variables, and the return address.
(b) When a function calls another function, the return address is saved on the stack, allowing the program to return to
the correct point after the called function completes its execution.
(c) Recursion is a mechanism where a function calls itself. C++ supports recursive function calls, and the call stack is used
to manage multiple levels of recursion.
Ans. : File handling in C++ is performed using the C++ Standard Library's file stream classes, namely ifstream, ofstream,
and fstream. These classes provide a convenient and flexible way to read from and write to files. Here's a step-by-step
guide on how to perform file handling in C++ :
#include <fstream>
Opening a file: To perform file input (read from a file) or file output (write to a file), you need to open the file first. Use
the open() member function of the respective file stream class to open a file.
std::ifstream inputFile;
inputFile.open("filename.txt");
For writing to a file (output):
std::ofstream outputFile;
outputFile.open("filename.txt");
file.open("filename.txt");
Checking if the file is open: Always check if the file has been successfully opened before performing any read or write
operations. You can use the is_open() member function to verify the file's status.
if (inputFile.is_open()) {
} else {
Reading from a file: To read from a file, you can use the >> extraction operator or getline() function (for reading lines).
You can read different data types, such as int, float, string, etc.
int number;
std::string line;
Writing to a file: To write to a file, you can use the << insertion operator.
outputFile << "Hello, this is a line written to the file!" << std::endl;
Closing the file: After performing read or write operations, always remember to close the file using the close() member
function.
inputFile.close();
outputFile.close();
It is essential to close the file explicitly, as it flushes the buffers and releases the resources associated with the file.
Here's a complete example that demonstrates how to read from and write to a file:
#include <iostream>
#include <fstream>
int main() {
std::ofstream outputFile;
outputFile.open("output.txt");
if (outputFile.is_open()) {
outputFile << "Hello, this is a line written to the file!" << std::endl;
outputFile.close();
} else {
std::ifstream inputFile;
inputFile.open("output.txt");
if (inputFile.is_open()) {
std::string line;
inputFile.close();
} else {
return 0;
Make sure to replace "output.txt" with the appropriate file path according to your system's file structure. This example
will write two lines to the file and then read and print them on the console.
Ques:- What is operator overloading? How to overload + operator?
Ans. : Operator overloading in C++ allows you to define the behavior of existing operators for user-defined types. It allows
you to extend the functionality of operators beyond their standard uses, enabling custom behavior when these operators
are used with objects of your own classes.
To overload the + operator for a custom class, you need to define a member function or a global function that implements
the addition operation for objects of that class. The overloaded + operator is used for adding two objects of the class
together, just like how the + operator works with built-in data types.
Here's how you can overload the + operator using a member function:
#include <iostream>
class MyNumber {
private:
int value;
public:
return value;
};
int main() {
MyNumber num1(5);
MyNumber num2(10);
return 0;
}
In this example, the class MyNumber represents a simple integer wrapper. The + operator is overloaded using a member
function named operator+. This function takes a constant reference to another MyNumber object as its parameter,
performs the addition of their values, and returns a new MyNumber object representing the result of the addition.
The main function demonstrates the usage of the overloaded + operator. Two MyNumber objects, num1 and num2, are
created, and the overloaded + operator is used to add them together and store the result in the sum variable. The value
of sum is then printed to the console.
You can also overload the + operator using a global function. Here's how you can do it:
#include <iostream>
class MyNumber {
private:
int value;
public:
return value;
};
int main() {
MyNumber num1(5);
MyNumber num2(10);
return 0;
}
In this version, we define a non-member function operator+ that takes two constant references to MyNumber objects as
its parameters. This function implements the addition operation in the same way as before. To allow this function to access
the private members of the MyNumber class, we declare it as a friend of the class.
Sum: 15
Remember that operator overloading should be used with caution and judiciously. Overusing it can lead to confusing and
less maintainable code. It is generally best to reserve operator overloading for situations where it significantly improves
the readability and expressiveness of your code.