Unit 1 OOP

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

SRES’s

SHREE RAMCHANDRA COLLEGE OF ENGINEERING


Lonikand, Pune – 412216
Department of Artificial Intelligence & Data Science

Unit 1 – Fundamentals of Object Oriented Programming


1. What are advantages of object-oriented programming over procedural oriented
programming? [SPPU Oct 2023, Marks:4]
Ans :
Object-Oriented Programming (OOP) and Procedural Programming are two of the most
common programming paradigms used today. While both paradigms have their strengths and
weaknesses, OOP has gained popularity in recent years due to its modular, flexible and scalable
approach to programming.
Following are the benefits of using OOP over Procedural Programming.
1. Modularity and Reusability:
One of the key advantages of OOPs over Procedural Programming is the concept of
modularity and reusability. In OOPs, code is organized into modular objects, each
encapsulating its data and behaviour.
This promotes code reusability, as objects can be easily reused in different parts of the
application or even in other projects.
In contrast, Procedural Programming often relies on writing functions that operate on
global data, which can lead to code duplication and lack of modular structure.
2. Encapsulation and Data Hiding:
Encapsulation is another fundamental principle of OOPs that enables data hiding and
abstraction.
By encapsulating data within objects and exposing only necessary interfaces, OOPs
provides better control over data access and manipulation. This enhances security and
minimizes the chances of data corruption or accidental modifications.
In Procedural Programming, data is typically exposed globally, making it more
vulnerable to unauthorized access and modification.
3. Inheritance and Code Reuse:
Inheritance is a powerful feature of OOPs that allows the creation of hierarchical
relationships between classes. This promotes code reuse and facilitates the creation of
specialized classes (subclasses) based on existing ones (superclasses). In Procedural
Programming, code reuse often requires duplicating or rewriting similar procedures, leading
to increased development time and potential maintenance issues.

SE AI & DS 2024 SRCOE Prof. Ashvini Swami 1


Object Oriented Programming Unit 1 – Fundamentals of OOP

4. Polymorphism and Flexibility:


Polymorphism, a core concept in OOPs, allows objects of different classes to be treated
as instances of a common superclass. This enables flexible and dynamic behaviour, where
different objects can respond differently to the same method invocation.
Procedural Programming lacks this inherent flexibility, as functions operate on fixed
data types and may require multiple function overloads to handle different scenarios.
5. Code Maintainability and Readability:
The object-oriented paradigm promotes clean and organized code structure, making it
easier to understand, modify, and maintain software systems.
With OOPs, developers can encapsulate complex logic within objects, improving code
readability and reducing the likelihood of introducing bugs. Procedural code, on the other
hand, tends to be more linear and less organized, making it challenging to comprehend and
modify as projects grow in size and complexity.
6. Scalability and Collaboration:
OOPs supports modular development, enabling teams of developers to work on different
modules simultaneously without conflicts. OOP has well-defined interfaces and
encapsulation, changes to one module have minimal impact on other parts of the system.
Procedural Programming, especially in large codebases, often lacks the scalability and
collaboration benefits offered by OOPs.
7. Software Development Productivity :
By leveraging the advantages mentioned above, OOPs boosts software development
productivity. The reusability of code, modular structure, and encapsulation reduce
development time and effort.
Additionally, the inherent organization and readability of object-oriented code facilitate
teamwork and collaboration, further enhancing productivity.

2. What is polymorphism? How does it relate to function overloading?


[SPPU Oct 2023, Marks:5]
Ans.
The word “polymorphism” means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A real-life
example of polymorphism is a person who at the same time can have different characteristics. A
man at the same time is a father, a husband, and an employee. So the same person exhibits
different behavior in different situations. This is called polymorphism. Polymorphism is

SE AI & DS 2024 SRCOE Prof. Ashvini Swami 1


Object Oriented Programming Unit 1 – Fundamentals of OOP

considered one of the important features of Object-Oriented Programming.


Polymorphism allows a single method to work with an arbitrary, unknown type, while
overloading allows one of multiple methods to be selected by examining the types of the
parameters. With overloading, the parameter types become part of the name of the method. With
polymorphism, the parameter types might not be known.
Function Overloading :
When there are multiple functions with the same name but different parameters, then the
functions are said to be overloaded, hence this is known as Function Overloading. Functions can
be overloaded by changing the number of arguments or/and changing the type of arguments. In
simple terms, it is a feature of object-oriented programming providing many functions that have
the same name but distinct parameters when numerous tasks are listed under one function name.

