0% found this document useful (0 votes)
22 views53 pages

PUE Solution

Uploaded by

fearless61022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views53 pages

PUE Solution

Uploaded by

fearless61022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

PUE Solution

Section A

1. List the reasons why object orientation works?

Object-oriented programming is based on the concept of objects. In object-oriented


programming data structures, or objects are defined, each with its own properties
or attributes. Each object can also contain its own procedures or methods. Software
is designed by using objects that interact with one another.

2. Define the object?

Object is a real world entity, for example, chair, car, pen, mobile, laptop etc. In other
words, object is an entity that has state and behavior. Here, state means data and
behavior means functionality. Object is a runtime entity, it is created at runtime

3. Define the stereotypes with graphical representation. Stereotypes is extensibility


mechanisms in UML which allows designers to extend the vocabulary of UML in
order to create new model elements. By applying appropriate stereotypes in your
model you can make the specification model comprehensible.

4. Distinguish between collaboration and sequence diagram.

• The sequence diagram represents the UML, which is used to visualize the sequence of
calls in a system that is used to perform a specific functionality. The collaboration
diagram also comes under the UML representation which is used to visualize the
organization of the objects and their interaction.
• The sequence diagram are used to represent the sequence of messages that are flowing
from one object to another. The collaboration diagram are used to represent the
structural organization of the system and the messages that are sent and received.
• The sequence diagram is used when time sequence is main focus. The collaboration
diagram is used when object organization is main focus.
• The sequence diagrams are better suited of analysis activities. The collaboration
diagrams are better suited for depicting simpler interactions of the smaller number of
objects.
5. How abstraction is different from encapsulation? Distinguish

Abstraction is a process of hiding the implementation details of a system from the


user, and only the functional details will be available to the user end. On the other
hand, Encapsulation is a method of wrapping up the data and code acting on the data
into a single unit.

6. What are three models that are needs to combine to perform the operations on
classes? Discuss.

After analysis, we have the object, dynamic, and functional models, but the object
model is the main framework around which the design is constructed. The object
model from the analysis may not show operations. The designer must convert the
actions and activities of the dynamic model and the processes of the functional model
into operations attached to classes in the object model. In making this conversion, we
begin the process of mapping the logical structure of the analysis model into a
physical organization of a program.

7. Determine the C++ syntax and write a program to execute enumerated data type.

An enumeration is a user-defined data type that consists of integral constants. To


define an enumeration, keyword enum is used.

#include <iostream>
using namespace std;

enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

int main()
{
week today;
today = Wednesday;
cout << "Day " << today+1;
return 0;
}

8. Determine the following C++ code and justify the output.

#include<iostream> using namespace std; class Test

{
Test()

{
cout<< "Test of OOSD";
} };

int main() {

Test t;

return 0; }

9. Explain the three access specifiers.

There are three access specifiers: public - members are accessible from outside the
class. private - members cannot be accessed (or viewed) from outside the class.
protected - members cannot be accessed from outside the class, however, they can be
accessed in inherited classes.

10. Discuss the characteristics of constructor function.

1. Constructors are invoked automatically when we create objects.


2. Constructors should be declared in the public section of the Class.
3. Constructors cannot return values to the calling program because they do not
have return types.
4. Constructors should always be non-virtual.

Section B

2. Discuss the advantages of modeling techniques.

Modeling is a central part of all the activities that lead up to the deployment of good
software. We build models to communicate the desired structure and behavior of our system.
We build models to visualize and control the system's architecture. We build models to better
understand the system we are building, often exposing opportunities for simplification and
reuse. And we build models to manage risk.

Importance of Modeling
Modeling is a proven & well accepted engineering techniques. In building architecture, we
develop architectural models of houses & high rises to help visualize the final products. In
Unified Modeling Language (UML), a model may be structural, emphasizing the
organization of the system or it may be behavioral, emphasizing the dynamics of the system.
A model is a simplification of reality, providing blueprints of a system. UML, in specific:
• Permits you to specify the structure or behavior of a system.
• Helps you visualize a system.
• Provides template that guides you in constructing a system.
• Helps to understand complex system part by part.
• Document the decisions that you have made.
We build model so that we can better understand the system we are developing. A model may
encompass an overview of the system under consideration, as well as a detailed planning for
system design, implementation and testing.
Principles of UML Modeling
1. The choice of model is important
The choice of what models to create has a profound influence on how a problem is attacked
and how a solution is shaped. We need to choose your models well.
• The right models will highlight the most critical development problems.
• Wrong models will mislead you, causing you to focus on irrelevant issues.

For Example: We can use different types of diagrams for different phases in software
development.

2. Every model may be expressed at different levels of precision


For Example,
• If you are building a high rise, sometimes you need a 30,000-foot view for instance,
to help your investors visualize its look and feel.
• Other times, you need to get down to the level of the studs for instance, when there's a
tricky pipe run or an unusual structural element.

3. The best models are connected to reality


All models simplify reality and a good model reflects important key characteristics.

4. No single model is sufficient


Every non-trivial system is best approached through a small set of nearly independent
models. Create models that can be built and studied separately, but are still interrelated. In the
case of a building:
• You can study electrical plans in isolation
• But you can also see their mapping to the floor plan and perhaps even their interaction
with the routing of pipes in the plumbing plan.

OR

Discuss the differences between Procedural and Object-Oriented Programming.

In procedural programming, the program is divided into small parts called functions. In
object-oriented programming, the program is divided into small parts called objects.

Procedural programming follows a top-down approach. Object-oriented programming


follows a bottom-up approach.

There is no access specifier in procedural programming. Object-oriented programming has


access specifiers like private, public, protected, etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have any proper way of hiding data so it is less secure.
Object-oriented programming provides data hiding so it is more secure.

In procedural programming, overloading is not possible. Overloading is possible in object-


oriented programming.

In procedural programming, there is no concept of data hiding and inheritance. In object-


oriented programming, the concept of data hiding and inheritance is used.

