21-22 Solution

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

Section A

I. Attempt all Questions.

1. Differentiate between Link and Association.


Link

• It can be understood as the physical connection between objects.


• It helps tell about the relationship among objects.
• It is represented using line segment between objects.
• They can’t be referenced.
• It is used in UML designs.

Association

• It is a specification about the collection of links.


• The connections are related to classes.
• It is a general relationship between classes.
• They are implemented using programming languages as a reference model.
• It shows connections between classes using line segments.
• It is used in UML designs.

2. What is an abstract class? Is it possible that an abstract class


is inherited by another class?
Data abstraction is the process of hiding certain details and showing only essential information.
Abstraction can be achieved with either abstract classes or interfaces .The abstract keyword is
a non-access modifier, used for classes and methods:
• Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).
• Abstract method: can only be used in an abstract class, and it does not have a body. The body
is provided by the subclass (inherited from).

Yes you can inherit abstract class from another abstract class. Yes you can inherit or extend
one abstract class to another abstract class but if the class is a sealed class or single ton class
at that time only inheritance cant’ be applicable

3. Draw a state diagram for electric bulb.

4. When do we use the protected visibility specifier to class


member?

The protected access specifier allows the class the member belongs to, friends, and derived classes to
access the member. However, protected members are not accessible from outside the class.
5. When will you make a function name inline? Why?
We will make a function inline when the functions are small that called often. Inline functions
run a little faster than the normal functions as the compiler replaces the function call
statement with the function code itself and then compiles the entire code.

6. Define Destructor. Why do we use a destructor in a


program?
A destructor is called by the compiler when the object is destroyed and its main function is to
deallocate the memory of the object. Constructors have the same as of class while destructors
have the same name of the class with the prefix a tilde (~) operator.

Destructors are usually used to deallocate memory and do other cleanup for a class object and
its class members when the object is destroyed. A destructor is called for a class object when that
object passes out of scope or is explicitly deleted.

7. What is the use of Scope resolution operator?


The :: (scope resolution) operator is used to qualify hidden names so that you can still use
them. You can use the unary scope operator if a namespace scope or global scope name is
hidden by an explicit declaration of the same name in a block or class.

8. What is the candidate key?


Candidate key is a single key or a group of multiple keys that uniquely identify rows in a
table. A Candidate key is a subset of Super keys and is devoid of any unnecessary attributes
that are not important for uniquely identifying tuples

9. What is the use of friend function in c++?


In object-oriented programming, a friend function, that is a "friend" of a given class, is a function that
is given the same access as methods to private and protected data. A friend function is declared by the
class that is granting access, so friend functions are part of the class interface, like methods. A friend
function is a function that isn't a member of a class but has access to the class's private and protected
members. Friend functions aren't considered class members; they're normal external functions that are
given special access privileges.

10. What is information Hiding?


Information hiding is the process of hiding the details of an object or function. The hiding of
these details results in an abstraction, which reduces the external complexity and makes the
object or function easier to use.

Section B
II. Attempt any three part of the following:
a) What is constructor ? Write down the different
characteristics of a constructor. Write a program
in C++ for constructor overloading.
A constructor can be defined as a special member function which is used to initialize the objects
of the class with initial values. It is special member function as its name is the same as the class
name. It enables an object to initialize itself during its creation. This is termed as automatic
initialization of objects.

Features of constructors:
Constructor have following special features:
1. A constructor name must be same as that of its class name.
2. Constructors are called automatically when the objects are created.
3. Constructors should be declared in the public section to be availabile to all the
functions.
4. Constructors do not have return type , not even void and therefore they can not return
value.
5. Constructors can have default arguments as other C++ functions.
6. Constructors can not be inherited.
7. Constructors can not be static.
8. Constructors can not be virtual.
9. The address of a constructor can not be referred.
10. Constructors are member functions so they can be overloaded.

• class Person {
• private:
• int age;

• public:
• // 1. Constructor with no arguments
• Person() {
• age = 20;
• }

• // 2. Constructor with an argument
• Person(int a) {
• age = a;
• }

• int getAge() {
• return age;
• }
• };

• int main() {
• Person person1, person2(45);

• cout << "Person1 Age = " << person1.getAge() << endl;
• cout << "Person2 Age = " << person2.getAge() << endl;

• return 0;
• }

b) What is an inline function? Why do we use inline


function in our program? Write a program in C++
for inline function.
C++ programming language provides various important and fascinating methods and in-built
functions to its users. When it comes to enhancing the performance of the program, the inline
function proves to be an excellent concept. Inline function in C++ is an enhancement feature
that improves the execution time and speed of the program. The main advantage of inline
functions is that you can use them with C++ classes as well.

When an instruction of a function call is encountered during the compilation of a program, its
memory address is stored by the compiler. The function arguments are copied on the stack
and after the execution of the code, the control is transferred to the calling instruction. This
process can sometimes cause overhead in function calls, especially if the function is small
and its execution time is less than the switching time. This issue is resolved by using the
inline functions. These functions overcome the overhead and also make the program faster by
reducing the execution time of the program.

