0% found this document useful (0 votes)
6 views16 pages

Object Oriented Programming & C++-Assignment-

Uploaded by

Venkatesh Venkat
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
6 views16 pages

Object Oriented Programming & C++-Assignment-

Uploaded by

Venkatesh Venkat
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 16

Internal Assessments

Program – MBA
Subject - Object Oriented Programming C++

1. What is the difference between procedural programming and


object-oriented programming?

The primary difference between procedural programming (PP) and object-oriented


programming (OOP) lies in their approach to organizing and structuring code. While
procedural programming focuses on procedures (functions) to perform tasks, object-
oriented programming centers around objects that combine data and behavior.
Below is a detailed comparison of the two paradigms:

1. Fundamental Concept
Procedural Programming

 Procedural programming is a programming paradigm based on the concept of


functions, which are sequences of instructions grouped together to perform
specific tasks.
 The emphasis is on the procedure (or function) that operates on data.
 Programs are typically structured as a series of steps or instructions to be
executed sequentially.

Object-Oriented Programming

 OOP is based on the concept of objects, which are instances of classes that
encapsulate both data (attributes) and methods (functions).
 The focus is on defining and manipulating objects, making the program
modular and reusable.
 OOP emphasizes abstraction, encapsulation, inheritance, and polymorphism
to model real-world entities.

2. Structure and Organization


Procedural Programming

 Programs are divided into functions or procedures, each of which performs a


specific operation.
 Functions are typically global, and data is passed between them.
 Example (C-style procedural code):

int add(int a, int b) {


return a + b;
}
int main() {
int result = add(3, 5);
printf("Result: %d", result);
return 0;
}

Object-Oriented Programming

 Programs are divided into classes, which define the structure and behavior of
objects.
 Functions (methods) are tied to objects and operate on the data contained
within those objects.
 Example (OOP-style code in Python):

class Calculator:
def add(self, a, b):
return a + b

calc = Calculator()
result = calc.add(3, 5)
print("Result:", result)

3. Data Handling
Procedural Programming

 Data and functions are separate.


 Data is often shared across functions using global variables, which can lead to
issues like accidental modification and difficulty in debugging.
 There is less emphasis on data security or encapsulation.

Object-Oriented Programming

 Data and methods are encapsulated within objects.


 Access to data is controlled through access modifiers (e.g., private, public,
protected).
 Encapsulation ensures that data is secure and modifications are controlled.

4. Reusability and Modularity


Procedural Programming

 Functions can be reused, but the overall structure is less modular.


 Code reuse requires copying and modifying functions, which can lead to
redundancy.

Object-Oriented Programming

 Classes and objects promote modularity and reusability.


 Inheritance allows new classes to inherit properties and methods from
existing ones, reducing code duplication.
 Polymorphism enables using the same interface for different
implementations.

5. Scalability and Maintenance


Procedural Programming

 Suitable for small to medium-sized programs but becomes difficult to manage


as program complexity grows.
 Debugging and maintaining procedural code can be challenging due to the
lack of structure and modularity.

Object-Oriented Programming

 Highly scalable, making it suitable for large and complex applications.


 OOP’s modular structure makes it easier to maintain, update, and debug
code.

6. Real-World Problem Modeling


Procedural Programming

 Less effective at modeling real-world scenarios because it does not naturally


align with the way objects and behaviors interact in the real world.
 Example: Modeling a "car" requires separate procedures for "start," "stop,"
and "accelerate."

Object-Oriented Programming

 Excels at modeling real-world problems by representing entities as objects


with attributes and behaviors.
 Example: A "Car" class can encapsulate properties like speed and methods
like start() and stop().

7. Execution Flow
Procedural Programming

 Follows a top-down execution flow where instructions are executed in


sequence unless altered by loops, conditionals, or function calls.
 The focus is on how to perform a task (step-by-step instructions).

Object-Oriented Programming

 Focuses on defining the objects and their interactions rather than the flow of
execution.
 Execution often involves invoking methods on objects and managing
interactions between them.
8. Use Cases
Procedural Programming

 Commonly used for applications where tasks can be broken into smaller,
independent functions.
 Examples: System-level programming, embedded systems, and simple utility
programs.
Object-Oriented Programming

 Ideal for applications requiring complex interactions and scalability.


 Examples: GUI applications, game development, and enterprise-level
software systems.

9. Examples of Languages
Procedural Programming

 Examples: C, Pascal, Fortran, and early versions of BASIC.


 Even modern languages like Python and Java support procedural
programming but are better suited for OOP.