In procedural programming, the function is more important than the data. In object-oriented
programming, data is more important than function.

Procedural programming is based on the unreal world. Object-oriented programming is


based on the real world.

Procedural programming is used for designing medium-sized programs. Object-oriented


programming is used for designing large and complex programs.

Procedural programming uses the concept of procedure abstraction. Object-oriented


programming uses the concept of data abstraction.
Code reusability absent in procedural programming, Code reusability present in object-
oriented programming.

Examples: C, FORTRAN, Pascal, Basic, etc.Examples: C++, Java, Python, C#, etc.

3. Sketch the Activity diagram for Student Result Management Sy

stem.

OR
Sketch the sequence diagram of food order sys

tem.

4. Explain the steps that the designer must perform during object design.

Object Design
After the hierarchy of subsystems has been developed, the objects in the system are
identified and their details are designed. Here, the designer details out the strategy
chosen during the system design. The emphasis shifts from application domain
concepts toward computer concepts. The objects identified during analysis are
etched out for implementation with an aim to minimize execution time, memory
consumption, and overall cost.
Object design includes the following phases −

• Object identification
• Object representation, i.e., construction of design models
• Classification of operations
• Algorithm design
• Design of relationships
• Implementation of control for external interactions
• Package classes and associations into modules
Object Identification
The first step of object design is object identification. The objects identified in the
object–oriented analysis phases are grouped into classes and refined so that they are
suitable for actual implementation.
The functions of this stage are −
• Identifying and refining the classes in each subsystem or package
• Defining the links and associations between the classes
• Designing the hierarchical associations among the classes, i.e., the
generalization/specialization and inheritances
• Designing aggregations
Object Representation
Once the classes are identified, they need to be represented using object modelling
techniques. This stage essentially involves constructing UML diagrams.
There are two types of design models that need to be produced −
• Static Models − To describe the static structure of a system using class
diagrams and object diagrams.
• Dynamic Models − To describe the dynamic structure of a system and
show the interaction between classes using interaction diagrams and
state–chart diagrams.
Classification of Operations
In this step, the operation to be performed on objects are defined by combining the
three models developed in the OOA phase, namely, object model, dynamic model,
and functional model. An operation specifies what is to be done and not how it should
be done.
The following tasks are performed regarding operations −
• The state transition diagram of each object in the system is developed.
• Operations are defined for the events received by the objects.
• Cases in which one event triggers other events in same or different
objects are identified.
• The sub–operations within the actions are identified.
• The main actions are expanded to data flow diagrams.
Algorithm Design
The operations in the objects are defined using algorithms. An algorithm is a stepwise
procedure that solves the problem laid down in an operation. Algorithms focus on
how it is to be done.
There may be more than one algorithm corresponding to a given operation. Once the
alternative algorithms are identified, the optimal algorithm is selected for the given
problem domain. The metrics for choosing the optimal algorithm are −
• Computational Complexity − Complexity determines the efficiency of
an algorithm in terms of computation time and memory requirements.
• Flexibility − Flexibility determines whether the chosen algorithm can be
implemented suitably, without loss of appropriateness in various
environments.
• Understandability − This determines whether the chosen algorithm is
easy to understand and implement.
Design of Relationships
The strategy to implement the relationships needs to be chalked out during the object
design phase. The main relationships that are addressed comprise of associations,
aggregations, and inheritances.
The designer should do the following regarding associations −
• Identify whether an association is unidirectional or bidirectional.
• Analyze the path of associations and update them if necessary.
• Implement the associations as a distinct object, in case of many–to-
many relationships; or as a link to other object in case of one–to-one or
one–to-many relationships.
Regarding inheritances, the designer should do the following −
• Adjust the classes and their associations.
• Identify abstract classes.
• Make provisions so that behaviors are shared when needed.
Implementation of Control
The object designer may incorporate refinements in the strategy of the state–chart
model. In system design, a basic strategy for realizing the dynamic model is made.
During object design, this strategy is aptly embellished for appropriate
implementation.
The approaches for implementation of the dynamic model are −
• Represent State as a Location within a Program − This is the
traditional procedure-driven approach whereby the location of control
defines the program state. A finite state machine can be implemented
as a program. A transition forms an input statement, the main control
path forms the sequence of instructions, the branches form the
conditions, and the backward paths form the loops or iterations.
• State Machine Engine − This approach directly represents a state
machine through a state machine engine class. This class executes the
state machine through a set of transitions and actions provided by the
application.
• Control as Concurrent Tasks − In this approach, an object is
implemented as a task in the programming language or the operating
system. Here, an event is implemented as an inter-task call. It preserves
inherent concurrency of real objects.

Packaging Classes
In any large project, meticulous partitioning of an implementation into modules or
packages is important. During object design, classes and objects are grouped into
packages to enable multiple groups to work cooperatively on a project.
The different aspects of packaging are −
• Hiding Internal Information from Outside View − It allows a class to
be viewed as a “black box” and permits class implementation to be
changed without requiring any clients of the class to modify code.
• Coherence of Elements − An element, such as a class, an operation, or
a module, is coherent if it is organized on a consistent plan and all its
parts are intrinsically related so that they serve a common goal.
• Construction of Physical Modules − The following guidelines help
However, this may pose update anomalies, i.e., a change in the values
of base attributes with no corresponding change in the values of the
derived attributes. while constructing physical modules −
o Classes in a module should represent similar things or
components in the same composite object.
o Closely connected classes should be in the same module.
o Unconnected or weakly connected classes should be
placed in separate modules.
o Modules should have good cohesion, i.e., high cooperation
among its components.
o A module should have low coupling with other modules,
i.e., interaction or interdependence between modules
should be minimum.