In case of inline functions, the compiler does not go through the above process of switching
between the stack and calling function. Instead, it copies the definition of the inline function
and the calling instruction with that definition. The following demonstration illustrates the
working of inline function in C++:

// define an inline function

// that prints the sum of 2 integers

inline void printSum(int num1,int num2) {

cout << num1 + num2 << "\n";

int main() {
// call the inline function

// first call

printSum(10, 20);

// second call

printSum(2, 5);

// third call

printSum(100, 400);

return 0;

Following are some key points that you need to keep in mind while dealing with inline
functions:

• Inline functions that are small have higher efficiency and better results than the lengthier
inline functions. So, try to keep your inline functions small in length.

• Although these functions increase the efficiency of the program and improve its
execution, you should not convert all the functions into inline functions. If you convert
larger functions to inline, it may lead to code bloat and reduce the functioning quality of
the program.

• Always try to define large functions outside the class, since functions defined inside a
class are automatically defined as inline and this will affect the program negatively. You
can use scope resolution (::) for this purpose.

c) Explain object oriented programming. What are


the main advantages of object oriented
programming over procedural programming ?
Write a program in C++ by creating a class
integer and write a function that prints all prime
numbers from the class.
Object-oriented programming – As the name suggests uses objectsin programming.
Object-oriented programming aims to implement real-world entities like inheritance,
hiding, polymorphism, etc in programming. The main aim of OOP is to bind together
the data and the functions that operate on them so that no other part of the code can
access this data except that function.
The main advantages of object oriented programming over procedural programming: : The
Classes & Objects
An object is a basic unit in object-oriented programing. An object contains data and methods or
functions that operate on that data. Objects take up space in memory.

A class, on the other hand, is a blueprint of the object. Conversely, an object can be defined as an
instance of a class. A class contains a skeleton of the object and does not take any space in the
memory.

Let us take an Example of a car object. A car object named “Maruti” can have data such as color;
make, model, speed limit, etc. and functions like accelerate. We define another object “ford”.
This can have similar data and functions like that of the previous object plus some more
additions.
Similarly, we can have numerous objects of different names having similar data and functions
and some minor variations.

Thus instead of defining these similar data and functions in these different objects, we define a
blueprint of these objects which is a class called Car. Each of the objects above will be instances
of this class car.

Abstraction
Abstraction is the process of hiding irrelevant information from the user. For Example, when we
are driving the car, first we start the engine by inserting a key. We are not aware of the process
that goes on in the background for starting the engine.
Using abstraction in programming, we can hide unnecessary details from the user. By using
abstraction in our application, the end user is not affected even if we change the internal
implementation.

Encapsulation
Encapsulation is the process using which data and the methods or functions operating on them are
bundled together. By doing this, data is not easily accessible to the outside world. In OOP we
achieve encapsulation by making data members as private and having public functions to access
these data members.

Inheritance
Using inheritance object of one class can inherit or acquire the properties of the object of another
class. Inheritance provides reusability of code.

As such we can design a new class by acquiring the properties and functionality of another class
and in this process, we need not modify the functionality of the parent class. We only add new
functionality to the class.

Polymorphism
Polymorphism means many forms.
Polymorphism is an important feature of OOP and is usually implemented as operator
overloading or function overloading. Operator overloading is a process in which an operator
behaves differently in different situations. Similarly, in function overloading, the same function
behaves differently in different situations.

Dynamic Binding
OOP supports dynamic binding in which function call is resolved at runtime. This means that the
code to be executed as a result of a function call is decided at runtime. Virtual functions are an
example of dynamic binding.

Message Passing
In OOP, objects communicate with each other using messages. When objects communicate,
information is passed back and forth between the objects. A message generally consists of the
object name, method name and actual data that is to be sent to another object.

Advantages Of OOP
#1) Reusability
OOP allows the existing code to be reused through inheritance. We can easily acquire the existing
functionality and improve on it without having to rewrite the code again. This results in less
bloated code.

#2) Modularity
As we modularize the program in OOP, it’s easy to modify or troubleshoot the program if a
problem occurs or new feature or enhancement is to be added. Modularization also helps in code
clarity and makes it more readable.

#3) Flexibility
OOP helps us with flexible programming using the polymorphism feature. As polymorphism
takes many forms, we can have operators or functions that will work with many objects and thus
save us from writing different functions for each object.

#4) Maintainability
Maintaining code is easier as it is easy to add new classes, objects, etc without much restructuring
or changes.

#5) Data and Information Hiding


OOP aids us in data hiding thereby keeping information safe from leaking. Only the data that is
required for the smooth functioning of the program are exposed to the user by hiding intrinsic
details.

#include <iostream>
using namespace std;

bool check_prime(int);

int main() {

int n;
cout << "Enter a positive integer: ";
cin >> n;

if (check_prime(n))
cout << n << " is a prime number.";
else
cout << n << " is not a prime number.";

return 0;
}

bool check_prime(int n) {
bool is_prime = true;

// 0 and 1 are not prime numbers


if (n == 0 || n == 1) {
is_prime = false;
}

for (int i = 2; i <= n / 2; ++i) {


if (n % i == 0) {
is_prime = false;
break;
}
}

return is_prime;
}

d) Explain all basic concepts of Object oriented


