[go: up one dir, main page]

0% found this document useful (0 votes)
18 views43 pages

Unit 2 OODP

21CSC101T

Uploaded by

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

Unit 2 OODP

21CSC101T

Uploaded by

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

21CSC101T OBJECT ORIENTED DESIGN AND

PROGRAMMING
( PROFESSIONAL CORE)
L-2, T-1, C-3
TOPICS
Constructors- Types of constructors – Static
constructor and Copy constructor -Destructor -
Polymorphism: Constructor overloading -
Method Overloading Operator Overloading -
UML Interaction Diagrams -Sequence Diagram
- Collaboration Diagram - Example Diagram
(9 hours)
Constructors
• A constructor in C++ is a special method that is
automatically called when an object of a class is
created.
• The constructor in C++ has the same name as the
class or structure.
• Constructor does not have a return value, hence they
do not have a return type.
• The prototype of Constructors is as follows:
<class-name> (list-of-parameters){
//initialize values to the data members
}
Constructors Example
class MyClass { // The class
public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
Parameterized Constructor

• Constructors can also take parameters (just like regular functions), which can be
useful for setting initial values for attributes.
Example
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z; } };
int main() { // Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
Constructors defined outside the
class
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};
// Constructor definition outside the class
Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z; }
int main() { // Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
Types of Constructors
• Default/Static Constructors: Default constructor is
the constructor which doesn’t take any argument.
It has no parameters. It is also called a
zero-argument constructor.
• Parameterized Constructors: It is possible to pass
arguments to constructors. Typically, these
arguments help initialize an object when it is
created.
• Copy Constructor: A copy constructor is a member
function that initializes an object using another
object of the same class.
Default/Static Constructor
• A constructor which has no argument is known as default constructor. It is
invoked at the time of creating object.
Example
#include <iostream>
using namespace std;
class Employee {
public:
Employee() {
cout<<"Default Constructor Invoked"<<endl; }
};
int main(void) {
Employee e1; //creating an object of Employee
Employee e2;
return 0; }
Parameterized Constructor
• A constructor which has parameters is called parameterized constructor. It is used to
provide different values to distinct objects.
Example
#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Copy Constructor
• A member function known as a copy constructor initializes an item using another object
#include <iostream>
using namespace std;
from the same class class Employee {
Example private:
string name;
int age;
#include <iostream> public:
// Default Constructor
using namespace std; Employee() {
name = "John Doe";
// declare a class age = 30;
cout << "Default Constructor Invoked" << endl;
class Wall { }

// Parameterized Constructor
private: Employee(string newName, int newAge) {
name = newName;
double length; age = newAge;
cout << "Parameterized Constructor Invoked" << endl;
double height; }

public: // Copy Constructor


Employee(const Employee &source) {
// initialize variables with parameterized constructor name = source.name;
age = source.age;
cout << "Copy Constructor Invoked" << endl;
Wall(double len, double hgt) { }

length = len; // Method to display employee information


void display() {
height = hgt; }
cout << "Name: " << name << ", Age: " << age << endl;

} };

// copy constructor with a Wall object as parameter int main() {


// Creating an object using default constructor
Employee e1;
// copies data of the obj parameter
// Creating another object using parameterized constructor
Wall(Wall &obj) { Employee e2("Alice", 25);

length = obj.length; // Creating a third object using copy constructor


Employee e3 = e2; // Copy constructor invoked
height = obj.height; // Displaying information of all employees
cout << "Employee 1: ";
} e1.display();
cout << "Employee 2: ";
double calculateArea() { e2.display();
cout << "Employee 3: ";
return length * height; e3.display();

} }
return 0;

};
Destructor
• A destructor is also a special member function as a constructor.
• Destructor destroys the class objects created by the constructor.
• Destructor has the same name as their class name preceded by
a tilde (~) symbol. It is not possible to define more than one
destructor.
• The destructor is only one way to destroy the object created by
the constructor. Hence destructor can-not be overloaded.
• Destructor neither requires any argument nor returns any value.
It is automatically called when the object goes out of scope.
• Destructors release memory space occupied by the objects
created by the constructor.
• In destructor, objects are destroyed in the reverse of object
creation.
Destructor
• The syntax for defining the destructor within the class
~ <class-name>()
{
}

• The syntax for defining the destructor outside the class


<class-name>: : ~ <class-name>(){}

• Example
#include <iostream>
using namespace std;