Object-Oriented Programming

 Examples: Java, Python, C++, Ruby, C#, and Swift.

10. Advantages and Disadvantages


Procedural Programming

 Advantages: Simple, easy to learn, and works well for straightforward tasks.
 Disadvantages: Poor scalability, lack of modularity, and harder maintenance
for large systems.

Object-Oriented Programming

 Advantages: Better scalability, reusability, and alignment with real-world


problem-solving.
 Disadvantages: Steeper learning curve and may introduce unnecessary
complexity for simple programs.

Conclusion

Procedural programming and object-oriented programming are two distinct


paradigms suited for different purposes. Procedural programming is straightforward
and works well for simple tasks, while object-oriented programming excels in
modularity, scalability, and modeling complex systems. Understanding their
differences helps developers choose the right paradigm for their specific project
needs.
2. What do you mean by object modelling technique?
Object Modeling Technique (OMT) is a methodology for analyzing, designing, and modeling
systems based on objects. It was developed by James Rumbaugh and his colleagues as a
structured approach to object-oriented design, providing a framework to represent the real-
world entities of a system and their interactions. OMT is widely used in software engineering
and is considered a precursor to the Unified Modeling Language (UML). Below is a detailed
explanation of the Object Modeling Technique:

1. Definition of Object Modeling Technique

OMT is a graphical modeling approach used to develop object-oriented systems. It


emphasizes representing a system as a collection of objects, where each object encapsulates
both data (attributes) and behavior (methods). These objects interact with one another to
achieve the desired functionality.
OMT uses three interrelated models to represent a system comprehensively:

1. Object Model: Focuses on the static structure of the system.


2. Dynamic Model: Captures the behavior of the system over time.
3. Functional Model: Represents the data flow and processes in the system.

2. Key Components of OMT


Object Model

The object model is the cornerstone of OMT. It describes the static, structural aspects of a
system, including:
 Objects: Represent entities in the system. Each object has attributes and operations
(methods).
 Classes: Define the blueprint for objects, specifying attributes and methods that all
objects of the class share.
 Relationships: Show how objects interact with one another, including associations,
aggregations, and generalizations (inheritance).
 Example: In a Library Management System:
o Objects: Book, Member, Librarian.
o Classes: Book class with attributes like Title, Author, and methods like
CheckAvailability().
o Relationships: A Member borrows a Book.
OMT uses diagrams similar to class diagrams in UML to represent the object model.

Dynamic Model

The dynamic model focuses on the time-dependent behavior of objects. It defines how
objects interact over time and react to events. The dynamic model includes:
 State Diagrams: Show the states an object can be in and transitions triggered by
events.
 Events: External or internal stimuli that cause state changes.
 States: Conditions of an object at a particular time.
 Example: In the Library Management System:
o States for a Book object: Available, Borrowed, Reserved.
o Events: Borrow, Return.
State diagrams provide a visual representation of an object’s lifecycle.

Functional Model

The functional model describes the flow of data and the transformation of inputs into
outputs within a system. It focuses on:
 Processes: Operations that transform data.
 Data Flow: How data moves through the system.
 Data Stores: Where data is stored within the system.
This model often uses data flow diagrams (DFDs) to depict how information is processed
and transferred.

 Example: In the Library Management System:


o Process: A member searches for a book.
o Data Flow: Search query → System → Search results.

3. Steps in Object Modeling Technique

OMT involves four key phases:


1. Analysis:
o Identify the objects, classes, and their relationships.
o Create the object, dynamic, and functional models.
2. System Design:
o Define the overall system architecture, including subsystem decomposition,
hardware, and software mapping.
3. Object Design:
o Refine the models created during the analysis phase.
o Specify detailed class definitions, including attributes, methods, and
relationships.
4. Implementation:
o Translate the design into code using an object-oriented programming
language (e.g., Java, C++).
o Ensure that the code aligns with the object, dynamic, and functional models.

4. Benefits of Object Modeling Technique

1. Real-World Representation: OMT provides a natural way to model systems by


aligning closely with real-world entities and their interactions.
2. Modularity and Reusability: By encapsulating data and behavior within objects,
OMT promotes modularity and facilitates code reuse.
3. Comprehensive Analysis: The integration of object, dynamic, and functional models
ensures a holistic understanding of the system.
4. Improved Communication: Graphical representations make it easier for
stakeholders, including developers, designers, and clients, to understand the system.
5. Foundation for Object-Oriented Programming: OMT directly supports object-
oriented programming, bridging the gap between analysis, design, and
implementation.