programming.
• Object-oriented programming has four basic concepts: encapsulation, abstraction,
inheritance and polymorphism. While these concepts may seem complex,
understanding the general framework of how they work will help you understand the
basics of an OOP computer program.
• 1. Encapsulation
• The word “encapsulate” means to enclose something. Just like a pill "encapsulates" or
contains the medication inside its coating, encapsulation works in a similar way in
OOP: by forming a protective barrier around the information contained within a class
from the rest of the code.
• In OOP, we encapsulate by binding the data and functions that operate on that data
into a single unit known as the class. This hides private details of a class from the
outside world and only exposes functionality important for interfacing with it. When a
class does not allow calling code access to its private data directly, we say that it is
well encapsulated.
• Example
• Elaborating on the person class example from earlier, we might have private data in
the class, such as "socialSecurityNumber," that should not be exposed to other objects
in the program. By encapsulating this data member as a private variable in the class,
outside code would not have direct access and it would remain safe within that
person’s object.
• If a method is written in the person class to perform, say, a bank transaction called
"bankTransaction()," that function could then access the "socialSecurityNumber"
variable as necessary. The person’s private data would be well encapsulated in such a
class.
• 2. Abstraction
• Often, it’s easier to reason and design a program when you can separate the interface
of a class from its implementation, and focus on the interface. This is akin to treating
a system as a “black box,” where it’s not important to understand the gory inner
workings in order to reap the benefits of using it.
• This process is called “abstraction” in OOP because we are abstracting away the
implementation details of a class and only presenting a clean, easy-to-use interface via
the class’s member functions. Carefully used, abstraction helps isolate the impact of
changes made to the code so that if something goes wrong, the change will only affect
the implementation details of a class and not the outside code.
• Example
• Think of a stereo system as an object with a complex logic board on the inside. It has
buttons on the outside to allow for interaction with the object. When you press a
button, you're not thinking about what happens on the inside because you can't see it.
Even though you can't see the logic board completing these functions as a result of
pressing a button, it's still performing them.
• This is the concept of abstraction, which is incredibly useful in all areas of
engineering and also applied to great effect in object-oriented programming.
• Example
• In OOP, we might have a class defined to represent the human body. One might
define some functions as part of its publicly facing interface such as “walk()” or
“eatFood().” Calling code could call these functions and remain completely oblivious
to the complex inner workings of the human body and its necessary functions to
perform the act of walking or eating. These details are completely hidden in the
implementation of the walk() and eatFood() body functions and are abstracted away
from the end-user. In these cases, it’s not important for calling code to understand
how the brain coordinates walking or how the stomach manages digesting the food
but rather simply that a human walked or ate.
• 3. Inheritance
• Object-oriented languages that support classes almost always support the notion of
“inheritance.” Classes can be organized into hierarchies where a class might have one
or more parent or child classes. If a class has a parent class, we say it is derived or
inherited from the parent class and it represents an “IS-A” type relationship. That is to
say, the child class “IS-A” type of the parent class.
• Therefore, if a class inherits from another class, it automatically obtains much of the
same functionality and properties from that class and can be extended to contain
separate code and data. A nice feature of inheritance is that it often leads to good code
reuse since a parent class’s functions don’t need to be re-defined in any of its child
classes.
• Consider two classes: one being the superclass—or parent—and the other being the
subclass—or child. The child class will inherit the properties of the parent class,
possibly modifying or extending its behavior. Programmers applying the technique of
inheritance arrange these classes into what is called an “IS-A” type of relationship.
• Example
• For instance, in the animal world, an insect could be represented by an Insect
superclass. All insects share similar properties, such as having six legs and an
exoskeleton. Subclasses might be defined for grasshoppers and ants. Because they
inherit or are derived from the Insect class, they automatically share all insect
properties.
• 4. Polymorphism
• In OOP, polymorphism allows for the uniform treatment of classes in a hierarchy.
Therefore, calling code only needs to be written to handle objects from the root of the
hierarchy, and any object instantiated by any child class in the hierarchy will be
handled in the same way.
• Because derived objects share the same interface as their parents, the calling code can
call any function in that class’ interface. At run-time, the appropriate function will be
called depending on the type of object passed leading to possibly different behaviors.
• Example
• Suppose we have a class called, “Animal” and two child classes, “Cat,” and “Dog.” If
the Animal class has a method to make a noise, called, “makeNoise,” then, we can
override the "makeNoise" function that is inherited by the sub-classes, "Cat" and
"Dog," to be “meow” and “bark,” respectively. Another function can, then, be written
that accepts any Animal object as a parameter and invokes its "makeNoise" member
function. The noise will be different: either a “meow” or a “bark” depending on the
type of animal object that was actually passed to the function.