Design Optimization
The analysis model captures the logical information about the system, while the
design model adds details to support efficient information access. Before a design is
implemented, it should be optimized so as to make the implementation more efficient.
The aim of optimization is to minimize the cost in terms of time, space, and other
metrics.
However, design optimization should not be excess, as ease of implementation,
maintainability, and extensibility are also important concerns. It is often seen that a
perfectly optimized design is more efficient but less readable and reusable. So the
designer must strike a balance between the two.
The various things that may be done for design optimization are −

• Add redundant associations


• Omit non-usable associations
• Optimization of algorithms
• Save derived attributes to avoid re-computation of complex
expressions
Addition of Redundant Associations
During design optimization, it is checked if deriving new associations can reduce
access costs. Though these redundant associations may not add any information,
they may increase the efficiency of the overall model.

Omission of Non-Usable Associations


Presence of too many associations may render a system indecipherable and hence
reduce the overall efficiency of the system. So, during optimization, all non-usable
associations are removed.

Optimization of Algorithms
In object-oriented systems, optimization of data structure and algorithms are done in
a collaborative manner. Once the class design is in place, the operations and the
algorithms need to be optimized.
Optimization of algorithms is obtained by −

• Rearrangement of the order of computational tasks


• Reversal of execution order of loops from that laid down in the
functional model
• Removal of dead paths within the algorithm
Saving and Storing of Derived Attributes
Derived attributes are those attributes whose values are computed as a function of
other attributes (base attributes). Re-computation of the values of derived attributes
every time they are needed is a time–consuming procedure. To avoid this, the values
can be computed and stored in their computed forms.
• To avoid this, the following steps are taken −
• With each update of the base attribute value, the derived attribute is
also re-computed.
• All the derived attributes are re-computed and updated periodically in
a group rather than after each update.

Design Documentation
Documentation is an essential part of any software development process that
records the procedure of making the software. The design decisions need to be
documented for any non–trivial software system for transmitting the design to
others.

Usage Areas
Though a secondary product, a good documentation is indispensable, particularly in
the following areas −

• In designing software that is being developed by a number of


developers
• In iterative software development strategies
• In developing subsequent versions of a software project
• For evaluating a software
• For finding conditions and areas of testing
• For maintenance of the software.
Contents
A beneficial documentation should essentially include the following contents −
• High–level system architecture − Process diagrams and module
diagrams
• Key abstractions and mechanisms − Class diagrams and object
diagrams.
• Scenarios that illustrate the behavior of the main aspects −
Behavioural diagrams
Features
The features of a good documentation are −
• Concise and at the same time, unambiguous, consistent, and complete
• Traceable to the system’s requirement specifications
• Well-structured
• Diagrammatic instead of descriptive

OR
Describe the different features of object-oriented programming.

Object-oriented programming, or OOPs, is a programming model which breaks down a


problem in terms of classes and objects. OOPs allows the creation of several instances of a
class called objects, hence facilitating code reuse. Some object-oriented programming
languages are C++, Java, Javascript, Python, etc.
The four main pillars or features of object oriented programming
include Abstraction, Polymorphism, Inheritance, and Encapsulation, or you can learn it as A
PIE to recall all of them easily.
Let’s learn the important features of object-oriented programming and examples in the
next section.
Features Of Object Oriented Programming

The main features of object oriented programming are as follows:


• Classes

• Objects

• Abstraction

• Polymorphism

• Inheritance

• Encapsulation

In the upcoming sections, let’s see each object-oriented programming feature in detail.
Classes and Objects in OOPs
A class is a template that consists of the data members or variables and functions and defines
the properties and methods for a group of objects.
The compiler does not allocate memory whenever you define a class.
Example:
You can define a class called Vehicle. Its data fields can be vehicle_name, model_number,
color, date_of_manufacture, etc.

An object is nothing but an instance of a class. Each object has its values for the different
properties present in its class. The compiler allocates memory for each object.
Example:
The different objects of the class Vehicle can be Car, Bike, Bicycle, etc. Each of them will
have its values for the fields like color, model_number, etc.
Abstraction
The literal meaning of abstraction is to remove some characteristics from something to
reduce it to a smaller set. Similarly, Object Oriented Programming abstraction exposes only
the essential information of an object to the user and hides the other details.
In real life, like when you toggle a switch, it simply turns on or off the lights. Here, we only
know the functionality of the switch, but we don’t know its internal implementation, like how
it works.
How to implement abstraction?
You can implement abstraction using classes that group the data members and function
together. Inside classes, you can choose the access specifiers for its members to control how
they are visible to the outside world. We can also create header files containing the
implementations of all the necessary functions. So, you can include the header file and call
these functions without getting into their implementation.
Advantages of Abstraction
The advantages of abstraction are as follows:
• It enables code reuse by avoiding code duplication.

• It enhances software security by making only necessary information available to


the users and hiding the complex ones.
Inheritance
Inheritance is one of the most important features of object oriented programming. It allows a
class to inherit the properties and methods of another class called the parent class, the base
class, or the super-class.
The class that inherits is called the child class or sub-class.
It helps to avoid duplication of codes by allowing code reuse as you need not define the same
methods and properties present in a super-class in the sub-classes again. The sub-class can
simply inherit them.
Example:
You can have a parent class called “Shape” and other classes like Square, Circle, Rectangle,
etc. Since all these are also shapes, they will have all the properties of a shape so that they
can inherit the class Shape.
Polymorphism
The word polymorphism means to have many forms. So, by using polymorphism, you can
add different meanings to a single component.
There are two types of polymorphism:
• Run-time polymorphism

• Compile-time polymorphism

Let's see each type in the next section.