5. Applications of OMT
 Software Development: Designing applications like e-commerce platforms,
inventory systems, and ERP solutions.
 System Engineering: Modeling embedded systems and hardware/software
integration.
 Database Design: Structuring data models for relational or object-oriented
databases.

6. Limitations of Object Modeling Technique

1. Complexity for Large Systems:


o The interrelation of object, dynamic, and functional models can become
challenging for large-scale projects.
2. Requires Expertise:
o Effective use of OMT demands a solid understanding of object-oriented
principles and modeling techniques.
3. Limited by Tools:
o OMT predates modern tools and languages, so it may require adaptation for
contemporary software development practices.

Conclusion

The Object Modeling Technique is a powerful approach to designing object-oriented


systems. By integrating the object, dynamic, and functional perspectives, OMT provides a
comprehensive framework for understanding and building complex systems. Its emphasis on
real-world representation, modularity, and reusability makes it a cornerstone of modern
software engineering practices, especially for projects requiring object-oriented
methodologies. Despite its limitations, OMT remains a foundational tool for system
designers and developers.

3.What are the steps to analyze and design an object-oriented system?


Analyzing and designing an object-oriented system involves a systematic process that
focuses on understanding the problem domain, defining its objects, and developing a model
that reflects real-world scenarios. The process ensures the system is modular, scalable, and
easier to maintain. Below are the key steps in analyzing and designing an object-oriented
system:

1. Requirement Analysis

The first step is to thoroughly understand the problem domain and gather detailed
requirements.

 Understand Objectives: Identify the purpose of the system and the problems it
seeks to solve.
 Gather Requirements: Collaborate with stakeholders to document functional and
non-functional requirements.
 Identify Constraints: Note any technical, business, or regulatory limitations that may
affect the design.

Example:
For a library management system, requirements may include tracking books, issuing books,
and managing member information.

2. System Conceptualization

Develop a high-level understanding of the system by identifying key elements.


 Define Use Cases: Describe the interactions between the users (actors) and the
system to fulfill specific tasks.
 Create Use Case Diagrams: Visualize how different actors interact with the system
and what functionality it provides.

Example:
A member borrowing a book would be a use case in the library system.

3. Identify Classes and Objects

The core of object-oriented design is identifying the entities (objects) and their classifications
(classes).
 Find Key Objects: Analyze the use cases to identify nouns (e.g., Book, Member,
Librarian) as potential objects.
 Define Classes: Group similar objects into classes and identify their attributes and
methods.
 Establish Relationships: Define how objects are related (e.g., associations,
aggregations, and inheritance).

Example:
 Class: Book
o Attributes: Title, Author, ISBN.
o Methods: Borrow(), Return().

4. Develop Static Structure

Create a static model of the system’s structure using class diagrams.


 Class Diagrams: Represent classes, their attributes, methods, and relationships
(inheritance, composition, or association).
 Encapsulation: Ensure data is protected by defining appropriate access modifiers
(public, private, protected).

Example:
In the library system, the Member class may have a relationship with the Book class to
represent borrowing.

5. Model Dynamic Behavior

Focus on how the system behaves over time and in response to events.
 State Diagrams: Model the lifecycle of objects, including their states and transitions
triggered by events.
 Sequence Diagrams: Show the interactions between objects over time to
accomplish specific tasks.
 Activity Diagrams: Represent workflows or processes within the system.
Example:
For the Book object, states might include Available, Issued, and Reserved.

6. Functional Modeling

Define how data flows through the system and how it is processed.
 Data Flow Diagrams: Show how inputs are transformed into outputs through
processes.
 Object Interactions: Highlight how objects collaborate to perform operations.

Example:
When a member searches for a book, the system processes the query and returns the
results.

7. System Design

Translate the analysis models into a blueprint for implementation.


 Define Architecture: Decide on system components, such as databases, application
layers, and APIs.
 Design Interfaces: Specify how objects will interact and communicate, including
input/output interfaces.
 Plan Persistence: Design the database schema or object storage for data
management.

8. Implementation Planning

Prepare for coding by selecting appropriate tools and languages.


 Choose a Programming Language: Use object-oriented languages like Java, Python,
or C#.
 Refine Models: Adjust models to accommodate technical constraints and
implementation details.

9. Validation and Testing

Ensure the design meets requirements and performs as expected.


 Review Models: Verify consistency and completeness of class, dynamic, and
functional models.
 Prototype Development: Create prototypes to validate critical parts of the system.
 Test Cases: Develop test cases for unit testing, integration testing, and system
