Oodp Unit 1

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

Comparison of Procedural and Object Oriented Programming

S.no. On the basis Procedural Programming Object-oriented programming


of
1. Definition It is a programming language that is Object-oriented programming is a
derived from structure programming computer programming design
and based upon the concept of calling philosophy or methodology that
procedures. It follows a step-by-step organizes/ models software design
approach in order to break down a around data or objects rather than
task into a set of variables and functions and logic.
routines via a sequence of
instructions.
2. Security It is less secure than OOPs. Data hiding is possible in object-oriented
programming due to abstraction. So, it is
more secure than procedural
programming.
3. Approach It follows a top-down approach. It follows a bottom-up approach.
4. Data In procedural programming, data In OOP, objects can move and
movement moves freely within the system from communicate with each other via
one function to another. member functions.
5. Orientation It is structure/procedure-oriented. It is object-oriented.
6. Access There are no access modifiers in The access modifiers in OOP are named
modifiers procedural programming. as private, public, and protected.
7. Inheritance Procedural programming does not There is a feature of inheritance in object-
have the concept of inheritance. oriented programming.
8. Code There is no code reusability present in It offers code reusability by using the
reusability procedural programming. feature of inheritance.
9. Overloading Overloading is not possible in In OOP, there is a concept of function
procedural programming. overloading and operator overloading.
10. Importance It gives importance to functions over It gives importance to data over
data. functions.
11. Virtual class In procedural programming, there are In OOP, there is an appearance of virtual
no virtual classes. classes in inheritance.
12. Complex It is not appropriate for complex It is appropriate for complex problems.
problems problems.
13. Data hiding There is not any proper way for data There is a possibility of data hiding.
hiding.
14. Program In Procedural programming, a In OOP, a program is divided into small
division program is divided into small parts that are referred to as objects.
programs that are referred to as
functions.
15. Examples Examples of Procedural The examples of object-oriented
programming include C, Fortran, programming are -
Pascal, and VB. .NET, C#, Python, Java, VB.NET, and
C++.
Object Oriented Programming Features in C++
1. Class
2. Objects
3. Encapsulation
4. Abstraction
5. Polymorphism
6. Inheritance
7. Dynamic Binding
8. Message Passing
Object-oriented programming – As the name suggests uses objects in 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.

Class: The building block of C++ that leads to Object-Oriented programming is a Class. It is
a user-defined data type, which holds its own data members and member functions, which can
be accessed and used by creating an instance of that class. A class is like a blueprint for an
object.

For Example: Consider the Class of Cars. There may be many cars with different names and
brand but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits, mileage are
their properties.
• A Class is a user-defined data-type which has data members and member functions.
• Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions
define the properties and behaviour of the objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage etc and
member functions can apply brakes, increase speed etc.
We can say that a Class in C++ is a blue-print representing a group of objects which shares
some common properties and behaviours.
Object: An Object is an identifiable entity with some characteristics and behaviour. An Object
is an instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
class person
{
char name[20];
int id;
public:
void getdetails(){}
};

int main()
{
person p1; // p1 is a object
}
Object take up space in memory and have an associated address like a record in pascal or
structure or union in C.

When a program is executed the objects interact by sending messages to one another.

Each object contains data and code to manipulate the data. Objects can interact without having
to know details of each other’s data or code, it is sufficient to know the type of message
accepted and type of response returned by the objects.

Encapsulation: In normal terms, Encapsulation is defined as wrapping up of data and


information under a single unit. In Object-Oriented Programming, Encapsulation is defined as
binding together the data and the functions that manipulate them.