class Test {
public:
Test() {
cout << "\n Constructor executed"; }

~Test()
Polymorphism

• The word polymorphism • Polymorphism allows us to


means having many forms. perform a single action in
• In simple words, we can different ways. In other
words, polymorphism allows
define polymorphism as the
you to define one interface
ability of a message to be and have multiple
displayed in more than one implementations.
form • Compile-time Polymorphism
• The word “poly” means • Runtime Polymorphism
many and “morphs” means
forms, So it means many
forms.
Constructor Overloading

• We can have more than one • Overloaded constructors


constructor in a class with essentially have the same
same name, as long as each name (exact name of the
has a different list of class) and different by number
arguments. and type of arguments.
• This concept is known as • A constructor is called
Constructor Overloading and depending upon the number
is quite similar to function and type of arguments
overloading. passed.
• While creating the object,
arguments must be passed to
let compiler know, which
constructor needs to be
called.
Constructor Overloading

// C++ program to illustrate construct(int a, int b)


{
// Constructor overloading
area = a * b;
#include <iostream> }
using namespace std; void disp()
class construct {
cout<< area<< endl;
{ }
public: };
float area; int main()
{
// Constructor with no parameters
// Constructor Overloading
construct() // with two different constructors
{ // of class name
area = 0; construct o;
construct o2( 10, 20);
} o.disp();
// Constructor with two parameters o2.disp();
return 1;
}
Method Overloading

• Function overloading is a • When a function name is


feature of object-oriented overloaded with different
programming jobs it is called Function
• where two or more Overloading.
functions can have the • In Function Overloading
same name but different “Function” name should be
parameters. the same and the
arguments should be
different
Method Overloading

#include <iostream> // Driver code


using namespace std; int main()
void add(int a, int b) {
{ add(10, 2);
cout << "sum = " << (a + b); add(5.3, 6.2);
} return 0;
void add(double a, double b) }
{
cout << endl << "sum = " << (a + b);

}
Operator Overloading

• Operator overloading is a • Operator overloading is


compile-time polymorphism used to overload or
in which the operator is redefines most of the
overloaded to provide the operators available in C++.
special meaning to the • It is used to perform the
user-defined data type. operation on the
• For example, user-defined data type.
• C++ provides the ability to
add the variables of the
user-defined data type that
is applied to the built-in
data types
Operator Overloading

• Operator that cannot be overloaded are as follows:


Scope operator (::)
Sizeof
member selector(.)
member pointer selector(*)
ternary operator(?:)
Syntax of Operator Overloading:
return_type class_name : : operator op(argument_list)
{
// body of the function.
}
Operator Overloading

• Rules for Operator • We cannot use friend


Overloading: function to overload certain
operators. However, the
• Existing operators can only
member function can be
be overloaded, but the new used to overload those
operators cannot be operators.
overloaded. • When unary operators are
• The overloaded operator overloaded through a
contains atleast one member function take no
operand of the user-defined explicit arguments, but, if
data type. they are overloaded by a
friend function, takes one
argument.
Operator Overloading

#include <iostream> void operator ++()


using namespace std; {
class Test num = num+2;
}
{
void Print() {
private: cout<<"The Count is: "<<num;
int num; }
public: };
Test() int main()
{
{ num=8;
Test tt;
} ++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}
UML Interaction Diagram
• From the term Interaction, it • This interactive behavior is
is clear that the diagram is represented in UML by two
used to describe some type of diagrams known as Sequence
interactions among the diagram and Collaboration
different elements in the diagram. The basic purpose of
model. both the diagrams are similar.
• This interaction is a part of
dynamic behavior of the • Sequence diagram emphasizes
system. on time sequence of messages
and collaboration diagram
emphasizes on the structural
organization of the objects
that send and receive
messages.
Sequence Diagram
• The sequence diagram • In UML, the lifeline is
represents the flow of represented by a vertical bar,
messages in the system and is whereas the message flow is
also termed as an event represented by a vertical
diagram. dotted line that extends across
• It helps in envisioning several the bottom of the page.
dynamic scenarios. • It incorporates the iterations
• It portrays the communication as well as branching.
between any two lifelines as a
time-ordered sequence of
events, such that these
lifelines took part at the run
time
Sequence Diagram
• Purpose of a Sequence Notations of a Sequence Diagram:
Diagram: • Lifeline
• To model high-level • Actor
interaction among active • Activation
objects within a system. • Messages
• To model interaction among • Sequence Fragments
objects inside a collaboration
realizing a use case.
• It either models generic
interactions or some certain
instances of interaction
Sequence Diagram
Lifeline:
• An individual participant in the
sequence diagram is
represented by a lifeline. It is
positioned at the top of the
diagram
Sequence Diagram
Actor:
• A role played by an entity that
interacts with the subject is called
as an actor.
• It is out of the scope of the
system. It represents the role,
which involves human users and
external hardware or subjects. An
actor may or may not represent a
physical entity, but it purely
depicts the role of an entity.
Several distinct roles can be
played by an actor or vice versa.
Sequence Diagram
Activation:
• It is represented by a thin
rectangle on the lifeline. It
describes that time period in
which an operation is performed
by an element, such that the top
and the bottom of the rectangle is
associated with the initiation and
the completion time, each
respectively.
Sequence Diagram
Messages: Call Message:
• The messages depict the • It defines a particular
interaction between the objects communication between
and are represented by arrows. the lifelines of an
They are in the sequential order interaction, which
on the lifeline. The core of the represents that the target
sequence diagram is formed by lifeline has invoked an
messages and lifelines. operation.
Sequence Diagram
Return Message
• It defines a particular
communication between the
lifelines of interaction that
represent the flow of information
from the receiver of the
corresponding caller message.
Sequence Diagram
Self Message:
It describes a communication,
particularly between the lifelines of
an interaction that represents a
message of the same lifeline, has
been invoked.
Sequence Diagram
Recursive Message:
• A self message sent for recursive
purpose is called a recursive
message. In other words, it can be
said that the recursive message is
a special case of the self message
as it represents the recursive
calls.
Sequence Diagram
Create Message:
• It describes a communication,
particularly between the lifelines
of an interaction describing that
the target (lifeline) has been
instantiated.
Sequence Diagram
Destroy Message:
• It describes a communication,
particularly between the lifelines
of an interaction that depicts a
request to destroy the lifecycle of
the target.
Sequence Diagram
Duration Message:
• It describes a communication
particularly between the lifelines
of an interaction, which portrays
the time passage of the message
while modeling a system.
Sequence Diagram
Note:
• A note is the capability of
attaching several remarks to the
element.
• It basically carries useful
information for the modelers.
Sequence Diagram
Sequence Fragments
• Sequence fragments have been
introduced by UML 2.0, which
makes it quite easy for the
creation and maintenance of an
accurate sequence diagram.
• It is represented by a box called a
combined fragment, encloses a
part of interaction inside a
sequence diagram.
• The type of fragment is shown by
a fragment operator.
Sequence Diagram
• Example of a Sequence Diagram:
• Any online customer can search
for a book catalog, view a
description of a particular book,
add a book to its shopping cart,
and do checkout.
Sequence Diagram
• Benefits of a Sequence • The drawback of a Sequence
Diagram: Diagram:
• It explores the real-time • In the case of too many lifelines,
the sequence diagram can get
application. more complex.
• It depicts the message flow • The incorrect result may be
between the different produced, if the order of the flow
objects. of messages changes.
• It has easy maintenance. • Since each sequence needs
distinct notations for its
• It is easy to generate. representation, it may make the
• Implement both forward and diagram more complex.
reverse engineering. • The type of sequence is decided
by the type of message.
• It can easily update as per the
new change in the system.
Collaboration Diagram
• The collaboration diagram is • An object consists of several
used to show the relationship features.
between the objects in a • Multiple objects present in the
system. system are connected to each
• Both the sequence and the other.
collaboration diagrams • The collaboration diagram,
represent the same which is also known as a
information but differently. communication diagram, is
Instead of showing the flow of used to portray the object's
messages, architecture in the system.
• it depicts the architecture of
the object residing in the
system as it is based on
object-oriented programming.
Collaboration Diagram
• Notations of a Collaboration • Links: The link is an instance of
association, which associates the
Diagram: objects and actors. It portrays a
• Objects: The representation of relationship between the objects
through which the messages are
an object is done by an object sent. It is represented by a solid
symbol with its name and class line. The link helps an object to
underlined, separated by a connect with or navigate to
another object,
colon.
• Messages: It is a communication
• Actors: In the collaboration between objects which carries
diagram, the actor plays the information and includes a
sequence number, so that the
main role as it invokes the activity may take place. It is
interaction. Each actor has its represented by a labeled arrow,
respective role and name. In which is placed near a link.
this, one actor initiates the use
case.
Collaboration Diagram
When to use a Collaboration Steps for creating a
Diagram? Collaboration Diagram:
• The collaborations are used • Determine the behavior for
when it is essential to depict the which the realization and
relationship between the implementation are specified.
object. • Discover the structural
elements that are class roles,
• Both the sequence and objects, and subsystems for
collaboration diagrams performing the functionality of
represent the same collaboration.
information, but the way of • Choose the context of an
portraying it quite different. The interaction: system,
collaboration diagrams are best subsystem, use case, and
suited for analyzing use cases. operation.
Collaboration Diagram
Sequence Diagram

You might also like