Method Overloading
Methods overloading is a type of compile-time polymorphism using which you can define
various functions with the same name but different numbers of arguments. The function call
is resolved at compile time, so it's a type of compile-time polymorphism. Here resolution of
the function call implies binding to the correct function definition depending on the
arguments passed in the function call.
Example:
You can create a function “add”. Now, when you pass two integers to this function, it will
return their sum, while on passing two strings, it will return their concatenation.
So, the same function acts differently depending on the input data type.
Method Overriding
Method Overriding is a type of run-time polymorphism. It allows overriding a parent class’s
method by a child class. Overriding means that a child class provides a new implementation
of the same method it inherits from the parent class.
These function calls are resolved at run-time, so it's a type of runtime polymorphism.
Example:
You can have a parent class called “Shape” with a method named “findArea” that calculates
and returns the area of the shape. Several sub-classes inherit from the “Shape,” like Square,
Circle, Rectangle, etc. Each of them will define the function “findArea” in its way, thus
overriding the function.
Encapsulation
Encapsulation means enclosing the data/variables and the methods for manipulating the data
into a single entity called a class. It helps to hide the internal implementation of the functions
and state of the variables, promoting abstraction.

Example:
You can have some private variables in a class that you can't access outside the class for
security reasons. Now, to read or change the value of this variable, you can define public
functions in the class which will perform the read or writes operations.

Other Oops Features:


Dynamic Binding
Dynamic binding takes place during run time based on the type of object. Since it is delayed
till the run time, it is also called late binding or runtime binding. When the compiler cannot
determine all the information required to resolve a function call during compile time, these
function calls are not bound until run time.
Message Passing
Message passing refers to the process of passing a message, or data, between different objects
or components in a program. This can be done in many ways, such as function calls, events,
or inter-process communication. The specific implementation of message passing will depend
on the program's design and the system's needs.
Advantages of Object Oriented Programming
The advantages of object oriented programming are as follows:
• It makes troubleshooting easier and faster by making the code modular. So, you
can look at the particular class or method whenever an error occurs instead of
checking the entire code.

• It allows code reuse by inheritance.

• It enables flexibility through polymorphism as one function or object can adapt


to several forms according to the requirement.

• It allows you to solve a problem efficiently by breaking a huge problem into


smaller manageable parts like classes and objects.
Disadvantages of Object Oriented Programming
The disadvantages of object oriented programming are as follows:
• It has a steep learning curve because breaking down a problem into simple
components requires long-term thinking, which comes with experience.

• Generally, the code becomes larger in object-oriented programming compared to


procedural programming.

5. Examine the output by write a C++ code to implement three default


arguments.

A default argument is a value provided in a function declaration that is


automatically assigned by the compiler if the calling function doesn’t provide a
value for the argument. In case any value is passed, the default value is
overridden.

1) The following is a simple C++ example to demonstrate the use of default


arguments. Here, we don’t have to write 3 sum functions; only one function
works by using the default values for 3rd and 4th arguments.
2) #include <iostream>
3) using namespace std;
4)
5) // A function with default arguments,
6) // it can be called with
7) // 2 arguments or 3 arguments or 4 arguments.
8) int sum(int x, int y=0, int z = 0, int w = 0) //assigning
default values to z,w as 0
9) {
10) return (x + y + z + w);
11) }
12)
13) // Driver Code
14) int main()
15) {
16) // Statement 1
17) cout << sum(10) << endl;
18)
19) // Statement 2
20) cout << sum(10, 15, 25) << endl;
21)
22) // Statement 3
23) cout << sum(10, 15, 25, 30) << endl;
24) return 0;
25) }

OR

Compare and contrast the differences between Inline function and Macros

with examples.

1. Inline :
An inline function is a normal function that is defined by the inline keyword.
An inline function is a short function that is expanded by the compiler. And its
arguments are evaluated only once. An inline functions are the short length
functions that are automatically made the inline functions without using
the inline keyword inside the class.
Syntax of an Inline function:
inline return_type function_name ( parameters )
{
// inline function code
}
Example of an Inline function:
#include <iostream>
using namespace std;

// Inline function
inline int Maximum(int a, int b)
{
return (a > b) ? a : b;
}

// Main function for the program


int main()
{
cout << "Max (100, 1000):" << Maximum(100, 1000) << endl;
cout << "Max (20, 0): " << Maximum(20, 0) << endl;

return 0;
}

Output:
Max (100, 1000): 1000
Max (20, 0): 20
2. Macro :
It is also called preprocessors directive. The macros are defined by
the #define keyword. Before the program compilation, the preprocessor
examines the program whenever the preprocessor detects the macros then
preprocessor replaces the macro by the macro definition.
Syntax of Macro:
#define MACRO_NAME Macro_definition
Example of Macro:
#include <iostream>
using namespace std;

// macro with parameter


#define MAXIMUM(a, b) (a > b) ? a : b

// Main function for the program


int main()
{
cout << "Max (100, 1000):";
int k = MAXIMUM(100, 1000);
cout << k << endl;

cout << "Max (20, 0):";


int k1 = MAXIMUM(20, 0);
cout << k1;

return 0;
}

Output:
Max (100, 1000):1000
Max (20, 0):20

Difference between Inline and Macro in C++ :


S.NO Inline Macro

An inline function is Whereas the macros are


1. defined by defined by
the inlinekeyword. the #definekeyword.
S.NO Inline Macro

Through inline function,


Whereas macro can’t access
2. the class’s data members
the class’s data members.
can be accessed.

In the case of inline Whereas in the case of


3. function, the program can macros, the program can’t be
be easily debugged. easily debugged.

Whereas in the case of macro,


In the case of inline, the
the arguments are evaluated
4. arguments are evaluated
every time whenever macro is
only once.
used in the program.

In C++, inline may be Whereas the macro is all the


5. defined either inside the time defined at the beginning
class or outside the class. of the program.

In C++, inside the class,


the short length functions While the macro is
6.
are automatically made the specifically defined.
inline functions.

Inline is not as widely While the macro is widely


7.
used as macros. used.

While the macro is very much


Inline is not used in
8. used in competitive
competitive programming.
programming.

Inline function is While the macro is not


9. terminated by the curly terminated by any symbol, it
brace at the end. is terminated by a new line.

6. Distinguish among different types of inheritance and write the C++ code to
execute multiple inheritance.