Consider a real-life example of encapsulation, in a company, there are different sections like
the accounts section, finance section, sales section etc. The finance section handles all the
financial transactions and keeps records of all the data related to finance. Similarly, the sales
section handles all the sales-related activities and keeps records of all the sales. Now there may
arise a situation when for some reason an official from the finance section needs all the data
about sales in a particular month. In this case, he is not allowed to directly access the data of
the sales section. He will first have to contact some other officer in the sales section and then
request him to give the particular data. This is what encapsulation is. Here the data of the sales
section and the employees that can manipulate them are wrapped under a single name “sales
section”.
Encapsulation in C++
Encapsulation also leads to data abstraction or hiding. As using encapsulation also hides the
data. In the above example, the data of any of the section like sales, finance or accounts are
hidden from any other section.

Abstraction: Data abstraction is one of the most essential and important features of object-
oriented programming in C++. Abstraction means displaying only essential information and
hiding the details. Data abstraction refers to providing only essential information about the data
to the outside world, hiding the background details or implementation.

Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of the car or applying brakes will stop the car but he does
not know about how on pressing accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of accelerator, brakes etc in the
car. This is what abstraction is.

Abstraction using Classes: We can implement Abstraction in C++ using classes. The class
helps us to group data members and member functions using available access specifiers. A
Class can decide which data member will be visible to the outside world and which is not.
Abstraction in Header files: One more type of abstraction in C++ can be header files. For
example, consider the pow() method present in math.h header file. Whenever we need to
calculate the power of a number, we simply call the function pow() present in the math.h header
file and pass the numbers as arguments without knowing the underlying algorithm according
to which the function is actually calculating the power of numbers.
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 person at the same time can have different characteristic. Like a man at the same time is a
father, a husband, an employee. So the same person posses different behaviour in different
situations. This is called polymorphism.

An operation may exhibit different behaviours in different instances. The behaviour depends
upon the types of data used in the operation.

C++ supports operator overloading and function overloading.

Operator Overloading: The process of making an operator to exhibit different behaviours in


different instances is known as operator overloading.
Function Overloading: Function overloading is using a single function name to perform
different types of tasks.
Polymorphism is extensively used in implementing inheritance.
Example: Suppose we have to write a function to add some integers, some times there are 2
integers, some times there are 3 integers. We can write the Addition Method with the same
name having different parameters, the concerned method will be called according to
parameters.
Inheritance: The capability of a class to derive properties and characteristics from another
class is called Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming.

Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class.
Super Class:The class whose properties are inherited by sub class is called Base Class or Super
class.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.

Example
Example:
1. class ABC : private XYZ //private derivation
{
};
2. class ABC : public XYZ //public derivation
{
};
3. class ABC : protected XYZ //protected derivation
{
};
4. class ABC: XYZ //private derivation by default
{
};

Dynamic Binding: In dynamic binding, the code to be executed in response to function call is
decided at runtime. C++ has virtual functions to support this.
Message Passing: Objects communicate with one another by sending and receiving information
to each other. A message for an object is a request for execution of a procedure and therefore
will invoke a function in the receiving object that generates the desired results. Message passing
involves specifying the name of the object, the name of the function and the information to be
sent.
I/O operation in c++
Input ;Information given to the program, is called input. In input data is flow inside the program
It required a source(for reading )
Output : Information given by the program is called output.In output data is flow outside the
program
In c++ I/O operations are alone using streams
A stream is class is provide set of functions to perform input and output operations A
stream represents input source (reading) and output destination (writing) C++ provides 2
stream classes
1. ostream
2. istream
Istream: The istream consists of input functions to read a streams of characters from the
keyboard.
Ostream : The ostream consists of output functions to write a character onto the screen.
Cout -> It is a predefined object of class Ostream
Cout represent console output
Cout represent standard output devise (Monitor)
For cout object destination is standard output device
Ostream cout(“ con ”);
This predefined object is a variable in IOstream.h file
This object uses << (insertion) operator to perform formatted output operation
This object uses all the member function of stream class to perform output operation << (
insertion operator) is overloaded operation on member function
Insertion means writing / printing Cout << ’10,20 ; // it will print 10
Syntax : cout<< variable/constant/expression;
In order to print multiple values cout uses multiple insertion operators.
Cout<value 1<value2<value 3…….
Using multiple insertion operator with cout is called cascading , it is a method of organizing
evaluation of insertion operators are done from right to left and insertion is done from left to
right
Example :
# include<iostream.h>
void main()
{
cout<< “welcome to c++”<<endl;;
}