3. Write a class ''Student'' with attributes like name, roll number & mark. Include member
functions to set & display these attributes? [SPPU Oct 2023, Marks:6]
Ans :
// C++ program to create student class, read and print student's details
#include <iostream>
using namespace std;
class student {
private:
char name[30];
int rollNo;
float perc;
public:
//member function to get student's details
void setDetails();
//member function to print student's details
void putDetails();
};
//member function definition, outside of the class
void student::setDetails()
{
cout << "Enter name: ";
cin >> name;
cout << "Enter roll number: ";
cin >> rollNo;
cout << "Enter Percentage marks : ";
cin >> perc;
}

//member function definition, outside of the class


void student::putDetails()
{
cout << "Student details:\n";
SE AI & DS 2024 SRCOE Prof. Ashvini Swami 2
Object Oriented Programming Unit 1 – Fundamentals of OOP

cout << "\n Name:" << name << "\n Roll Number:" << rollNo << "\n Percentage:" <<
perc;
}
int main()
{
student std; // objects creation
cout << "Enter details of student \n";
std.setDetails();
cout << endl;
cout << "Details of student \n";
std.putDetails();
return 0;
}
Output of above program will be as follows:
Output :
Enter details of student
Enter name: Mike
Enter roll number: 101
Enter Percentage marks : 9.1

Details of student
Student details:
Name:Mike
Roll Number:101
Percentage:9.1

4. State differences between abstraction and encapsulation. [SPPU Oct 2023, Marks:4]
Ans :
Abstraction is defined as a process of hiding the implementation details of a system from
the user. Thus, by using abstraction, we provided only the functionality of the system to the user.
Consequently, the user will have information on what the system does, but not on how the system
does it.
Encapsulation is one of the fundamental OOP concepts. Encapsulation is defined as a method
by which data wrapping is done into a single unit. It is used in wrapping up the data and the code
acting on the data together as a single unit.
In encapsulation, the variables of a class are hidden from other classes, and can be accessed
only by methods of the current class. Therefore, encapsulation is also called data hiding.
Encapsulation is implemented using access modifiers like public, private and protected.
Difference between Abstraction and Encapsulation
The following table highlights all the important differences between abstraction and
encapsulation –

SE AI & DS 2024 SRCOE Prof. Ashvini Swami 3


Object Oriented Programming Unit 1 – Fundamentals of OOP

Sr. Abstraction Encapsulation


No.

It is the process of gaining information. It is a method that helps wrap up data into a single
1.
module.

2. The problems in this technique are solved Problems in encapsulation are solved at the
at the interface level. implementation level.

It helps hide the unwanted It helps hide data using a single entity, or using a
3. details/information. unit with the help of method that helps protect the
information.

It can be implemented using abstract It can be implemented using access modifiers like
4.
classes and interfaces. public, private and protected.

The complexities of the implementation are The data is hidden using methods such as getters
5.
hidden using interface and abstract class. and setters.

Abstraction can be performed using objects Objects in encapsulation don't need to be in


6. that are encapsulated within a single abstraction.
module.

5. What are C++ access specifiers? Write down their significance. [SPPU Oct 2023, Marks:5]
Ans :
Access modifiers are used to implement an important aspect of Object-Oriented
Programming known as Data Hiding. Access Modifiers or Access Specifiers in a class are used
to assign the accessibility to the class members, i.e., they set some restrictions on the class
members so that they can’t be directly accessed by the outside functions.
There are 3 types of access modifiers available in C++:
Public
Private
Protected
If we do not specify any access modifiers for the members inside the class, then by default
the access modifier for the members will be Private.
Public: All the class members declared under the public specifier will be available to
everyone. The data members and member functions declared as public can be accessed by
other classes and functions too. The public members of a class can be accessed from anywhere
in the program using the direct member access operator (.) with the object of that class.

SE AI & DS 2024 SRCOE Prof. Ashvini Swami 4


Object Oriented Programming Unit 1 – Fundamentals of OOP

Private: The class members declared as private can be accessed only by the member
functions inside the class. They are not allowed to be accessed directly by any object or
function outside the class. Only the member functions or the friend functions are allowed to
access the private data members of the class.