nheritance is a method through which one class inherits the properties from its
parent class. Inheritance is a feature in which one new class is derived from
the existing ones. The new class derived is termed a derived class, and the
current class is termed a Parent or base class. Inheritance is one of the most
essential features of Object Oriented Programming. Rather than defining new
data functions while creating a class, you can inherit the existing class's data
functions. The derived class takes over all the properties of the parent class
and adds some new features to itself. For example, using inheritance, you can
add the members' names and descriptions to a new class.

Child class: The class that inherits the characteristics of another class is known
as the child class or derived class. The number of child classes that can be
inherited from a single parent class is based upon the type of inheritance. A
child class will access the data members of the parent class according to the
visibility mode specified during the declaration of the child class.

Parent class: The class from which the child class inherits its properties is
called the parent class or base class. A single parent class can derive multiple
child classes (Hierarchical Inheritance) or multiple parent classes can inherit a
single base class (Multiple Inheritance). This depends on the different types of
inheritance in C++.

The syntax for defining the child class and parent class in all types of
Inheritance in C++ is given below:

class parent_class

//class definition of the parent class

};

class child_class : visibility_mode parent_class

//class definition of the child class


};

Syntax Description

parent_class: Name of the base class or the parent class.

child_class: Name of the derived class or the child class.

visibility_mode: Type of the visibility mode (i.e., private, protected, and


public) that specifies how the data members of the child class inherit from the
parent class.

Importance of Inheritance in C++

Instead of trying to replicate what already exists, it is always ideal to reuse it


since it saves time and enhances reliability. In C++, inheritance is used to
reuse code from existing classes. C++ highly supports the principle of
reusability. Inheritance is used when two classes in a program share the same
domain, and the properties of the class and its superclass should remain the
same. Inheritance is a technique used in C++ to reuse code from pre-existing
classes. C++ actively supports the concept of reusability.

Implementing Inheritance in C++

To create a parent class that is derived from the base class below is a syntax
that you should follow:

class

<derived_class_name> : <access-specifier>