e) What is an inheritance? Explain the


different types of it. Write a program in
C++ for multiple inheritance.
Inheritance is one of four pillars of Object-Oriented Programming (OOPs). It is a feature that
enables a class to acquire properties and characteristics of another class. Inheritance allows
you to reuse your code since the derived class or the child class can reuse the members of the
base class by inheriting them. Consider a real-life example to clearly understand the concept
of inheritance. A child inherits some properties from his/her parents, such as the ability to
speak, walk, eat, and so on. But these properties are not especially inherited in his parents
only. His parents inherit these properties from another class called mammals. This mammal
class again derives these characteristics from the animal class. Inheritance works in the same
manner.

During inheritance, the data members of the base class get copied in the derived class and can
be accessed depending upon the visibility mode used. The order of the accessibility is always
in a decreasing order i.e., from public to protected. There are mainly five types of Inheritance
in C++ that you will explore in this article. They are as follows:
• Single Inheritance

• Multiple Inheritance

• Multilevel Inheritance

• Hierarchical Inheritance

• Hybrid Inheritance

• #include <iostream>
• using namespace std;

• // create a base class1
• class Base_class
• {
• // access specifier
• public:
• // It is a member function
• void display()
• {
• cout << " It is the first function of the Base class " << endl;
• }
• };

• // create a base class2
• class Base_class2
• {
• // access specifier
• public:
• // It is a member function
• void display2()
• {
• cout << " It is the second function of the Base class " << endl;
• }
• };

• /* create a child_class to inherit features of Base_class and Base_class2 with access s
pecifier. */
• class child_class: public Base_class, public Base_class2
• {

• // access specifier
• public:
• void display3() // It is a member function of derive class
• {
• cout << " It is the function of the derived class " << endl;
• }

• };

• int main ()
• {
• // create an object for derived class
• child_class ch;
• ch.display(); // call member function of Base_class1
• ch.display2(); // call member function of Base_class2
• ch.display3(); // call member function of child_class
• }

Section C
III. Attempt any one part of the following:
a) What is polymorphism? Differentiate between
runtime polymorphism and compile time
polymorphism.
• Polymorphism is one of the most important OOPs concepts. Its is a concept by which
we can perform single task in multiple ways. There are two types of polymorphism one
is Compile-time polymorphism and another is run-time polymorphism.
• Method overloading is the example of compile time polymorphism and method
overriding is the example of run-time polymorphism.

Sr. Key Compile-time Runtime


No. polymorphism polymorphism

1 Basic Compile time R un time


polymorphism means polymorphism where at
binding is occuring at run time we came to
compile time know which method is
going to invoke
Sr. Key Compile-time Runtime
No. polymorphism polymorphism

2 Static/DynamicBinding It can be achieved It can be achieved


through static through dynamic
binding binding

4. Inheritance Inheritance is not Inheritance is involved


involved

5 Example Method overloading Method overriding is an


is an example of example of runtime
compile time polymorphism
polymorphism

b) What is operator overloading? Write a program


in C++ for binary operator overloading.
An operator which contains two operands to perform a mathematical operation
is called the Binary Operator Overloading. It is a polymorphic compile
technique where a single operator can perform various functionalities by
taking two operands from the programmer or user. There are multiple binary
operators like +, -, *, /, etc., that can directly manipulate or overload the object
of a class.
1. #include <iostream>
2. using namespace std;
3. class Complex_num
4. {
5. // declare data member or variables
6. int x, y;
7. public:
8. // create a member function to take input
9. void inp()
10. {
11. cout << " Input two complex number: " << endl;
12. cin >> x >> y;
13. }
14. // use binary '+' operator to overload
15. Complex_num operator + (Complex_num obj)
16. {
17. // create an object
18. Complex_num A;
19. // assign values to object
20. A.x = x + obj.x;
21. A.y = y + obj.y;
22. return (A);
23. }
24. // overload the binary (-) operator
25. Complex_num operator - (Complex_num obj)
26. {
27. // create an object
28. Complex_num A;
29. // assign values to object
30. A.x = x - obj.x;
31. A.y = y - obj.y;
32. return (A);
33. }
34. // display the result of addition
35. void print()
36. {
37. cout << x << " + " << y << "i" << "\n";
38. }
39.
40. // display the result of subtraction
41. void print2()
42. {
43. cout << x << " - " << y << "i" << "\n";
44. }
45. };
46. int main ()
47. {
48. Complex_num x1, y1, sum, sub; // here we created object of class Addition i.e x1 and y1
49. // accepting the values
50. x1.inp();
51. y1.inp();
52. // add the objects
53. sum = x1 + y1;
54. sub = x1 - y1; // subtract the complex number
55. // display user entered values
56. cout << "\n Entered values are: \n";
57. cout << " \t";
58. x1.print();
59. cout << " \t";
60. y1.print();
61. cout << "\n The addition of two complex (real and imaginary) numbers: ";
62. sum.print(); // call print function to display the result of addition
63. cout << "\n The subtraction of two complex (real and imaginary) numbers: ";
64. sub.print2(); // call print2 function to display the result of subtraction
65. return 0;
66. }