testing.

10. Iteration and Refinement

Object-oriented design is an iterative process. After testing and validation, refine the models
and design based on feedback.
 Incorporate stakeholder feedback.
 Optimize classes, methods, or workflows for better performance and usability.

Conclusion

Analyzing and designing an object-oriented system is a structured process that starts with
understanding requirements and ends with creating a blueprint for implementation. By
following these steps, developers ensure the system is modular, maintainable, and aligned
with user needs. This process supports scalability and allows for effective handling of
complex systems.

4.What is the syntax for closing a file?


In programming, closing a file after performing file operations (like reading or writing) is
crucial to ensure that system resources are freed, changes are saved properly, and file locks
are released. The syntax for closing a file varies slightly depending on the programming
language being used. Below, we will explain how file closure is handled in several popular
programming languages.

1. Python

In Python, file operations are performed using the built-in open() function, and the file is
closed using the close() method.

Syntax:
file = open("filename.txt", "r") # Open the file in read mode
# Perform file operations here
file.close() # Close the file

Explanation:
 The open() function opens a file and returns a file object.
 After file operations, the close() method is called to release the resources.

Alternatively, Python provides a context manager (with statement), which automatically


closes the file when the block of code inside the with statement is executed, even if an error
occurs.
with open("filename.txt", "r") as file:
# Perform file operations
# File is automatically closed after the block execution

2. C
In C, the fopen() function is used to open a file, and the fclose() function is used to close it.

Syntax:
FILE *file = fopen("filename.txt", "r"); // Open the file
if (file != NULL) {
// Perform file operations
fclose(file); // Close the file
}

Explanation:
 fopen() opens the file and returns a file pointer (FILE *).
 fclose() is used to close the file and free associated resources.
 It's good practice to check if fopen() returned NULL, indicating an error opening the
file, before attempting to close it.

3. Java
In Java, file operations are performed using classes from the java.io package, such as
FileReader or BufferedReader, and the close() method is used to close the file stream.

Syntax:
import java.io.FileReader;
import java.io.IOException;

FileReader file = new FileReader("filename.txt");


try {
// Perform file operations
} finally {
file.close(); // Close the file
}
Explanation:
 FileReader opens the file and returns a file object.
 The close() method is called in the finally block to ensure that the file is closed even
if an exception is thrown.
Java also provides the try-with-resources statement (available in Java 7 and later), which
automatically closes resources like files when they are no longer needed.

try (FileReader file = new FileReader("filename.txt")) {


// Perform file operations
}
// No need to explicitly call file.close() here

4. C++
In C++, file operations are typically handled through the fstream library, and the close()
method of the fstream object is used to close the file.

Syntax:
#include <fstream>

std::ifstream file("filename.txt"); // Open the file for reading


if (file.is_open()) {
// Perform file operations
file.close(); // Close the file
}

Explanation:
 ifstream is used to open a file for reading, and ofstream for writing.
 The close() method is called to close the file stream.
 The is_open() method is used to check if the file was successfully opened before
performing operations.
In modern C++, the file stream object is automatically closed when it goes out of scope (i.e.,
when the object is destroyed).

5. JavaScript (Node.js)
In JavaScript, using Node.js, file operations are typically done through the fs (filesystem)
module. The fs.close() function is used to close a file.

Syntax:
const fs = require('fs');

fs.open('filename.txt', 'r', (err, fd) => {


if (err) throw err;
// Perform file operations
fs.close(fd, (err) => {
if (err) throw err;
console.log('File closed');
});
});

Explanation:
 fs.open() opens the file and returns a file descriptor (fd).
 fs.close() is used to close the file, taking the file descriptor as an argument.

6. PHP
In PHP, files are opened using the fopen() function, and they are closed using the fclose()
function.

Syntax:
$file = fopen("filename.txt", "r"); // Open the file
if ($file) {
// Perform file operations
fclose($file); // Close the file
}

Explanation:
 fopen() returns a file pointer, which is used to perform operations on the file.
 fclose() closes the file and releases resources.

Conclusion
Closing a file is essential to ensure system resources are freed, data is saved properly, and
potential file locks are released. The specific syntax for closing a file varies between
programming languages, but the general idea is consistent: use a specific method (such as
close()) on the file object or file descriptor to close the file. It is good practice to ensure files
are closed in a timely manner, either manually or automatically using language-specific
constructs like with in Python or try-with-resources in Java.

5.What is the behaviour of the virtual function in the derived class