endl : It is a manipulator used for inserting new line

Cin : It is an object of istream class.


istream class provide set of functions to performs input operations
Cin uses >> (extraction) operation to read any type of value
It does not required any formatting specifiers
Formatting is an implicit functionality of extract of operation
It is an overloaded operation // reading (source) writing Cdestination which extend
functionality of >> (shift operator)
syntax :
Cin >> variable –name;
One extraction operator read only one value
cin>>var1>>var2>>var3----
Using multiple extraction is called as cascading
Variable (local) :
The variable declared inside function is called local variable.
Memory for this variable is allocated on execution of function and after completion of function
The scope of this variable within function
Local variable are called auto variable.
Auto is storage class and variable is never declared without class
Storage class define scope life time and storage of variable.
Eg :
#include<iostream.h>
void main()
{
int x;
int Y;
int Z;
Cout << X << endl;
cout<<Z<<endl;
}
o/p : The output of above program is garbage value, Because local variables are not given any
default values.
C++ allows to declare local variable anywhere within function
Static Variable
When the static keyword preceded the declaration of a variable, that variable becomes a static
variable.
Syntax:
static <type> <variable_name>;
A static keyword serves a different purpose depending on where it has been declared.
• If it is declared inside of a class, all instances of the class (i.e. objects) will share the
same copy of the variable, and we can access it without any object by class name outside
the class.
• If it is declared inside of a function then its value is preserved between successive calls
for the lifetime of the program, but it cannot be accessd outside the scope or function
in which it is declared.
Example 1: Static Variable inside of a Class
#include <iostream>
using namespace std;
class Natural{
public:
static int num;

void increase(){
++num;
}
};
/*
*It is important to initialize the static variable outside of a class
*we do so by using the class name and scope resolution operator.
*/
int Natural::num = 0;

int main()
{
//Creating 1st object
Natural obj1;

//Incrementing Natural::num 2 times


obj1.increase();
obj1.increase();

cout << "Num of 1st Object: "<< obj1.num << endl;

//Creating 2nd object


Natural obj2;

cout << "Num of 2nd Object: "<< obj2.num << endl;

return 0;
}
Output:

Num of 1st Object: 2


Num of 2nd Object: 2

Observe the output, the value of num of both the objects are the same, regardless of the fact
that we have not incremented the num of the second object.

The same value of num in both objects proves that a static variable is shared among the objects.

Example 2: Static Variable inside a Function


#include <iostream>
using namespace std;

void increase(){
static int num = 0;
cout << ++num << endl;
}

int main(){
increase();
increase();
return 0;
}
Output:

1
2

C++ Pointers
The pointer in C++ language is a variable, it is also known as locator or indicator that points to
an address of a value.

Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees
etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.


3) It makes you able to access any memory location in the computer's memory.

Usage of pointer

There are many usage of pointers in C++ language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions
where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code
and improves the performance.
Symbols used in pointer

Symbol Name Description

& (ampersand sign) Address operator Determine the address of a variable.

∗ (asterisk sign) Indirection operator Access the value of an address.


Declaring a pointer
The pointer in C++ language can be declared using ∗ (asterisk symbol).
int ∗ a; //pointer to int
char ∗ c; //pointer to char
Pointer Example
Let's see the simple example of using pointers printing the address and value.

#include <iostream>
using namespace std;
int main()
{
int number=30;
int ∗ p;
p=&number;//stores the address of number variable
cout<<"Address of number variable is:"<<&number<<endl;
cout<<"Address of p variable is:"<<p<<endl;
cout<<"Value of p variable is:"<<*p<<endl;
return 0;
}
Output:

Address of number variable is:0x7ffccc8724c4


Address of p variable is:0x7ffccc8724c4
Value of p variable is:30
Pointer Program to swap 2 numbers without using 3rd variable
#include <iostream>
using namespace std;
int main()
{
int a=20,b=10,∗p1=&a,∗p2=&b;
cout<<"Before swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
∗p1=∗p1+∗p2;
∗p2=∗p1-∗p2;
∗p1=∗p1-∗p2;
cout<<"After swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
return 0;
}
Output:

Before swap: ∗p1=20 ∗p2=10


After swap: ∗p1=10 ∗p2=20

Type Conversion in C++


Type conversion is the process that converts the predefined data type of one variable into an
appropriate data type. The main idea behind type conversion is to convert two different data
type variables into a single data type to solve mathematical and logical expressions easily
without any data loss.
For example, we are adding two numbers, where one variable is of int type and another of float
type; we need to convert or typecast the int variable into a float to make them both float data
types to add them.

Type conversion can be done in two ways in C++, one is implicit type conversion, and the
second is explicit type conversion.
Implicit Type Conversion
The implicit type conversion is the type of conversion done automatically by the compiler
without any human effort. It means an implicit conversion automatically converts one data type
into another type based on some predefined rules of the C++ compiler. Hence, it is also known
as the automatic type conversion.
For example:

int x = 20;
short int y = 5;
int z = x + y;
In the above example, there are two different data type variables, x, and y, where x is an int
type, and the y is of short int data type. And the resultant variable z is also an integer type that
stores x and y variables. But the C++ compiler automatically converts the lower rank data type
(short int) value into higher type (int) before resulting the sum of two numbers. Thus, it avoids
the data loss, overflow, or sign loss in implicit type conversion of C++.
Order of the typecast in implicit conversion
The following is the correct order of data types from lower rank to higher rank:

bool -> char -> short int -> int -> unsigned int -> long int -> unsigned long int -> long long int
-> float -> double -> long double
Explicit type conversion
Conversions that require user intervention to change the data type of one variable to another,
is called the explicit type conversion. In other words, an explicit conversion allows the
programmer to manually changes or typecasts the data type from one variable to another type.
Hence, it is also known as typecasting. Generally, we force the explicit type conversion to
convert data from one type to another because it does not follow the implicit conversion rule.

The explicit type conversion is divided into two ways:


1. Explicit conversion using the cast operator
2. Explicit conversion using the assignment operator
Program to convert float value into int type using the cast operator
Cast operator: In C++ language, a cast operator is a unary operator who forcefully converts one
type into another type.
Let's consider an example to convert the float data type into int type using the cast operator of
the explicit conversion in C++ language.

Program3.cpp

#include <iostream>
using namespace std;
int main ()
{
float f2 = 6.7;
// use cast operator to convert data from one type to another
int x = static_cast <int> (f2);
cout << " The value of x is: " << x;
return 0;
}
Output
The value of x is 6
Program to convert one data type into another using the assignment operator
Let's consider an example to convert the data type of one variable into another using the
assignment operator in the C++ program.

Program4.cpp

#include <iostream>
using namespace std;
int main ()
{
// declare a float variable
float num2;
// initialize an int variable
int num1 = 25;

// convert data type from int to float


num2 = (float) num1;
cout << " The value of int num1 is: " << num1 << endl;
cout << " The value of float num2 is: " << num2 << endl;
return 0;
}
Output

The value of int num1 is: 25


The value of float num2 is: 25.0
UML Unified Modeling Language Diagrams Introduction
UML is used to model (i.e., represent) the system being built. Taken in total, the UML model
that you build will represent, to a certain level of fidelity, the real system that will be
constructed.
• The UML has numerous types of diagrams, each providing a certain view of your
system.
• One must understand both the structure and the function of the objects involved.
• One must understand the taxonomic structure of the class objects, the inheritance
mechanisms used, the individual behaviors of objects, and the dynamic behavior of the
system as a whole.