IV. Attempt any one part of the following:


a) A farmer wants to cross the river along with a
bag of grass , goat, and a lion . Only one things
can be carried in the boat at a time. If the boat is
left alone with a grass will be eaten.If the goat is
left along with a ion , the goat will be eaten.
1) Prepare a scenario in which everything is
safely transport4ed across the river.
2) Prepare the event trace diagram for the
above problem.

b) Define the term multiplicity and quantification.


• n UML, multiplicity describes how many instances of one class can be connected to
an instance of another class through a given association. This relation is often
expressed as a string showing the lower and upper bounds at the endpoints of a
connection.
• Let's look at an example from a hypothetical banking system. In our system, each
customer must have at least one account at our bank and should not have more than
five accounts in total. We could model this with the following UML association:

• Multiplicity in a UML diagram
• The text 1 .. 5 placed at the connection's end defines the range of possible accounts. To
interpret this diagram, we would start reading from left to right :
• One customer must have between one and five bank accounts
• (note that the cardinality of the customer - "one" - is not explicitly modeled in the diagram)
• But that's not all: We can also describe the relation between bank accounts and
customers. Let's say that every account must belong to at least one customer, but for
joint accounts, it could also have two owners:


• Multiplicity in the reverse direction
• Here we had to place the lower and upper bound on the other end, and consequently,
we must now read from right to left:
• One bank account must belong to one up to two customers*.
• Again, the diagram does not contain the cardinality of "one" for the bank account.

Finally, we can combine both multiplicities into the same diagram to express both
directions:


• Both multiplicities combined in a single diagram
• It's essential to keep in mind that this diagram combines the two expressions
mentioned above into a single diagram, so the correct way to read it would be:
• One customer has one to five bank accounts and one bank account belongs to one or
two customers.
• and not, as one would intuitively think
• One or two customers have one to five bank accounts.

• Multiplicity in UMLBoard
• 1.4
• UMLBoard supports the definition of multiplicities for all associations (i.e.,
compositions, aggregations, and simple associations). By default, a newly created
relationship does not have any multiplicity information stored, indicated by the
grayed-out text none when moving the mouse over a connection.


• A connection in UMLBoard without any multiplicity set

• Start Editing
• To add a multiplicity to a connection, click and hold (or double-click) on one of
the none texts. The cardinality editor will open with the cursor always starting on the
edit field for the lower bound.


• The cardinality editor can be opened by clicking on a multiplicity
• Just enter any cardinality you want; UMLBoard does not set you any restrictions here.
You can use any number or arbitrary string as input. If you only want to set a single
boundary, you can also leave one cardinality edit field empty. Clearing both edit
fields will remove the multiplicity from this end.

V. Attempt any one part of the following:


a) What is UML ?List all basic building blocks of
UML. Explain all types of things used in UML.
UML is a standard language for specifying, visualizing, constructing, and documenting the
artifacts of software systems.
UML was created by the Object Management Group (OMG) and UML 1.0 specification draft
was proposed to the OMG in January 1997.
OMG is continuously making efforts to create a truly industry standard.
• UML stands for Unified Modeling Language.
• UML is different from the other common programming languages such as C++, Java,
COBOL, etc.
• UML is a pictorial language used to make software blueprints.
• UML can be described as a general purpose visual modeling language to visualize,
specify, construct, and document software system.

UML describes the real-time systems, it is very important to make a conceptual model and then
proceed gradually. The conceptual model of UML can be mastered by learning the following
three major elements −

• UML building blocks


• Rules to connect the building blocks
• Common mechanisms of UML
This chapter describes all the UML building blocks. The building blocks of UML can be
defined as −

• Things
• Relationships
• Diagrams

Things
Things are the most important building blocks of UML. Things can be −

• Structural
• Behavioral
• Grouping
• Annotational
Structural Things
Structural things define the static part of the model. They represent the physical and
conceptual elements. Following are the brief descriptions of the structural things.
Class − Class represents a set of objects having similar responsibilities.

Interface − Interface defines a set of operations, which specify the responsibility of a class.

Collaboration −Collaboration defines an interaction between elements.


Use case −Use case represents a set of actions performed by a system for a specific goal.

Component −Component describes the physical part of a system.

Node − A node can be defined as a physical element that exists at run time.

Behavioral Things
A behavioral thing consists of the dynamic parts of UML models. Following are the
behavioral things −
Interaction − Interaction is defined as a behavior that consists of a group of messages
exchanged among elements to accomplish a specific task.

State machine − State machine is useful when the state of an object in its life cycle is
important. It defines the sequence of states an object goes through in response to events. Events
are external factors responsible for state change