from the base class and abstract?
In object-oriented programming, a virtual function in a base class and its behavior in a
derived class, as well as the concept of abstract functions, play a critical role in
polymorphism and inheritance. Let’s explore each concept in detail and understand their
relationships and behaviors.

1. Virtual Function in Base Class

A virtual function is a function in a base class that can be overridden in a derived class. The
keyword virtual is used to indicate that a function is intended to be overridden.

Behavior in Base Class:


 A virtual function provides a way to define a function in the base class, and the
derived class can modify (override) this behavior.
 When a derived class overrides a virtual function, the most derived version of the
function is called, depending on the type of the object, not the type of the reference
or pointer that invokes the function (this is known as dynamic polymorphism).

Example:
#include <iostream>
using namespace std;

class Base {
public:
virtual void display() {
cout << "Display from Base Class" << endl;
}
};

class Derived : public Base {


public:
void display() override { // Override the base class function
cout << "Display from Derived Class" << endl;
}
};

int main() {
Base* basePtr;
Derived derivedObj;

basePtr = &derivedObj;

basePtr->display(); // Calls the Derived class version of display() because of virtual


function
return 0;
}

Explanation:
 Here, display() is a virtual function in the base class.
 When basePtr (a pointer of type Base*) points to an object of Derived, calling
basePtr->display() invokes the overridden function in the Derived class. This
behavior is the result of dynamic dispatch.

Key Points:
 Virtual functions enable polymorphism: The function call is resolved at runtime.
 The virtual function mechanism allows derived classes to provide their own specific
implementation.

2. Virtual Function in Derived Class


When a derived class overrides a virtual function, it provides its own version of the function,
which replaces the base class version when the function is called on an object of the derived
class.

Example:
class Base {
public:
virtual void show() {
cout << "Base class show()" << endl;
}
};

class Derived : public Base {


public:
void show() override {
cout << "Derived class show()" << endl;
}
};

 In the example above, when a Derived object is used, the show() method of the
Derived class will be invoked, even if it is referenced through a base class pointer or
reference.

3. Abstract Functions

An abstract function is a function in a base class that is declared with no implementation. It


is intended to be overridden by derived classes, and it is declared using the = 0 syntax in C++
or the abstract keyword in languages like Java.
An abstract function makes the class containing it an abstract class, meaning that it cannot
be instantiated directly. A derived class is required to provide an implementation for all
abstract functions before it can be instantiated.

Behavior of Abstract Function:

 An abstract function does not have a body in the base class.


 Any derived class that inherits from the base class must override and provide an
implementation for the abstract function to become concrete and instantiable.
 If a derived class does not provide an implementation for the abstract function, the
derived class itself becomes abstract and cannot be instantiated.

Example in C++:
#include <iostream>
using namespace std;

class Base {
public:
virtual void display() = 0; // Pure virtual function (abstract)
};

class Derived : public Base {


public:
void display() override { // Must override the abstract function
cout << "Display from Derived Class" << endl;
}
};

int main() {
// Base baseObj; // Error: Cannot instantiate an abstract class
Derived derivedObj;
derivedObj.display(); // Calls Derived class implementation
return 0;
}

Explanation:
 The display() function in the base class is pure virtual, which means the base class is
abstract.
 The derived class Derived overrides the display() function and provides an
implementation.
 If you try to instantiate an object of the base class Base, it will lead to a compilation
error, as you cannot instantiate an abstract class.

Key Points:
 Abstract functions enforce implementation in derived classes: A class with an
abstract function is incomplete and cannot be instantiated until all abstract
functions are implemented by a derived class.
 Abstract classes enable a general interface: They allow the definition of common
behaviors (like virtual functions) but leave the specific
implementation details to be provided by subclasses.

Summary of Key Differences:

Feature Virtual Function (Base Class) Abstract Function (Base Class)


A function that can be overridden A function without
Definition
in derived classes implementation in base class
To provide a default
To force derived classes to
Purpose implementation or allow derived
implement the function
classes to override it
Implementation in Base
May have a body (implementation) No body (purely abstract)
Class
Can the Base Class be Yes, if the function has an No, because the class is
Instantiated? implementation abstract
Derived class must override the
Behavior in Derived Derived class can override the
abstract function to be
Class virtual function
concrete

Conclusion:

 Virtual functions allow dynamic method dispatch, enabling polymorphism and the
ability to provide default behavior or allow derived classes to override behavior.
 Abstract functions force derived classes to provide specific implementations,
making abstract classes useful for defining interfaces or incomplete functionality
that must be implemented in subclasses.

You might also like