Ques: Explain Oops Concepts in Detail With Example

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

B.C.A.

(IInd-Semester) UT Examination--Object Oriented Programming Using C++ (201)


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.

Object-Oriented Programming has 4 main Pillars. They are as follows.

1. Inheritance

2. Polymorphism

3. Abstraction

4. Encapsulation

Examples

First, let us start by studying what are classes and objects.

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;

void setData(string name,int roll_no, int marks) {

this->name = name;

this->roll_no = roll_no;

this-> marks = marks;

void printData() {

cout<<"My name is "<<name<<" and my roll number is "<<roll_no<<". I


got "<<marks<<" marks out of 100\n";

};

int main() {

// s1 is an object of class Student

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.

There are several types of constructors in C++ :

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

Ques: What is inheritance explain diff. types of inheritance with example?


Ans. : Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called the derived
class or subclass) to inherit properties and behaviors from another class (called the base class or superclass). The derived
class can extend or specialize the functionality of the base class by adding new data members and methods.

In C++, there are different types of inheritance:

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

// Derived class (inherits from Shape)


class Circle : public Shape {
public:
void area() {
// Calculate the area of the circle
}
};
(b) Multiple Inheritance : In multiple inheritance, a class inherits from two or more base classes. It allows the derived
class to combine features from multiple base classes.

// Base class

class Person {

public:

void introduce() {

// Introduce the person

};

// Another base class

class Programmer {

public:

void code() {

// Write code

};

// Derived class (inherits from Person and Programmer)

class SoftwareEngineer : public Person, public Programmer {

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)

class Mammal : public Animal {

public:

void run() {

// Mammal runs

};

// Derived class (inherits from Mammal)

class Dog : public Mammal {

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

};

// Derived class (inherits from Vehicle)

class Car : public Vehicle {

public:

void honk() {

// Car honks } };

// Another derived class (inherits from Vehicle)

class Bike : public Vehicle {

public:

void ringBell() {

// Bike rings the bell } };


(e) Hybrid Inheritance (not directly supported in C++) : Hybrid inheritance is a combination of multiple inheritance and
multilevel inheritance. It involves the use of multiple base classes and forming a hierarchy.

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

};

// Another base class

class Bird {

public:

void fly() {

// Bird flies

};

// Derived class (inherits from Animal and Bird)

class FlyingBird : public Animal, public Bird {

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.

Ques: Explain Different Types of Visibility Modes with example?

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() {

// Accessible in derived class

protected:

int protectedMember;

void protectedFunction() {

// Accessible in derived class

private:

int privateMember;

void privateFunction() {

// Not accessible in derived class

};

class Derived : public Base {

public:

void example() {

publicMember = 10; // Accessible (public member of Base)

protectedMember = 20; // Accessible (protected member of Base)

// privateMember = 30; // Not accessible (private member of Base)

publicFunction(); // Accessible (public function of Base)

protectedFunction(); // Accessible (protected function of Base)

// privateFunction(); // Not accessible (private function of Base)

};
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() {

// Accessible in derived class

protected:

int protectedMember;

void protectedFunction() {

// Accessible in derived class

private:

int privateMember;

void privateFunction() {

// Not accessible in derived class

};

class Derived : protected Base {

public:

void example() {

publicMember = 10; // Accessible (protected member of Base)

protectedMember = 20; // Accessible (protected member of Base)

// privateMember = 30; // Not accessible (private member of Base)

publicFunction(); // Accessible (protected function of Base)

protectedFunction(); // Accessible (protected function of Base)

// privateFunction(); // Not accessible (private function of Base)

};
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() {

// Accessible in derived class

protected:

int protectedMember;

void protectedFunction() {

// Accessible in derived class

private:

int privateMember;

void privateFunction() {

// Not accessible in derived class

};

class Derived : private Base {

public:

void example() {

publicMember = 10; // Accessible (private member of Base)

protectedMember = 20; // Accessible (private member of Base)

// privateMember = 30; // Not accessible (private member of Base)

publicFunction(); // Accessible (private function of Base)

protectedFunction(); // Accessible (private function of Base)

// privateFunction(); // Not accessible (private function of Base)

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

Characteristics of Friend Functions:

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.

Key points to remember about virtual base classes :

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

Here are some key points about reference variables in C++ :

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

The key components related to handling exceptions in C++ are :

(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>

// A function that throws an exception

double divide(double numerator, double denominator) {

if (denominator == 0)

throw std::string("Error: Division by zero!");

return numerator / denominator;

int main() {

double num1, num2;

std::cout << "Enter two numbers: ";

std::cin >> num1 >> num2;

try {

double result = divide(num1, num2);

std::cout << "Result of division: " << result << std::endl;

catch (std::string& errorMsg) {

std::cerr << "Exception caught: " << errorMsg << std::endl;

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.

Call Stack and Recursion:

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

Ques: How we done file handling in c++?

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 the necessary header file:

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

For reading from a file (input):

std::ifstream inputFile;

inputFile.open("filename.txt");
For writing to a file (output):

std::ofstream outputFile;

outputFile.open("filename.txt");

For reading and writing to a file (both input and output):


std::fstream file;

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()) {

// File is open, perform read operations.

} else {

// Failed to open the file, handle the error.

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;

inputFile >> number; // Read an integer from the file

std::string line;

std::getline(inputFile, line); // Read a line from the file

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 << "Another line." << std::endl;

outputFile.close();

std::cout << "File write operation successful." << std::endl;

} else {

std::cerr << "Failed to open the output file." << std::endl;

std::ifstream inputFile;

inputFile.open("output.txt");

if (inputFile.is_open()) {

std::string line;

while (std::getline(inputFile, line)) {

std::cout << line << std::endl;

inputFile.close();

std::cout << "File read operation successful." << std::endl;

} else {

std::cerr << "Failed to open the input file." << std::endl;

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:

MyNumber(int num) : value(num) {}

MyNumber operator+(const MyNumber& other) const {

return MyNumber(value + other.value);

int getValue() const {

return value;

};

int main() {

MyNumber num1(5);

MyNumber num2(10);

MyNumber sum = num1 + num2;

std::cout << "Sum: " << sum.getValue() << std::endl;

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:

MyNumber(int num) : value(num) {}

friend MyNumber operator+(const MyNumber& lhs, const MyNumber& rhs);

int getValue() const {

return value;

};

MyNumber operator+(const MyNumber& lhs, const MyNumber& rhs) {

return MyNumber(lhs.value + rhs.value);

int main() {

MyNumber num1(5);

MyNumber num2(10);

MyNumber sum = num1 + num2;

std::cout << "Sum: " << sum.getValue() << std::endl;

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.

Both implementations of operator overloading will yield the same output:

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.

You might also like