<base_class_name>
{

/ /body

Here, class is a keyword which is used to create a new class,


derived_class_name is the new class name which will inherit the properties of
a base class, and access-specifier defines through mode the derived class has
been created, whether through public, private or protected mode and the
base_class_name is the name of the base class.

Public Inheritance: The public members of the base class remain public even
in the derived class; the same applies to the protected members.

Private Inheritance: This makes public members and protected members from
the base class to be protected in the derived class. The derived class has no
access to the base class's private members.

Protected Inheritance protects the Public and protected members from the
derived class's base class.

#include<iostream>
using namespace std;

class A
{
public:
A() { cout << "A's constructor called" << endl; }
};

class B
{
public:
B() { cout << "B's constructor called" << endl; }
};

class C: public B, public A // Note the order


{
public:
C() { cout << "C's constructor called" << endl; }
};

int main()
{
C c;
return 0;
}

Output:
B's con

OR

Examine the output when implementing the friend function in C++ code.
Write the program.

If a function is defined as a friend function in C++, then the protected and private data of a
class can be accessed using the function.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the body of
a class starting with the keyword friend.

Declaration of friend function in C++


1. class class_name
2. {
3. friend data_type function_name(argument/s); // syntax of friend function.
4. };

In the above declaration, the friend function is preceded by the keyword friend. The function
can be defined anywhere in the program like a normal C++ function. The function definition
does not use either the keyword friend or scope resolution operator.

Characteristics of a Friend function:


o The function is not in the scope of the class to which it has been declared as a
friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
o It cannot access the member names directly and has to use an object name and
dot membership operator with the member name.
o It can be declared either in the private or the public part.

C++ friend function Example


Let's see the simple example of C++ friend function used to print the length of a box.

1. #include <iostream>
2. using namespace std;
3. class Box
4. {
5. private:
6. int length;
7. public:
8. Box(): length(0) { }
9. friend int printLength(Box); //friend function
10. };
11. int printLength(Box b)
12. {
13. b.length += 10;
14. return b.length;
15. }
16. int main()
17. {
18. Box b;
19. cout<<"Length of box: "<< printLength(b)<<endl;
20. return 0;
21. }

Section C

7. Sketch the conceptual model of the UML and also interpret with suitable
notations for each building blocks.
UML is composed of three main building blocks, i.e., things, relationships,
and diagrams. Building blocks generate one complete UML model diagram by
rotating around several different blocks. It plays an essential role in
developing UML diagrams. The basic UML building blocks are enlisted
below:

Things

Relationships

Diagrams

Things

Anything that is a real world entity or object is termed as things. It can be


divided into several different categories:

Structural things

Behavioral things

Grouping things

Annotational things

Structural things

Nouns that depicts the static behavior of a model is termed as structural things.
They display the physical and conceptual components. They include class,
object, interface, node, collaboration, component, and a use case.

Class: A Class is a set of identical things that outlines the functionality and
properties of an object. It also represents the abstract class whose
functionalities are not defined. Its notation is as follows;

Pause

Next
Unmute

Current TimeÂ

0:00

DurationÂ

-:-

Loaded: 0%

Fullscreen

Backward Skip 10s

Play Video

Forward Skip 10s

UML-Building Blocks

Object:: An individual that describes the behavior and the functions of a


system. The notation of the object is similar to that of the class; the only
difference is that the object name is always underlined and its notation is given
below;

UML-Building Blocks

Interface: A set of operations that describes the functionality of a class, which


is implemented whenever an interface is implemented.

UML-Building Blocks
Collaboration: It represents the interaction between things that is done to meet
the goal. It is symbolized as a dotted ellipse with its name written inside it.

UML-Building Blocks

Use case: Use case is the core concept of object-oriented modeling. It portrays
a set of actions executed by a system to achieve the goal.

UML-Building Blocks

Actor: It comes under the use case diagrams. It is an object that interacts with
the system, for example, a user.

UML-Building Blocks

Component: It represents the physical part of the system.

UML-Building Blocks

Node: A physical element that exists at run time.

UML-Building Blocks

Behavioral Things

They are the verbs that encompass the dynamic parts of a model. It depicts the
behavior of a system. They involve state machine, activity diagram,
interaction diagram, grouping things, annotation things

State Machine: It defines a sequence of states that an entity goes through in


the software development lifecycle. It keeps a record of several distinct states
of a system component.

UML-Building Blocks
Activity Diagram: It portrays all the activities accomplished by different
entities of a system. It is represented the same as that of a state machine
diagram. It consists of an initial state, final state, a decision box, and an action
notation.

UML-Building Blocks

Interaction Diagram: It is used to envision the flow of messages between


several components in a system.

UML-Building Blocks

Grouping Things

It is a method that together binds the elements of the UML model. In UML,
the package is the only thing, which is used for grouping.

Package: Package is the only thing that is available for grouping behavioral
and structural things.

UML-Building Blocks

Annotation Things

It is a mechanism that captures the remarks, descriptions, and comments of


UML model elements. In UML, a note is the only Annotational thing.

Note: It is used to attach the constraints, comments, and rules to the elements
of the model. It is a kind of yellow sticky note.

UML-Building Blocks

Relationships
It illustrates the meaningful connections between things. It shows the
association between the entities and defines the functionality of an application.
There are four types of relationships given below:

Dependency: Dependency is a kind of relationship in which a change in target


element affects the source element, or simply we can say the source element is
dependent on the target element. It is one of the most important notations in
UML. It depicts the dependency from one entity to another.

It is denoted by a dotted line followed by an arrow at one side as shown


below,

UML-Building Blocks

Association: A set of links that associates the entities to the UML model. It
tells how many elements are actually taking part in forming that relationship.

It is denoted by a dotted line with arrowheads on both sides to describe the


relationship with the element on both sides.

UML-Building Blocks

Generalization: It portrays the relationship between a general thing (a parent


class or superclass) and a specific kind of that thing (a child class or subclass).
It is used to describe the concept of inheritance.

It is denoted by a straight line followed by an empty arrowhead at one side.

UML-Building Blocks

Realization: It is a semantic kind of relationship between two things, where


one defines the behavior to be carried out, and the other one implements the
mentioned behavior. It exists in interfaces.
It is denoted by a dotted line with an empty arrowhead at one side.

UML-Building Blocks

Diagrams

The diagrams are the graphical implementation of the models that incorporate
symbols and text. Each symbol has a different meaning in the context of the
UML diagram. There are thirteen different types of UML diagrams that are
available in UML 2.0, such that each diagram has its own set of a symbol.
And each diagram manifests a different dimension, perspective, and view of
the system.

UML diagrams are classified into three categories that are given below:

Structural Diagram

Behavioral Diagram

Interaction Diagram

Structural Diagram: It represents the static view of a system by portraying the


structure of a system. It shows several objects residing in the system.
Following are the structural diagrams given below:

Class diagram

Object diagram

Package diagram

Component diagram

Deployment diagram

Behavioral Diagram: It depicts the behavioral features of a system. It deals


with dynamic parts of the system. It encompasses the following diagrams:
Activity diagram

State machine diagram

Use case diagram

Interaction diagram: It is a subset of behavioral diagrams. It depicts the


interaction between two objects and the data flow between them. Following
are the several interaction diagrams in UML:

Timing diagram

Sequence diagram

Collaboration diagram

OR

Demonstrate and discuss the principles of modelling in detail?

First principle of modeling:

The choice of what models to create has a profound influence on how a


problem is attacked and how a solution is shaped.

Choose your models well. The right models will highlight the most nasty
development problems. Wrong models will mislead you, causing you to focus
on irrelevant issues.
Second principle of modeling:

Every model may be expressed at different levels of precision.

Sometimes, a quick and simple executable model of the user interface is


exactly what you need. At other times, you have to get down to complex
details such as cross-system interfaces or networking issues etc.

In any case, the best kinds of models are those that let you choose your degree
of detail, depending on who is viewing it. An analyst or an end user will want
to focus on issues of what and a developer will want to focus on issues of how.

Third principle of modeling:

The best models are connected to reality.


In software, the gap between the analysis model and the system’s design
model must be less. Failing to bridge this gap causes the system to diverge
over time. In object-oriented systems, it is possible to connect all the nearly
independent views of a system into one whole.

Fourth principle of modeling:

No single model is sufficient. Every non-trivial system is best approached


through a small set of nearly independent models.

In the case of a building, you can study electrical plans in isolation, but you
can also see their mapping to the floor plan and perhaps even their interaction
with the routing of pipes in the plumbing plan.

The same is true of object-oriented systems. To understand the architecture of


such a system, you need several complementary and interlocking views: a use
case view (exposing the requirements of the system), a design view (capturing
the vocabulary of the problem space and the solution space), a process view
(modeling the distribution of the system’s processes and threads), an
implementation view (addressing the physical realization of the system) and a
deployment view (focusing on system engineering issues). Depending on the
nature of the system, some models may be more important than others.

8. Determine and discuss the basic structural modelling with classes,


relationships and common mechanism.
OR

Determine and discuss use case diagram and defend UML use case withan
example.

A use case diagram is used to represent the dynamic behavior of a system. It encapsulates the
system's functionality by incorporating use cases, actors, and their relationships. It models the
tasks, services, and functions required by a system/subsystem of an application. It depicts the
high-level functionality of a system and also tells how the user handles a system.

Purpose of Use Case Diagrams


The main purpose of a use case diagram is to portray the dynamic aspect of a system. It
accumulates the system's requirement, which includes both internal as well as external
influences. It invokes persons, use cases, and several things that invoke the actors and
elements accountable for the implementation of use case diagrams. It represents how an
entity from the external environment can interact with a part of the system.

Following are the purposes of a use case diagram given below:

1. It gathers the system's needs.


2. It depicts the external view of the system.
3. It recognizes the internal as well as external factors that influence the system.
4. It represents the interaction between the actors.

How to draw a Use Case diagram?


It is essential to analyze the whole system before starting with drawing a use case diagram,
and then the system's functionalities are found. And once every single functionality is
identified, they are then transformed into the use cases to be used in the use case diagram.

PauseNext
Unmute

Current Time 0:00

Duration -:-
Loaded: 0%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
After that, we will enlist the actors that will interact with the system. The actors are the
person or a thing that invokes the functionality of a system. It may be a system or a private
entity, such that it requires an entity to be pertinent to the functionalities of the system to
which it is going to interact.

Once both the actors and use cases are enlisted, the relation between the actor and use case/
system is inspected. It identifies the no of times an actor communicates with the system.
Basically, an actor can interact multiple times with a use case or system at a particular
instance of time.

Following are some rules that must be followed while drawing a use case diagram:

1. A pertinent and meaningful name should be assigned to the actor or a use case of a
system.
2. The communication of an actor with a use case must be defined in an understandable
way.
3. Specified notations to be used as and when required.
4. The most significant interactions should be represented among the multiple no of
interactions between the use case and actors.

Example of a Use Case Diagram


A use case diagram depicting the Online Shopping website is given below.

Here the Web Customer actor makes use of any online shopping website to purchase online.
The top-level uses are as follows; View Items, Make Purchase, Checkout, Client Register.
The View Items use case is utilized by the customer who searches and view products.
The Client Register use case allows the customer to register itself with the website for
availing gift vouchers, coupons, or getting a private sale invitation. It is to be noted that
the Checkout is an included use case, which is part of Making Purchase, and it is not
available by itself.
The View Items is further extended by several use cases such as; Search Items, Browse
Items, View Recommended Items, Add to Shopping Cart, Add to Wish list. All of these
extended use cases provide some functions to customers, which allows them to search for an
item. The View Items is further extended by several use cases such as; Search Items, Browse
Items, View Recommended Items, Add to Shopping Cart, Add to Wish list. All of these
extended use cases provide some functions to customers, which allows them to search for an
item.

Both View Recommended Item and Add to Wish List include the Customer
Authentication use case, as they necessitate authenticated customers, and simultaneously item
can be added to the shopping cart without any user authentication.
Similarly, the Checkout use case also includes the following use cases, as shown below. It
requires an authenticated Web Customer, which can be done by login page, user
authentication cookie ("Remember me"), or Single Sign-On (SSO). SSO needs an external
identity provider's participation, while Web site authentication service is utilized in all these
use cases.

The Checkout use case involves Payment use case that can be done either by the credit card
and external credit payment services or with PayPal.
Important tips for drawing a Use Case diagram
Following are some important tips that are to be kept in mind while drawing a use case
diagram:

1. A simple and complete use case diagram should be articulated.


2. A use case diagram should represent the most significant interaction among the
multiple interactions.
3. At least one module of a system should be represented by the use case diagram.
4. If the use case diagram is large and more complex, then it should be drawn more
generalized.

9. Compare SA/SD methodology with OMT methodology


SA/SD OMT

It manages system around real


1 It manages a system around procedures.
world objects.

More importance is on object


More importance is on functional model and
2 model and less on functional
less on object model.
model.

Dominance order is functional, dynamic and Dominance order is object,


3
object. dynamic and functional.

4 It is a historical approach. It is much advanced approach.

It clearly marks the system boundaries across


System boundries can be easily
which software procedures should
5 extending by adding new
communicate with real world. It is difficult to
objects, relationships.
extend boundries.

Decomposition of process to sub-process is Decompsition is based on


6 not standardized. Different people provide objects so different people
different decomposition. provide similar decomposition.

Reusablity of components
Reusability of components across projects is
7 across projects is more as
less as compared to in OMT.
compared to SA/AD.

Easily modifiable and


8 Not easily modifiable and extensible.
extensible.

Used when functions are more important than Used when data is more
9
data. important than functions.

Difficult to merge programming code It better integrates data with


10 organized about functions while database is programming code as database
organized around data. is organized around data.

OR

Compare and contrast the SA/SD phases with JSD phases.


Structured Analysis and Structured Design (SA/SD) is a diagrammatic
notation which is design to help people understand the system. The basic goal
of SA/SD is to improve quality and reduce the risk of system failure. It
establishes a concrete management specification and documentation. It
focuses on solidity, pliability and maintainability of the system.
Basically, the approach of SA/SD is based on the Data Flow Diagram. It is
easy to understand SA/SD but it focuses on well-defined system boundary
whereas the JSD approach is too complex and does not have any graphical
representation.
SA/SD is combined known as SAD and it mainly focuses on following 3 points:

1. System
2. Process
3. Technology

SA/SD involves 2 phases:

1. Analysis Phase: It uses Data Flow Diagram, Data Dictionary, State


Transition diagram and ER diagram.
2. Design Phase: It uses the Structure Chart and Pseudo Code.

Jackson System Development (JSD) is a method of system development that


covers the software life cycle either directly or by providing a framework into
which more specialized techniques can fit. JSD can start from the stage in a
project when there is only a general statement of requirements. However many
projects that have used JSD actually started slightly later in the life cycle,
doing the first steps largely from existing documents rather than directly with
the users.

Phases of JSD:

JSD has 3 phases:

Modelling Phase: In the modelling phase of JSD, the designer creates a


collection of entity structure diagrams and identifies the entities in the system,
the actions they perform, the attributes of the actions and the time order of the
actions in the life of the entities.
Specification Phase: This phase focuses on actually what is to be done?
Previous phase provides the basic for this phase. An sufficient model of a
time-ordered world must itself be time-ordered. Major goal is to map progress
in the real world on progress in the system that models it.

Implementation Phase: In the implementation phase JSD determines how to


obtain the required functionality. Implementation way of the system is based
on the transformation of the specification into an efficient set of processes.
The processes involved in it should be designed in such a manner that it would
be possible to run them on available software and hardware.

JSD Steps:

Initially there were six steps when it was originally presented by Jackson, they
were as below:

Entity/action step

Initial model step

Interactive function step

Information function step

System timing step

System implementation step

Modelling Step

Network Step

Implementation Step

Merits of JSD:

It is designed to solve the real-time problems.

JSD modelling focuses on time.

It considers simultaneous processing and timing.

Provides functionality in the real world.


It is a better approach for microcode applications.

Demerits of JSD:

It is a poor methodology for high level analysis and database design.

JSD is a complex methodology due to pseudo code representation.

It is less graphically oriented as compared to SA/SD or OMT.

It is a bit complex and difficult to understand.

10. Code a C++ program for run time polymorphism.

OR

Code a C++ program for compile time polymorphism.

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 considered
one of the important features of Object-Oriented Programming.
Types of Polymorphism
• Compile-time Polymorphism
• Runtime Polymorphism
Types of Polymorphism

1. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator
overloading.

A. 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. There are certain Rules of Function Overloading that should be
followed while overloading a function.
Below is the C++ program to show function overloading or compile-time
polymorphism:
C++

// C++ program to demonstrate


// function overloading or
// Compile-time Polymorphism
#include <bits/stdc++.h>

using namespace std;


class Geeks {
public:
// Function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}

// Function with same name but


// 1 double parameter
void func(double x)
{
cout << "value of x is " << x << endl;
}

// Function with same name and


// 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y
<< endl;
}
};