Protected: The protected access modifier is similar to the private access modifier in the sense
that it can’t be accessed outside of its class unless with the help of a friend class. The
difference is that the class members declared as Protected can be accessed by any subclass
(derived class) of that class as well.
Access Modifiers or Access Specifiers in a class are used to assign the accessibility to
the class members, i.e., they set some restrictions on the class members so that they can't be
directly accessed by the outside functions.

6. Write a class ''Calculator'' with methods for addition, subtraction, multiplication and
division functions. Create a object to perform arithmetic operation.
[SPPU Oct 2023, Marks:5]
Ans :
// C++ program to implement the class ''Calculator'' with methods for addition, subtraction,
// multiplication and division functions.
#include <iostream>
#include <math.h>
using namespace std;
// Class calculator
class Calculator
{
float a, b;
public:
// Function to take input from user
void result()
{
cout << "Enter First Number: ";
cin >> a;
cout << "Enter Second Number: ";
cin >> b;
}
// Function to add two numbers
float add()
{
return a + b;
}
// Function to subtract two numbers
float sub()

SE AI & DS 2024 SRCOE Prof. Ashvini Swami 5


Object Oriented Programming Unit 1 – Fundamentals of OOP

{
return a - b;
}
// Function to multiply two numbers
float mul()
{
return a * b;
}
// Function to divide two numbers
float div()
{
if (b == 0)
{
cout << "Division By Zero" << endl;
return INFINITY;
}
else
{
return a / b;
}
}
};
// Driver code
int main()
{
int ch;
Calculator c;
cout << "Enter 1 to Add 2 Numbers" <<
"\nEnter 2 to Subtract 2 Numbers" <<
"\nEnter 3 to Multiply 2 Numbers" <<
"\nEnter 4 to Divide 2 Numbers" <<
"\nEnter 0 To Exit";
do
{
cout << "\nEnter Choice: ";
cin >> ch;
switch (ch)
{
case 1:

// result function invoked


c.result(); // add function to calculate sum
cout << "Result: " << c.add() << endl;
break;
case 2:
// sub function to calculate difference
c.result();
cout << "Result: " << c.sub() << endl;
break;
case 3:
c.result();
SE AI & DS 2024 SRCOE Prof. Ashvini Swami 6
Object Oriented Programming Unit 1 – Fundamentals of OOP

// mul function to calculate product


cout << "Result: " << c.mul() << endl;
break;
case 4:
c.result();

// div function to calculate division


cout << "Result: " << c.div() << endl;
break;
}

} while (ch >= 1 && ch <= 4);


return 0;
}

7. What is the use of ‘this’ pointer. Explain with Example. [SPPU Oct 2022, Marks:4]
Ans :
When a member function is called, it is automatically passed an implicit argument that is
a pointer to the invoking object (i.e. the object on which the function is invoked). This pointer
is known as 'this' pointer. It is internally created at the time of function call.
In C++ programming, this is a keyword that refers to the current instance of the class. There can
be 3 main usage of this keyword in C++.
o It can be used to pass current object as a parameter to another method.
o It can be used to refer current class instance variable.
o It can be used to declare indexers.

this Pointer Example