Grouping Things
Grouping things can be defined as a mechanism to group elements of a UML model together.
There is only one grouping thing available −
Package − Package is the only one grouping thing available for gathering structural and
behavioral things.
Annotational Things
Annotational things can be defined as a mechanism to capture remarks, descriptions, and
comments of UML model elements. Note - It is the only one Annotational thing available. A
note is used to render comments, constraints, etc. of an UML element.

Relationship
Relationship is another most important building block of UML. It shows how the elements are
associated with each other and this association describes the functionality of an application.
There are four kinds of relationships available.
Dependency
Dependency is a relationship between two things in which change in one element also affects
the other.

Association
Association is basically a set of links that connects the elements of a UML model. It also
describes how many objects are taking part in that relationship.

Generalization
Generalization can be defined as a relationship which connects a specialized element with a
generalized element. It basically describes the inheritance relationship in the world of objects.
Realization
Realization can be defined as a relationship in which two elements are connected. One element
describes some responsibility, which is not implemented and the other one implements them.
This relationship exists in case of interfaces.

UML Diagrams
UML diagrams are the ultimate output of the entire discussion. All the elements, relationships
are used to make a complete UML diagram and the diagram represents a system.
The visual effect of the UML diagram is the most important part of the entire process. All the
other elements are used to make it complete.
UML includes the following nine diagrams, the details of which are described in the subsequent
chapters.

• Class diagram
• Object diagram
• Use case diagram
• Sequence diagram
• Collaboration diagram
• Activity diagram
• Statechart diagram
• Deployment diagram
• Component diagram
• Seven Types of Structural Things

1. Class - An object with defined attributes and operations. A class in


UML is very much like a class in C++.

2. Interface - A collection of functions that specify a service of a class


or component, i.e. externally visible behavior of that class.
3. Collaboration - A larger pattern of behaviors and actions. Example:
All classes and behaviors that create the modeling of a moving tank in
a simulation.

4. Use Case - A sequence of actions that a system performs that yields


an observable result. Used to structure behavior in a model. Is realized
by a collaboration.

5. Active Class - Like a class but its represents behavior that runs
concurrent with other behaviors, i.e. threading.

6. Component - A physical and replaceable part of a system that


implements a number of interfaces. Example: a set of classes,
interfaces, and collaborations.

7. Node - A physical element existing at run time and represents a


resource.

Two Types of Behavioral Things


1. Interaction - A behavior made up of a set of
messages exchanged among a set of objects in a
particular context to accomplish a specific purpose.

2. State Machine - A behavior that specifies the


sequences of states an object or interaction goes through
during its' lifetime in response to events.

One Type of Grouping Thing


1. Package - A general purpose mechanism for organizing elements into
groups.

One Type of Annotation Thing


1. Note - A symbol to display comments.

b) Explain Virtual base class with the help of an


example.
11. Virtual Class is defined by writing a keyword “virtual” in the derived classes which
allows only one copy of data to be copied to Class B and Class C (referring to the
above example). It is a way of preventing multiple instances of a class appearing as a
parent class in inheritance hierarchy when multiple inheritances are used.
12. Need for Virtual Base Class in C++
13. In order to prevent the error and let the compiler work efficiently, we’ve to use a
virtual base class when multiple inheritances occur. It saves space and avoids
ambiguity.
14. When a class is specified as a virtual base class, it prevents duplication of its data
members. Only one copy of its data members is shared by all the base classes that use
the virtual base class.
15. If a virtual base class is not used, then all the derived classes will get duplicated data
members. In this case, the compiler cannot decide which one to execute.
16. #include <iostream>
17. using namespace std;
18.
19. class A {
20. public:
21. void display() {
22. cout << "Hello form Class A \n";
23. }
24. };
25.
26. class B: public A {
27. };
28.
29. class C: public A {
30. };
31.
32. class D: public B, public C {
33. };
34.
35. int main() {
36. D object;
37. object.display();
38. }

VI. Attempt any one part of the following:


a)Discuss implicit and explicit type conversion in
detail.
Type conversion is the method of converting one data type to another. There are two types of
Type Conversions in C++:

• Implicit type conversion, and


• Explicit type conversion

Let's understand each one of them.

Implicit Type Conversion


The Implicit Type Conversion is that type conversion that is done automatically by the
compiler. It does not require any effort from the programmer. The C++ compiler has a set of
predefined rules. Based on these rules, the compiler automatically converts one data type to
another. Therefore, implicit type conversion is also known as automatic type conversion.

Data Loss During Conversion

When there is more than one data type present in an expression, there is a possibility of data
loss because different data types are not compatible with each other. Data loss occurs if a
variable converts from a higher data type to a lower data type. In order to avoid data loss, the
compiler automatically converts all the data types to the highest data type present in the
expression. This is called promotion. The precedence of different data types is given below.
For example:

#include <iostream>
using namespace std;