■ Package diagram
■ Class diagram
■ Component diagram
■ Deployment diagram
■ Object diagram
■ Composite structure diagram

Structure diagrams are often used in conjunction with behavior diagrams to depict a
particular aspect of your system. Each class may have an associated state machine
diagram that indicates the event-driven behavior of the class’s instances. Similarly, in
conjunction with an object diagram representing a scenario, we may provide an
interaction diagram to show the time or event ordering of messages as they are
evaluated.
The diagrams we have introduced thus far are largely static.In object-oriented
development, we express the dynamic behavioral semantics of a problem or its implementation
through the following additional diagrams:
■ Use case diagram
■ Activity diagram
■ State machine diagram
■ Interaction diagrams
■ Sequence diagram
■ Communication diagram
■ Interaction overview diagram
■ Timing diagram

Class Diagram
A class diagram is used to show the existence of classes and their relationships in the
logical view of a system. A single class diagram represents a view of the class structure of a
system. During analysis, we use class diagrams to indicate the common roles and
responsibilities of the entities that provide the system’s behavior.
During design, we use class diagrams to capture the structure of the classes that form
the system’s architecture.
The two essential elements of a class diagram are
1. classes
2. their basic relationships.
Essentials: The Class Notation
Figure 5–33 shows the icon used to represent a class in a class diagram and an example from
our Hydroponics Gardening System. The class icon consists of three compartments, with the
first occupied by the class name, the second by the attributes, and the third by the operations.
Attribute specification format:
visibility attributeName : Type [multiplicity] = DefaultValue {property string}
■ Operation specification format:
visibility operationName (parameterName : Type) : ReturnType {property string}
■ Public (+) Visible to any element that can see the class
■ Protected (#) Visible to other elements within the class and to subclasses
■ Private (-) Visible to other elements within the class
■ Package (~) Visible to elements within the same package

Class Relationships
Classes rarely stand alone; instead, they collaborate with other classes in a variety of
ways.
The essential connections among classes include
1. association,
2. generalization - “is a” relationship
3. aggregation,
4. composition,
The multiplicity adornment is applied to the target end of an association and denotes the
number of links between each instance of the source class and instances of the target class.
■ 1 Exactly one
■ * Unlimited number (zero or more)
■ 0..* Zero or more
■ 1..* One or more
■ 0..1 Zero or one
■ 3..7 Specified range (from three through seven, inclusive)
CLASS DIAGRAM

Purpose of Class Diagrams


1. Shows static structure of classifiers in a system
2. Diagram provides a basic notation for other structure diagrams prescribed by UML
3. Helpful for developers and other team members too
4. Business Analysts can use class diagrams to model systems from a business perspective
A UML class diagram is made up of:
• A set of classes and
• A set of relationships between classes
What is a Class
A description of a group of objects all with similar roles in the system, which consists of:
• Structural features (attributes) define what objects of the class "know"
• Represent the state of an object of the class
• Are descriptions of the structural or static features of a class
• Behavioral features (operations) define what objects of the class "can do"
• Define the way in which objects may interact
• Operations are descriptions of behavioral or dynamic features of a class
Class Notation
A class notation consists of three parts:
1. Class Name
• The name of the class appears in the first partition.
2. Class Attributes
• Attributes are shown in the second partition.
• The attribute type is shown after the colon.
• Attributes map onto member variables (data members) in code.
3. Class Operations (Methods)
• Operations are shown in the third partition. They are services the class provides.
• The return type of a method is shown after the colon at the end of the method
signature.
• The return type of method parameters is shown after the colon following the
parameter name.
• Operations map onto class methods in code

The graphical representation of the class - MyClass as shown above:


• MyClass has 3 attributes and 3 operations
• Parameter p3 of op2 is of type int
• op2 returns a float
• op3 returns a pointer (denoted by a *) to Class6
Class Relationships
A class may be involved in one or more relationships with other classes. A relationship can be
one of the following types: (Refer to the figure on the right for the graphical representation of
relationships).

Relationship Type Graphical Representation


Inheritance (or Generalization):
• Represents an "is-a" relationship.
• An abstract class name is shown in italics.
• SubClass1 and SubClass2 are specializations of
Super Class.
• A solid line with a hollow arrowhead that point
from the child to the parent class

Simple Association:
• A structural link between two peer classes.
• There is an association between Class1 and
Class2
• A solid line connecting two classes

Aggregation:
A special type of association. It represents a "part of"
relationship.
• Class2 is part of Class1.
• Many instances (denoted by the *) of Class2 can
be associated with Class1.
• Objects of Class1 and Class2 have separate
lifetimes.
• A solid line with an unfilled diamond at the
association end connected to the class of
composite

Composition:
A special type of aggregation where parts are destroyed
when the whole is destroyed.
• Objects of Class2 live and die with Class1.
• Class2 cannot stand by itself.
• A solid line with a filled diamond at the
association connected to the class of composite

Dependency:
• Exists between two classes if the changes to the
definition of one may cause changes to the other
(but not the other way around).
• Class1 depends on Class2
• A dashed line with an open arrow

Relationship Names
• Names of relationships are written in the middle of the association line.
• Good relation names make sense when you read them out loud:
• "Every spreadsheet contains some number of cells",
• "an expression evaluates to a value"
• They often have a small arrowhead to show the direction in which direction to read
the relationship, e.g., expressions evaluate to values, but values do not evaluate to
expressions.

Relationship - Roles
• A role is a directional purpose of an association.
• Roles are written at the ends of an association line and describe the purpose played by
that class in the relationship.
• E.g., A cell is related to an expression. The nature of the relationship is that the
expression is the formula of the cell.
Navigability
The arrows indicate whether, given one instance participating in a relationship, it is possible to
determine the instances of the other class that are related to it.
The diagram above suggests that,
• Given a spreadsheet, we can locate all of the cells that it contains, but that
• we cannot determine from a cell in what spreadsheet it is contained.
• Given a cell, we can obtain the related expression and value, but
• given a value (or expression) we cannot find the cell of which those are
attributes.
Visibility of Class attributes and Operations
In object-oriented design, there is a notation of visibility for attributes and operations. UML
identifies four types of visibility: public, protected, private, and package.
The +, -, # and ~ symbols before an attribute and operation name in a class denote the visibility
of the attribute and operation.
• + denotes public attributes or operations
• - denotes private attributes or operations
• # denotes protected attributes or operations
• ~ denotes package attributes or operations
Class Visibility Example

In the example above:


attribute1 and op1 of MyClassName are public
attribute3 and op3 are protected.
attribute2 and op2 are private.
Access for each of these visibility types is shown below for members of different classes.
Access Right public (+) private (-) protected (#) Package (~)
Members of the same class yes Yes yes yes
Members of derived classes yes No yes yes
Members of any other class yes No no in same package
Multiplicity
How many objects of each class take part in the relationships and multiplicity can be expressed
as:
• Exactly one - 1
• Zero or one - 0..1
• Many - 0..* or *
• One or more - 1..*
• Exact Number - e.g. 3..4 or 6
• Or a complex relationship - e.g. 0..1, 3..4, 6.* would mean any number of objects other
than 2 or 5
Multiplicity Example
• Requirement: A Student can take many Courses and many Students can be enrolled in
one Course.
• In the example below, the class diagram (on the left), describes the statement of the
requirement above for the static model while the object diagram (on the right) shows
the snapshot (an instance of the class diagram) of the course enrollment for the courses
Software Engineering and Database Management respectively)

Aggregation Example - Computer and parts


• An aggregation is a special case of association denoting a "consists-of" hierarchy
• The aggregate is the parent class, the components are the children classes

Inheritance Example - Cell Taxonomy


• Inheritance is another special case of an association denoting a "kind-of" hierarchy
• Inheritance simplifies the analysis model by introducing a taxonomy
• The child classes inherit the attributes and operations of the parent class.

Class Diagram - Diagram Tool Example


A class diagram may also have notes attached to classes or relationships. Notes are shown in
grey.
In the example above:
We can interpret the meaning of the above class diagram by reading through the points as
following.
1. Shape is an abstract class. It is shown in Italics.
2. Shape is a superclass. Circle, Rectangle and Polygon are derived from Shape. In other
words, a Circle is-a Shape. This is a generalization / inheritance relationship.
3. There is an association between DialogBox and DataController.
4. Shape is part-of Window. This is an aggregation relationship. Shape can exist without
Window.
5. Point is part-of Circle. This is a composition relationship. Point cannot exist without a
Circle.
6. Window is dependent on Event. However, Event is not dependent on Window.
7. The attributes of Circle are radius and center. This is an entity class.
8. The method names of Circle are area(), circum(), setCenter() and setRadius().
9. The parameter radius in Circle is an in parameter of type float.
10. The method area() of class Circle returns a value of type double.
11. The attributes and method names of Rectangle are hidden. Some other classes in the
diagram also have their attributes and method names hidden.
Dealing with Complex System - Multiple or Single Class Diagram?
Inevitably, if you are modeling a large system or a large business area, there will be numerous
entities you must consider. Should we use multiple or a single class diagram for modeling the
problem? The answer is:
• Instead of modeling every entity and its relationships on a single class diagram, it is
better to use multiple class diagrams.
• Dividing a system into multiple class diagrams makes the system easier to understand,
especially if each diagram is a graphical representation of a specific part of the system.
Perspectives of Class Diagram in Software Development Lifecycle
We can use class diagrams in different development phases of a software development
lifecycle and typically by modeling class diagrams in three different perspectives (levels of
detail) progressively as we move forward:
Conceptual perspective: The diagrams are interpreted as describing things in the real world.
Thus, if you take the conceptual perspective you draw a diagram that represents the concepts
in the domain under study. These concepts will naturally relate to the classes that implement
them. The conceptual perspective is considered language-independent.
Specification perspective: The diagrams are interpreted as describing software abstractions or
components with specifications and interfaces but with no commitment to a particular
implementation. Thus, if you take the specification perspective we are looking at the
interfaces of the software, not the implementation.
Implementation perspective: The diagrams are interpreted as describing software
implementations in a particular technology and language. Thus, if you take the implementation
perspective we are looking at the software implementation.

USE CASE DIAGRAMS


Use case diagrams are used to depict the context of the system to be built and the
functionality provided by that system. They depict who (or what) interacts with the system.
They show what the outside world wants the system to do.
Use case diagrams are valuable for visualizing the functional requirements of a system that will
translate into design choices and development priorities.
They also help identify any internal or external factors that may influence the system and
should be taken into consideration.
They provide a good high level analysis from outside the system. Use case diagrams specify
how the system interacts with actors without worrying about the details of how that
functionality is implemented.
Basic Use Case Diagram Symbols and Notations
System
Draw your system's boundaries using a rectangle that contains use cases. Place actors outside
the system's boundaries.

Use Case
Draw use cases using ovals. Label the ovals with verbs that represent the system's functions.

Actors
Actors are the users of a system. When one system is the actor of another system, label the
actor system with the actor stereotype.
Relationships
Illustrate relationships between an actor and a use case with a simple line. For relationships
among use cases, use arrows labeled either "uses" or "extends." A "uses" relationship indicates
that one use case is needed by another in order to perform a task. An "extends" relationship
indicates alternative options under a certain use case.
CONSTRUCTOR AND DESTRUCTOR
A constructor is a 'special' member function whose task is to initialize the objects of its class.
It is special because its name is same as the class name. The constructor is invoked whenever
an object of its associated class is created. It is called constructor because it construct the value
data members of the class.
//class with a constructor
class Integer
{
int m, n;
public:
Integer(void); / constructor declared ...
};
Integer :: Integer(void) // constructor defined
{
m = 0; n = 0;
}
};
When a class contains a constructor like the one defined above, it is guaranteed that an object
created by the class will be initialized automatically.
For example, the declaration.