#include <iostream>
using namespace std;
class Employee
{
public:
int id; //data member (also instance variable)
string name; //data member (also instance variable)
float salary;
Employee (int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{

SE AI & DS 2024 SRCOE Prof. Ashvini Swami 7


Object Oriented Programming Unit 1 – Fundamentals of OOP

cout<<id<<" "<<name<<" "<<salary<<endl;


}
};
int main(void)
{
Employee e1 =Employee (101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee (102, "Nakul", 59000); //creating an object of Employee
e1.display ();
e2.display ();
return 0;
}

Output:
101 Sonoo 890000
102 Nakul 59000

8. What are the different ways to define member functions of a class? Give Examples of Each.
[SPPU Oct 2022, Marks:4]
Class Member Functions:
A class member function is a function that, like any other variable, is defined or prototyped
within the class declaration. It has access to all the members of the class and can operate on any
object of that class.

Let us use a member function to access the members of a previously created class instead of
directly accessing them.
class Dice {
public:
double L; // a dice's length
double B; // a dice's breadth
double H; // a dice's height
double getVolume(void); // Returns dice volume
};
Member functions can be defined either within the class definition or separately with the scope
resolution operator, :: Even if the inline specifier is not used, specifying a member function
within the class declaration declares the function inline. So, you may either define the Volume()
function as shown below.
class Dice {
public:
SE AI & DS 2024 SRCOE Prof. Ashvini Swami 8
Object Oriented Programming Unit 1 – Fundamentals of OOP

double L; // a dice's length


double B; // a dice's breadth
double H; // a dice's height
double getVolume(void) {
return L * B * H;
}
};
If we want, we may define the identical function outside of the class using the scope resolution
operator (::), as seen below.
double Dice :: getVolume (void) {
return L * B * H;
}
The main thing to remember here is that we must use the class name exactly before the ::
operator. The dot operator (.) will be used to perform a member function on an object and will
only manipulate data relevant to that object as follows:
Dice myDice; // Generate an object
myDice.getVolume(); // Call the object's member function
9. Define inline function. Write a C++program for finding the area of a triangle using inline
functions. [SPPU Oct 2022, Marks:7]

Ans :
The main use of the inline function in C++ is to save memory space. Whenever the function
is called, then it takes a lot of time to execute the tasks, such as moving to the calling function.
If the length of the function is small, then the substantial amount of execution time is spent in
such overheads, and sometimes time taken required for moving to the calling function will be
greater than the time taken required to execute that function.
The solution to this problem is to use macro definitions known as macros. The preprocessor
macros are widely used in C, but the major drawback with the macros is that these are not normal
functions which means the error checking process will not be done during the compilation.
C++ has provided one solution to this problem. In the case of function calling, the time for
calling such small functions is huge, so to overcome such a problem, a new concept was
introduced known as an inline function. When the function is encountered inside the main ()
method, it is expanded with its definition thus saving time.
// calculate an area of triangle using the inline function

SE AI & DS 2024 SRCOE Prof. Ashvini Swami 9


Object Oriented Programming Unit 1 – Fundamentals of OOP

#include <iostream>
using namespace std;
// inline function, no need prototype
inline float triangle_area (float base, float height)
{
float area;
area = (0.5 * base * height);
return area;
}

int main(void)
{
float b, h, a;
b = 4;
h = 6;
// compiler will substitute the inline function code here.
a = triangle_area (b, h);
cout<<"Area = (0.5*base*height)"<<endl;
cout<<"where, base = 4, height = 6"<<endl;
cout<<"\nArea = "<<a<<endl;
return 0;
}

Output example:
Area = (0.5*base*height)
where, base = 4, height = 6
Area = 12

10. Compare Procedure oriented programming Vs Object oriented programming


[SPPU Oct 2022, Marks:4]
Ans :
Object-oriented programming and procedural programming both are used to develop the
applications. Both of them are high-level programming languages.
Procedural Programming :
It is defined as a programming language derived from the structure programming and
based on calling procedures. The procedures are the functions, routines, or subroutines that
consist of the computational steps required to be carried. It follows a step-by-step approach
in order to break down a task into a set of variables and routines via a sequence of instructions.
Object-oriented programming :
Object-oriented programming is a computer programming design philosophy or
methodology that organizes/ models software design around data or objects rather than
functions and logic. It includes two words, "object" and "oriented". In a dictionary object is

SE AI & DS 2024 SRCOE Prof. Ashvini Swami 10


Object Oriented Programming Unit 1 – Fundamentals of OOP

an article or entity that exists in the real world. The meaning of oriented is interested in a
particular kind of thing or entity. In layman's terms, it is a programming pattern that rounds
around an object or entity.

Sr. On the Procedural Programming Object-oriented programming


No. basis of

1. Definition It is a programming language that is Object-oriented programming is a


derived from structure programming computer programming design
and based upon the concept of calling philosophy or methodology that
procedures. It follows a step-by-step organizes/ models software design
approach in order to break down a around data or objects rather than
task into a set of variables and functions and logic.
routines via a sequence of
instructions.

2. Security It is less secure than OOPs. Data hiding is possible in object-


oriented programming due to
abstraction. So, it is more secure
than procedural programming.

3. Approach It follows a top-down approach. It follows a bottom-up approach.

4. Data In procedural programming, data In OOP, objects can move and


movement moves freely within the system from communicate with each other via
one function to another. member functions.

5. Orientation It is structure/procedure-oriented. It is object-oriented.

6. Access There are no access modifiers in The access modifiers in OOP are
modifiers procedural programming. named as private, public, and
protected.

7. Inheritance Procedural programming does not There is a feature of inheritance in


have the concept of inheritance. object-oriented programming.

8. Code There is no code reusability present in It offers code reusability by using


reusability procedural programming. the feature of inheritance.

9. Overloading Overloading is not possible in In OOP, there is a concept of


procedural programming. function overloading and operator
overloading.

10. Importance It gives importance to functions over It gives importance to data over
data. functions.

11. Virtual class In procedural programming, there are In OOP, there is an appearance of
no virtual classes. virtual classes in inheritance.

12. Complex It is not appropriate for complex It is appropriate for complex


problems problems. problems.

SE AI & DS 2024 SRCOE Prof. Ashvini Swami 11


Object Oriented Programming Unit 1 – Fundamentals of OOP

13. Data hiding There is not any proper way for data There is a possibility of data
hiding. hiding.

14. Program In Procedural programming, a In OOP, a program is divided into


division program is divided into small small parts that are referred to as
programs that are referred to as objects.
functions.

15. Examples Examples of Procedural The examples of object-oriented


programming include C, Fortran, programming are -
Pascal, and VB. .NET, C#, Python, Java, VB.NET,
and C++.

11. What is difference between pointer and references? [SPPU Oct 2022, Marks:4]
Ans :
Reference :
A reference is a variable that is referred to as another name for an already existing
variable. The reference of a variable is created by storing the address of another variable.
A reference variable can be considered as a constant pointer with automatic indirection.
Here, automatic indirection means that the compiler automatically applies the indirection
operator (*).
Example of reference:
int &a = i;
In the above declaration, 'a' is an alias name for 'i' variable. We can also refer to the 'i' variable
through 'a' variable also.

Pointer :
A pointer is a variable that contains the address of another variable. It can be
dereferenced with the help of (*) operator to access the memory location to which the pointer
points.
Difference between References and Pointers in C++

References Pointers

The variable cannot be The variable can be


Reassignment
reassigned in Reference. reassigned in Pointers.

It shares the same address as Pointers have their own


Memory Address
the original variable. memory address.

SE AI & DS 2024 SRCOE Prof. Ashvini Swami 12


Object Oriented Programming Unit 1 – Fundamentals of OOP

References Pointers

It is referring to another It is storing the address of the


Work
variable. variable.

It can have value assigned as


Null Value It does not have null value.
null.

The pointer does it work by


This variable is referenced by
Arguments the method known as pass by
the method pass by value.
reference.

12. Write C++ code that defines a class and declares and array of objects to that class
[SPPU Oct 2022, Marks:7]
Ans :
When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, you need to
create objects.
Syntax:
ClassName ObjectName[number of objects];
The Array of Objects stores objects. An array of a class type is also known as an array of
objects.
// C++ program to implement the array of objects

#include<iostream>
using namespace std;

class Employee
{
int id;
char name[30];
public:

// Declaration of function
void getdata();

// Declaration of function
void putdata();
};

// Defining the function outside the class


void Employee::getdata()
{

SE AI & DS 2024 SRCOE Prof. Ashvini Swami 13


Object Oriented Programming Unit 1 – Fundamentals of OOP

cout << "Enter Id : ";


cin >> id;
cout << "Enter Name : ";
cin >> name;
}

// Defining the function outside the class


void Employee::putdata()
{
cout << id << " ";
cout << name << " ";
cout << endl;
}

// Driver code
int main()
{
// This is an array of objects having
// maximum limit of 30 Employees
Employee emp[30];
int n, i;
cout << "Enter Number of Employees - ";
cin >> n;

// Accessing the function


for(i = 0; i < n; i++)
emp[i].getdata();

cout << "Employee Data - " << endl;

// Accessing the function


for(i = 0; i < n; i++)
emp[i].putdata();
}

Output :

Enter Number of Employees - 2


Enter Id : 1
Enter Name : Ram
Enter Id : 2
Enter Name : Shyam
Employee Data -
1 Ram
2 Shyam

SE AI & DS 2024 SRCOE Prof. Ashvini Swami 14

You might also like