// Driver code
int main()
{
Geeks obj1;

// Function being called depends


// on the parameters passed
// func() is called with int value
obj1.func(7);

// func() is called with double value


obj1.func(9.132);

// func() is called with 2 int values


obj1.func(85, 64);
return 0;
}

Output
value of x is 7
value of x is 9.132
value of x and y is 85, 64
Explanation: In the above example, a single function named
function func() acts differently in three different situations, which is a property
of polymorphism. To know more about this, you can refer to the article
– Function Overloading in C++.

B. Operator Overloading

C++ has the ability to provide the operators with a special meaning for a data
type, this ability is known as operator overloading. For example, we can make
use of the addition operator (+) for string class to concatenate two strings. We
know that the task of this operator is to add two operands. So a single operator
‘+’, when placed between integer operands, adds them and when placed
between string operands, concatenates them.
Below is the C++ program to demonstrate operator overloading:
CPP

// C++ program to demonstrate


// Operator Overloading or
// Compile-Time Polymorphism
#include <iostream>
using namespace std;

class Complex {
private:
int real, imag;

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

// This is automatically called


// when '+' is used with between
// two Complex objects
Complex operator+(Complex const& obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};
// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);

// An example call to "operator+"


Complex c3 = c1 + c2;
c3.print();
}