Integer int1; // object int1 created

not only creates the object int1 of type Integer but also initializes its data members m and n to
0.There is no need to write any statement to invoke the constructor function.

A constructor that accepts no parameters is called the default constructor. The default
constructor for class A is A::A(). If no such constructor is defined the compiler suppliers default
constructor. Therefore a statement such as
A a;

invokes the default constructor of the compiler to create the object a. The constructor functions
have some special characteristics.

• They should be declared in the public section.

• They are invoked automatically when the objects are created.


• They do not have return types, not even void and therefore, they cannot return values.
• They cannot be inherited, though a derived class can call the base class constructor.
• Like other C++ functions, they can have default arguments.
• Constructors cannot be virtual.
• We cannot refer to their addresses.
• An object with a constructor (or destructor) cannot be used as a member of a union.

They make implicit calls to the operations new and delete when memory allocation is required.
Remember, when a constructor is declared for a class initialization of the class objects become
mandatory.
PARAMETERIZED CONSTRUCTORS
The constructor Integer(), defined above, initialized the data members of all the objects to zero.
However in practice it may be necessary to initialize the various data elements of different
objects with different values when they are created. C++ permits us to achieve this objective
by passing arguments to the constructor function when the objects are created. The constructors
that can take arguments are called parameterized constructors.