int main() {
int int_var;
float float_var = 20.5;

int_var = float_var;
// trying to store the value of float_var in int_var

cout << "The value of int_var is: " << int_var << endl;
cout << "The value of float_var is: " << float_var << endl;

return 0;
}

Output:

The value of int_var is: 20


The value of float_var is: 20.5

When a float is converted to int, the numbers after the decimal point are lost. This is why the
value 20.5 was converted to 20 when we tried to store a float value in an int variable.

Similarly, when a signed int is implicitly converted to an unsigned int, the sign of the integer
is lost.

Order of Typecast in Implicit Conversion

The following is the correct order of automatic type conversion from lower rank of data type
to higher rank of data type.

bool --> char --> short int --> int -->


unsigned int --> long --> unsigned long -->
long long --> float --> double --> long double

Let us take an example to understand implicit type conversion:

#include <iostream>
using namespace std;

int main() {
int int_var = 50;
char char_var = 'a';

int_var = int_var + char_var;


// char_var is implicitly converted to the integer ASCII of 'a'
// ASCII of 'a' is 97

cout << "The value of (50 + 'a') is: " << int_var << endl;

// Now, converting int_var to a float (implicitly)


float float_var = int_var * 1.5;

cout << "The value of float_var is: " << float_var << endl;

return 0;
}

Output:

The value of (50 + 'a') is: 147


The value of float_var is: 220.5
In the above example, we had three variables of different data types. In line 9, we added an
integer variable int_var and a character variable char_var. Because of this, the
value 'a' present in char_var implicitly converted to the (int) ASCII value of 'a', i.e. 97.
Hence, 50 and 97 were added, and 147 was stored in int_var. Similarly, in line 16, we
multiplied an integer and a float. The integer was implicitly converted to a float, and the
multiplication operation was performed.

Explicit Type Conversion


Explicit Type Conversions are those conversions that are done by the programmer manually.
In other words, explicit conversion allows the programmer to typecast (change) the data type
of a variable to another type. Hence, it is also called typecasting. Generally, we use the
explicit type conversion if we do not want to follow the implicit type conversion rules.

Explicit type conversion in C++ can be done in two ways:

1. Conversion using the Assignment Operator


2. Conversion using the Cast Operator

Let us take a look at each one of them.

Conversion Using the Assignment Operator

Explicit typecasting using the assignment operator is also referred to as forced casting. This
conversion is done by explicitly declaring the required data type in front of the expression. It
can be done in two ways:

1. C-style type casting:

This type casting is usually used in the C programming language. It is also known as cast
notation. The syntax for this casting is:

(datatype)expression;

For example:

#include <iostream>
using namespace std;

int main() {
char char_var = 'a';
int int_var;

// Explicitly converting a character variable to integer variable


int_var = (int) char_var; // Using cast notation

cout << "The value of char_var is: " << char_var << endl;
cout << "The value of int_var is: " << int_var << endl;
return 0;
}

Output:

The value of char_var is: a


The value of int_var is: 97

In this example, we explicitly converted a char variable into an int. The result being, the
character 'a' was converted to 97.

2. Function style casting

As the name suggests, we can perform explicit typecasting using function style notations. It is
also known as old C++ style type casting. The syntax for this casting is:

datatype(expression);

For example:

#include <iostream>
using namespace std;

int main() {
int int_var = 17;

float float_var;

float_var = float(int_var) / 2;
// explicitly converting an int to a float

cout << "The value of float_var is: " << float_var << endl;

return 0;
}

Output:

The value of float_var is: 8.5

b) Explain generalization, Aggregation and


association in detail.
Association is the semantic relationship between classes that shows how one instance is
connected or merged with others in a system. The objects are combined either logically or
physically. Since it connects the object of one class to the object of another class, it is
categorized as a structural relationship.
Reflexive Association
In the reflexive associations, the links are between the objects of the same classes. In other
words, it can be said that the reflexive association consists of the same class at both ends. An
object can also be termed as an instance.

Let's have a look at its example of a class vegetable. The vegetable class has two objects, i.e.,
onion and eggplant. According to the reflexive association's definition, the link between the
onion and eggplant exist, as they belong to the same class, i.e., vegetable.

Directed Association
The directed association is concerned with the direction of flow inside association classes.
The flow of association can be shown by employing a directed association. The directed
association between two classes is represented by a line with an arrowhead, which indicates
the navigation direction. The flow of association from one class to another is always in one
direction.
It can be said that there is an association between a person and the company. The
person works for the company. Here the person works for the company, and not
the company works for a person.

What is Aggregation in UML


An association represents the relationship between two objects. Aggregation is a type of
association. In other words, it is a special case of association. When an object “has-a” another
object, then we can consider it as an aggregation. Therefore, aggregation describes the “has a”
relationship between objects.

Figure 1: Aggregation
The employee and address are linked with the “has a” relationship. An instance of the Address
class can exist without an instance of the Employee. It is an aggregation. In UML, the diamond
symbol represents an aggregation. The direction denotes which object contains the other object.

What is Generalization in UML