Output
12 + i9
Explanation: In the above example, the operator ‘+’ is overloaded. Usually,
this operator is used to add two numbers (integers or floating point numbers),
but here the operator is made to perform the addition of two imaginary or
complex numbers. To know more about this one, refer to the article – Operator
Overloading.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding
and dynamic polymorphism are other names for runtime polymorphism. The
function call is resolved at runtime in runtime polymorphism. In contrast, with
compile time polymorphism, the compiler determines which function call to
bind to the object after deducing it at runtime.

A. Function Overriding

Function Overriding occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.
Function overriding Explanation

Below is the C++ program to demonstrate function overriding:


C++

// C++ program for function overriding


#include <bits/stdc++.h>
using namespace std;

class base {
public:
virtual void print()
{
cout << "print base class" << endl;
}

void show() { cout << "show base class" << endl; }


};

class derived : public base {


public:
// print () is already virtual function in
// derived class, we could also declared as
// virtual void print () explicitly
void print() { cout << "print derived class" << endl; }

void show() { cout << "show derived class" << endl; }


};

// Driver code
int main()
{
base* bptr;
derived d;
bptr = &d;

// Virtual function, binded at


// runtime (Runtime polymorphism)
bptr->print();

// Non-virtual function, binded


// at compile time
bptr->show();

return 0;
}

Output
print derived class
show base class
Runtime Polymorphism with Data Members
Runtime Polymorphism can be achieved by data members in C++. Let’s see an
example where we are accessing the field by reference variable which refers to
the instance of the derived class.
C++

// C++ program for function overriding with data members


#include <bits/stdc++.h>
using namespace std;

// base class declaration.


class Animal {
public:
string color = "Black";
};

// inheriting Animal class.


class Dog : public Animal {
public:
string color = "Grey";
};

// Driver code
int main(void)
{
Animal d = Dog(); // accessing the field by reference
// variable which refers to derived
cout << d.color;
}

Output
Black

Virtual Function

A virtual function is a member function that is declared in the base class using
the keyword virtual and is re-defined (Overridden) in the derived class.
Some Key Points About Virtual Functions:
•Virtual functions are Dynamic in nature.
• They are defined by inserting the keyword “virtual” inside a base
class and are always declared with a base class and overridden in a
child class
• A virtual function is called during Runtime
Below is the C++ program to demonstrate virtual function:
C++

// C++ Program to demonstrate


// the Virtual Function
#include <iostream>
using namespace std;

// Declaring a Base class


class GFG_Base {

public:
// virtual function
virtual void display()
{
cout << "Called virtual Base Class function"
<< "\n\n";
}

void print()
{
cout << "Called GFG_Base print function"
<< "\n\n";
}
};

// Declaring a Child Class


class GFG_Child : public GFG_Base {

public:
void display()
{
cout << "Called GFG_Child Display Function"
<< "\n\n";
}

void print()
{
cout << "Called GFG_Child print Function"
<< "\n\n";
}
};

// Driver code
int main()
{
// Create a reference of class GFG_Base
GFG_Base* base;
GFG_Child child;

base = &child;

// This will call the virtual function


base->GFG_Base::display();

// this will call the non-virtual function


base->print();
}

Output
Called virtual Base Class function

Called GFG_Base print functi

You might also like