The constructor integer() may be modified to take arguments as shown below :


class integer
{
int m, n;
public:
integer (int x, int y); //parameterized constructor
.......
};
integer : : integer int x, int y)
{
m = x; n = y;
}
When a constructor has been parameterized, the object declaration statement such as
integer int1;
may not work. We must pass the initial values as arguments to the constructor function when
an object is declared. This can be done in two ways;
By calling the constructor explicitly.
By calling the constructor implicitly.

Integer Int1 = Integer (0, 100); //explicit call

This statement creates in integer object int1 and passes the values 0 and 100 to it.

The second is implemented as follows :

Integer int1 (0, 100); //implicit call.

This method sometimes called the shorthand method, is used very often as it is shorter, looks
better and is easy to implement.
COPY CONSTRUCTOR
We used the copy constructor.

Integer (integer & I)

in section 3.4 as one of the overloaded constructors.

As stated earlier, a copy constructor is used to declare and initialize an object from another
object For example, the statement.

integer l2 (l1);
would define the object I2 and at the same time initialize to the values of I1. Another form of
this statement is
integer l2 = l1;

The process of initializing through a copy constructor is known as copy initialization.


Remember the statement.

l2 = l1;

will not invoke the copy constructor. However, if I1 and I2 are objects, this statement is legal
simply assigns the values of I1 to I2, member-by- member.

A copy constructor takes a reference to an object of the same class s itself as an argument.

DESTRUCTORS
A destructor, as the name implies, is used to destroy the objects that have been created by a
constructor. Like a constructor, it is a member function whose name is the same as the class
name but is preceded by a tilde, For example, the destructor for the class integer can be defined
as shown below:
integer ( ) { }

A destructor never takes any argument nor does it return any value. It will be invoked implicitly
by the compiler upon exit from the program (or block or function as the case may be) to clean
up storage that is no longer accessible. It is good practice to declare destructors in a program
since it release memory space for future use

Whenever new is used to allocate memory in the constructors, we should use delete to free that
memory. For example the destructor for the matrix class discussed above may be defined as
follows.
matrix :: ~ matrix ( )
{
for (int i = 0: j < d1;i++)
delete p[i];
delete p;
}
This is required because when the pointers to object go out of scope, a destructor is not called
implicitly.

You might also like