Generalization is associated with inheritance, which is the process of allowing classes to use
the properties and methods of already existing classes. The existing class is the superclass while
the new class is the subclass. Generalization combines multiple classes into a general class.
Moreover, the superclass has the most general properties and methods. Subclasses can share
those properties and methods. Subclasses can have specialized properties and methods. As a
subclass is a type of super classes, the generalization represents “is a” relationship.

Figure 2: Generalization
Employee is the superclass. Permanent and Temporary Employee are subclasses whereas
Employee is the generalized form of Permanent and Temporary Employee. On the other hand,
Permanent and Temporary Employee are specialized forms of Employee. Employee has
properties id, name, salary and the method display. The subclasses Permanent and Temporary
Employee can also use these properties and methods. Furthermore, the subclasses have their
own properties and methods. In UML, an arrow represents generalization.

Difference Between Aggregation and Generalization


in UML
Definition
Aggregation is an association between two objects which describes the “has a” relationship
while generalization is a mechanism for combining similar classes of objects into a single
general class. Thus, this explains the main difference between aggregation and generalization
in UML.

Relationship
Aggregation denotes “has a” relationship while Generalization denotes “is a” relationship.
UML representation
A diamond symbol represents an aggregation whereas an arrow symbol represents
generalization. Hence, this further explains the difference between aggregation and
generalization in UML.

VII. Attempt any one part of the following:


a) What is friend function in C++? Write a
program in C++ to implement friend function .
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. }

Output:

Length of box: 10

Let's see a simple example when the function is friendly to two classes.

1. #include <iostream>
2. using namespace std;
3. class B; // forward declarartion.
4. class A
5. {
6. int x;
7. public:
8. void setdata(int i)
9. {
10. x=i;
11. }
12. friend void min(A,B); // friend function.
13. };
14. class B
15. {
16. int y;
17. public:
18. void setdata(int i)
19. {
20. y=i;
21. }
22. friend void min(A,B); // friend function
23. };
24. void min(A a,B b)
25. {
26. if(a.x<=b.y)
27. std::cout << a.x << std::endl;
28. else
29. std::cout << b.y << std::endl;
30. }
31. int main()
32. {
33. A a;
34. B b;
35. a.setdata(10);
36. b.setdata(20);
37. min(a,b);
38. return 0;
39. }

Output:

10

In the above example, min() function is friendly to two classes, i.e., the min() function can
access the private members of both the classes A and B.
b) Explain the following concepts in C++ by taking
a suitable example:
1) This pointer
2) Array of objects
This pointer

• Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the invoking object.
• Friend functions do not have a this pointer, because friends are not members of a class.
Only member functions have a this pointer.
• Let us try the following example to understand the concept of this pointer −
• Live Demo
• #include <iostream>

• using namespace std;

• class Box {
• public:
• // Constructor definition
• Box(double l = 2.0, double b = 2.0, double h = 2.0) {
• cout <<"Constructor called." << endl;
• length = l;
• breadth = b;
• height = h;
• }
• double Volume() {
• return length * breadth * height;
• }
• int compare(Box box) {
• return this->Volume() > box.Volume();
• }

• private:
• double length; // Length of a box
• double breadth; // Breadth of a box
• double height; // Height of a box
• };

• int main(void) {
• Box Box1(3.3, 1.2, 1.5); // Declare box1
• Box Box2(8.5, 6.0, 2.0); // Declare box2

• if(Box1.compare(Box2)) {
• cout << "Box2 is smaller than Box1" <<endl;
• } else {
• cout << "Box2 is equal to or larger than Box1" <<endl;
• }

• return 0;
• }

Array of objects
suppose we have 50 students in a class and we have to input the name and marks of all the 50
students. Then creating 50 different objects and then inputting the name and marks of all
those 50 students is not a good option. In that case, we will create an array of objects as we
do in case of other data-types.
Let's see an example of taking the input of name and marks of 5 students by creating an array
of the objects of students.

#include <iostream>
#include <string>

using namespace std;

class Student
{
string name;
int marks;
public:
void getName()
{
getline( cin, name );
}
void getMarks()
{
cin >> marks;
}
void displayInfo()
{
cout << "Name : " << name << endl;
cout << "Marks : " << marks << endl;
}
};

int main()
{
Student st[5];
for( int i=0; i<5; i++ )
{
cout << "Student " << i + 1 << endl;
cout << "Enter name" << endl;
st[i].getName();
cout << "Enter marks" << endl;
st[i].getMarks();
}

for( int i=0; i<5; i++ )


{
cout << "Student " << i + 1 << endl;
st[i].displayInfo();
}
return 0;
}

Output
Now let’s go through this code.
Student st[5]; - We created an array of 5 objects of the Student class where each object
represents a student having a name and marks.
The first for loop is for taking the input of name and marks of the
students. getName() and getMarks() are the functions to take the input of name and marks
respectively.
The second for loop is to print the name and marks of all the 5 students. For that, we called
the displayInfo() function for each student.

You might also like