0% found this document useful (0 votes)
68 views96 pages

CT 1

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)
68 views96 pages

CT 1

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/ 96

TOPICS

TOPICS
-Object-Oriented Programming
- Features of C++
-I/O Operations,
-Data Types,Variables-Static,Constants
Object-Oriented
-Pointers Programming - Features of
-Type Conversions
C++ - I/O
– Conditional Operations,
and looping statements Data Types,
Variables-Static,
– Arrays Constants-Pointers-Type
- C++ 11 features
Conversions – Conditional and looping
- Class and Objects,
-Abstraction and Encapsulation,
statements – Arrays - C++ 11 features - Class
-Access Specifier,
and Objects,
-Methods- Abstraction and Encapsulation,
UML Diagrams
-Introduction – Use Case Diagram - Class diagram
Access Specifier, Methods- UML Diagrams
Introduction – Use Case Diagram - Class
Diagram. (9 hours)
Object-Oriented Programming

• A computer programming model that organizes software design


around data, or objects, rather than functions and logic.
– An object has unique attributes and behaviour.
• OOP focuses on the objects that developers want to manipulate
rather than the logic required to manipulate them.
– well-suited for programs that are large, complex and actively updated
or maintained.
– Develop programs for manufacturing and design, as well as mobile
applications.
• for example, OOP can be used for manufacturing system simulation software.
• Aim of OOP:
– 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.
OOP
• Beneficial to collaborative development, where projects are divided into
groups.
– Additional benefits of OOP:
• code reusability, scalability and efficiency.
• First step in OOP:
– collect all of the objects a programmer wants to manipulate and identify how
they relate to each other.
• Examples of an object:
– physical entities, e.g. a human being who is described by properties like name
and address
– small computer programs, e.g. widgets.
• Once an object is known, it is labelled with a class of objects that defines
the kind of data it contains and any logic sequences that can manipulate it.
Each distinct logic sequence is known as a method.
• Objects can communicate with well-defined interfaces called messages.
Procedural Programming vs. OOP

• Procedural programming
– Writing procedures or functions that perform operations
on the data.
• Object-oriented programming
– Creating objects that contain both data and functions.
• Advantages of OOP over procedural programming:
– faster and easier to execute
– provides a clear structure for the programs
– Makes the code easier to maintain, modify and debug
– create full reusable applications with less code and shorter
development time.
Building blocks of OOP

• Classes are user-defined data types that act as the blueprint for individual
objects, attributes and methods.
• Objects are instances of a class created with specifically defined data.
– Objects can correspond to real-world objects or an abstract entity.
– When class is defined initially, the description is the only object that is defined.
• Methods are functions that are defined inside a class that describe the
behaviours of an object.
– Each method contained in class definitions starts with a reference to an instance
object.
– Additionally, the subroutines contained in an object are called instance methods.
Programmers use methods for reusability or keeping functionality encapsulated
inside one object at a time.
• Attributes are defined in the class template and represent the state of an
object. Objects will have data stored in the attributes field. Class attributes
belong to the class itself.
a tributes
Example
• Class: Fruit
• Objects: Apple, Banana, Mango
• Methods: getData(), displayData(), delete(),
add(), etc.
• Attributes: name, color, price, size, etc.
Principles of OOP/ Features of C++

• Encapsulation.
– This principle states that all important information is contained inside an object
and only select information is exposed.
– The implementation and state of each object are privately held inside a defined
class.
– Other objects do not have access to this class or the authority to make changes.
They are only able to call a list of public functions or methods.
– This characteristic of data hiding provides greater program security and avoids
unintended data corruption.
• Abstraction.
– Objects only reveal internal mechanisms that are relevant for the use of other
objects, hiding any unnecessary implementation code.
– The derived class can have its functionality extended.
– This concept can help developers more easily make additional changes or
additions over time.
Encapsulation: It's like putting your code and data in a container (class) to
keep things organized.

Abstraction: It's like using something without needing to know how it works
internally; you interact with the functionalities.
Features of OOP
• Inheritance. Classes can reuse code from other classes.
– Relationships and subclasses between objects can be assigned, enabling
developers to reuse common logic while still maintaining a unique
hierarchy.
– This property of OOP forces a more thorough data analysis, reduces
development time and ensures a higher level of accuracy.
• Polymorphism. Objects are designed to share behaviours and they
can take on more than one form.
– The program will determine which meaning or usage is necessary for
each execution of that object from a parent class, reducing the need to
duplicate code.
– A child class is then created, which extends the functionality of the
parent class.
– Polymorphism allows different types of objects to pass through the
same interface.
polymorphism is like using a single interface to interact with different objects,

allowing them to take on more than one form while sharing common
behaviors.
Examples of OOP Languages
• Simula is the first object-oriented programming language
• popular pure OOP languages include:
– Ruby
– Scala
– JADE
– Emerald
• Programming languages designed primarily for OOP include:
– Java
– Python
– C++
• Other programming languages that pair with OOP include:
– Visual Basic .NET
– PHP
– JavaScript
Benefits of OOP
• Modularity
– Encapsulation enables objects to be self-contained, making
troubleshooting and collaborative development easier.
• Reusability
– Code can be reused through inheritance, meaning a team
does not have to write the same code multiple times.
• Productivity
– Programmers can construct new programs quicker through
the use of multiple libraries and reusable code.
• Easily upgradable and scalable
– Programmers can implement system functionalities
independently.
MARVELS-P:

Modularity, Abstraction, Reusability, Vomit, Extension, Libraries, Security.


Productivity
Benefits of OOP
• Interface descriptions.
– Descriptions of external systems are simple, due to
message passing techniques that are used for objects
communication.
• Security.
– Using encapsulation and abstraction, complex code is
hidden, software maintenance is easier and internet
protocols are protected.
• Flexibility.
– Polymorphism enables a single function to adapt to the
class it is placed in.
– Different objects can also pass through the same interface.
Criticism of OOP
• OOP overemphasizes the data component of
software development and does not focus
enough on computation or algorithms.

• OOP code may be more complicated to write


and take longer to compile.
Alternative methods to OOP

• Functional programming.
– This includes languages such as Erlang and Scala, which are used for telecommunications
and fault tolerant systems.
• Structured or modular programming.
– This includes languages such as PHP and C#.
• Imperative programming.
– This alternative to OOP focuses on function rather than models and includes C++ and Java.
• Declarative programming.
– This programming method involves statements on what the task or desired outcome is but
not how to achieve it. Languages include Prolog and Lisp.
• Logical programming.
– This method, which is based mostly in formal logic and uses languages such as Prolog,
contains a set of sentences that express facts or rules about a problem domain. It focuses
on tasks that can benefit from rule-based logical queries.
• Note: Most advanced programming languages enable developers to combine
models, because they can be used for different programming methods. For example,
JavaScript can be used for OOP and functional programming.
I/O Operations
• In C++, I/O operation occurs in streams, which involve transfer of
information into byte
• It’s a sequences of bytes Text
Stream
• Stream involved in two ways Stream in C
– Source
Binary
– Destination of data Stream
• C++ programs input data and output data from a stream.
• Streams are related with a physical device such as the monitor or with a
file stored on the secondary disk.
• In a text stream, the sequence of characters is divided into lines, with
each line being terminated with a new-line character (\n) . On the other
hand, a binary stream contains data values using their memory
representation.
Cascading of Input or Output
Operators

• << operator – It can use multiple times in the same line.


• Its called Cascading
• cout , cin can be cascaded
– For example
• cout<<“\n Enter the Marks”;
• cin>> Computer Networks>>OODP;
Reading and Writing Characters
and Strings
• int marks;
• cin.get(marks);//The value for marks is read
Or
• marks=cin.get();//A character is read and assigned to marks
• string name;
• cin>>name;
• string empname;
• cin.getline(empname,20);
• cout<<“\n Welcome ,”<<empname
Formatted Input and
Output Operations
#include <iomanip>
Formatting with flags
• The setf() is a member function of the class that is used
to set flags for formatting output.
syntax -cout.setf(flag, bit-field)
• Here, flag defined in the ios class specifies how the
output should be formatted bit-field is a constant
(defined in ios ) that identifies the group to which the
formatting flag belongs to.
• There are two types of setf()—one that takes both flag
and bit-fields and the other that takes only the flag
Formatting Output Using
Manipulators
Data Types in C++
• A type defines a set of values and a set of operations that can be applied on
those values. The set of values for each type is known as the domainfor the
type.
• Data types in C++ is mainly divided into two types:
1. Primitive Data Type (directly by the user to declare variables)
▪ Integer Derived Data Types:
▪ Character

Array:
Boolean
▪ Floating Point A collection of elements of the same data type.
Pointer:
▪ Double Floating Point
▪ Valueless or Void A variable that stores the memory address of another variable.
Reference:
▪ Wide Character

An alias for an existing variable.
Also : String
2. Abstract or User Defined Data type (data types are defined by user itself)
char =1
int=2
long float=4
double=8
Variables
• A variable is the content of a memory location that stores a certain
value. A variable is identified or denoted by a variable name.
• The variable name contains a sequence of one or more letters, digits
or underscore, for example: empname
Rules for defining variable name:
• A variable name can have one or more letters or digits or underscore
for example character.
• White space, punctuation symbols or other characters are not
permitted to denote variable name.
• A variable name must begin with a letter.
• Variable names cannot be keywords or any reserved words of the
C++ programming language.
• Data C++ is a case-sensitive language. Variable names written in
capital letters differ from variable names with the same name but
written in small letters
Types of Variables
Constants
• Constants are identifiers whose value does not change. While variables can
change their value at any time, constants can never change their value.
• Constants are used to define fixed values such as Pi or the charge on an
electron so that their value does not get changed in the program even by
mistake.
• A constant is an explicit data value specified by the programmer.

• The value of the constant is known to the compiler at the compile time
Declaring Constants
• Rule 1 : Constant names are usually written in capital letters to
visually distinguish them from other variable names which are
normally written in lower case characters.
• Rule 2: No blank spaces are permitted in between the #
symbol and define keyword. E.g. #define PI 3.14
• Rule 3: Blank space must be used between #define and
constant name and between constant name and constant
value.
• Rule 4: #define is a preprocessor compiler directive and not a
statement. Therefore, it does not end with a semi-colon.
Pointers
• Pointers are symbolic representation of addresses.
• They enable programs to simulate call-by-reference as well as to create and
manipulate dynamic data structures.
Syntax data_type *pointer_variable;
• Example
int *p,sum
Assignment
• integer type pointer can hold the address of another int variable
• To assign the address of variable to pointer-ampersand symbol (&)
p=&sum;
this pointer holds the address of current object
• int num;
• this->num=num;
Void?
• When used in the declaration of a pointer, void specifies that the pointer is
"universal." If a pointer's type is void* , the pointer can point to any variable that's
not declared with the const or volatile keyword
Type Conversions
• A type cast is basically a conversion from one type to another.
There are two types of type conversion:
• Implicit Type Conversion Also known as ‘automatic type
conversion’.
– Done by the compiler on its own, without any external trigger from the
user.
– Generally takes place when in an expression more than one data type is
present. In such condition type conversion (type promotion) takes place
to avoid lose of data.
– All the data types of the variables are upgraded to the data type of the
variable with largest data type.bool -> char -> short int -> int ->
unsigned int -> long -> unsigned -> long long -> float -> double -> long
double
– It is possible for implicit conversions to lose information, signs can be
lost (when signed is implicitly converted to unsigned), and overflow can
occur (when long long is implicitly converted to float).
Type Conversions
• // An example of implicit conversion
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x = 10; // integer x
6. char y = 'a'; // character c
7.
8. // y implicitly converted to int. ASCII
9. // value of 'a' is 97
10. x = x + y;
11.
12. // x is implicitly converted to float
13. float z = x + 1.0;
14.
15. cout << "x = " << x << endl
16. << "y = " << y << endl
17. << "z = " << z << endl;
18.
19. return 0;
20. }
Output: x = 107 y = a z = 108
Type Conversions
• Explicit Type Conversion : This process is also called type casting and it is user-defined. Here the user can
typecast the result to make it of a particular data type. In C++, it can be done by two ways:
• Converting by assignment: This is done by explicitly defining the required type in front of the expression
in parenthesis. This can be also considered as forceful casting.
• Syntax:
(type) expression
• where type indicates the data type to which the final result is converted.
1. // C++ program to demonstrate
2. // explicit type casting
3. #include <iostream>
4. using namespace std;
5. int main()
6. {
7. double x = 1.2;
8. // Explicit conversion from double to int
9. int sum = (int)x + 1;
10. cout << "Sum = " << sum;
11. return 0;
12. }
Output: Sum = 2
Type Conversions
• Conversion using Cast operator: A Cast operator is an unary operator which forces one data type
to be converted into another data type.
C++ supports four types of casting:
– Static Cast
– Dynamic Cast ***
newType result =castName<toType>(expression);
– Const Cast
– Reinterpret Cast
• Example:
const int a = 5;
1. #include <iostream>
int b = const_cast<int>(a);
2. using namespace std;
3. int main()
4. {
5. float f = 3.5;
6. // using cast operator
7. int b = static_cast<int>(f);
8. cout << b;
9. }
Output: 3
Conditional and looping
statements
• QUIZ ACTIVITY
Arrays
• QUIZ ACTIVITY
Class and Objects
• Class :
• A user-defined data type that we can use in our
program, and it works as an object constructor, or a
"blueprint" for creating objects.
• For example:
• car : an object.
• Attributes: weight and color
• Methods: drive, apply_brake
• Attributes: variables, methods: functions
• Attributes and methods are often referred to as "class
members".
Create a Class
• use the class keyword:
• Example
• Create a class called "MyClass":
• class MyClass { // The class
public: // Access specifier
int room_num; // Attribute (int variable)
string dept; // Attribute (string variable)
};
Explanation
• public: specifies that members (attributes and
methods) of the class are accessible from
outside the class.
• The class consists of an integer
variable room_num and a string-type
variable dept.
• When variables are declared within a class,
they are called attributes.
• The class definition ends with a semicolon (;)
Create an Object
• To create an object of MyClass, specify the class name, followed by the object name.
• To access the class attributes, use the object name, dot operator (.) and
variable/attribute name.
• Example
• Create an object called "myObj" and access the attributes:

• class MyClass { // The class


public: // Access specifier
int room_num; // Attribute (int variable)
string dept; // Attribute (string variable)
};
int main() {
MyClass myObj; // Create an object of MyClass
// Access attributes and set values
myObj.room_num = 602;
myObj.dept = ”dsbs";

// Print attribute values


cout << myObj.room_num << "\n";
cout << myObj.dept;
return 0;
}
Access Specifiers
• three access specifiers:
• public - members are accessible from outside the
class
• private - members cannot be accessed (or viewed)
from outside the class
• protected - members cannot be accessed from
outside the class, however, they can be accessed
in inherited classes.
Example
• class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}

• If you try to access a private member, an error occurs:


error: y is private
Methods
• Methods are functions that belongs to the class.
• There are two ways to define functions that
belongs to a class:
• Inside class definition
• Outside class definition
• Example
• define a function inside the class, and name it
"myMethod".
• Note: access methods by creating an object of the
class, using the dot operator (.), and the method
name.
Inside the class
class MyClass { // The class
public: // Access specifier
void myMethod() {
// Method inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Outside the class
• To define a function outside the class definition, declare the method
inside the class and then define it outside of the class.
• Define outside by specifying the name of the class, followed the scope
resolution :: operator, followed by the name of the function.
Example
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};
// Method/function definition outside the class
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Abstraction and Encapsulation
showing only use by fuctions in class
• Abstraction:
• 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.
• In C++, an abstraction is implemented by using a class, a
template, or a function.
Example:
• when we are driving a car, we are only concerned about driving the car
like start/stop the car, accelerate/ break, etc.
• We do not know how on pressing the accelerator the speed is actually
increasing, do not know about the inner mechanism of the car or the
implementation of the accelerator, brakes, etc in the car.

Abstraction: It's like using something without needing to know how it works
internally; you interact with the functionalities.
Types of Abstraction
• Data abstraction
• This type only shows the required information
about the data and hides the unnecessary data.
• Control Abstraction
• This type only shows the required information
about the implementation and hides unnecessary
information.
How do we implement abstraction?

• 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.
• Use the access specifiers : public and private.

• Example:
• the members that define the internal implementation can be marked as
private in a class.
• the important information needed to be given to the outside world can
be marked as public.
• the public members can access the private members as they are inside
the class.
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.
Example 1
• // C++ Program to Demonstrate the 16. void display()
• // working of Abstraction 17. {
1. #include <iostream> 18. cout << "a = " << a << endl;
2. using namespace std;
3. 19. cout << "b = " << b << endl;
4. Class AbstractionDemo { 20. }
5. private: 21. };
6. int a, b; 22.
7. 23. int main()
8. public: 24. {
9. // method to set values of
10. // private members
25. AbstractionDemo obj;
11. void set(int x, int y) 26. obj.set(10, 20);
12. { 27. obj.display();
13. a = x; 28. return 0;
14. b = y; 29. }
15. }

Output: a = 10 b = 20
we are not allowed to access the variables a and b directly. However, one can call the function set()
to set the values in a and b and the function display() to display the values of a and b.
Advantages of Data Abstraction

• Helps the user to avoid writing the low-level code


• Avoids code duplication and increases reusability.
• Can change the internal implementation of the
class independently without affecting the user.
• Helps to increase the security of an application or
program as only important details are provided to
the user.
• It reduces the complexity as well as the
redundancy of the code, therefore increasing the
readability.
Encapsulation
hiding info by private
• Hide the sensitive data from users.
• To achieve this, we declare class variables/attributes
as private so that it cannot be accessed from outside the
class.
• To allow others to read or modify the value of a private
member, we provide public get and set methods.
• Encapsulation ensures better control of your data, because
you (or others) can change one part of the code without
affecting other parts.
• It provides an increased security of data.
Encapsulation: It's like putting your code and data in a
container (class) to keep things organized.
Example
#include <iostream>
using namespace std; int main() {
Employee myObj;
class Employee { myObj.setSalary(50000);
private: cout << myObj.getSalary();
// Private attribute return 0;
int salary; }

public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
Explanation
• The salary attribute is private, it has restricted access.
• The public setSalary() method takes a parameter (s)
and assigns it to the salary attribute (salary = s).
• The public getSalary() method returns the value of the
private salary attribute.
• Inside main(), we create an object of
the Employee class.
• Now we can use the setSalary() method to set the value of
the private attribute to 50000.
• Then we call the getSalary() method on the object to return
the value.
UML Diagrams Introduction

• UML is not a programming language, it is rather a


visual language.
• We use UML diagrams to portray the behaviour and
structure of a system.
• UML helps software engineers, businessmen and
system architects with modelling, design and analysis.
• The Object Management Group (OMG) adopted
Unified Modelling Language as a standard in 1997.
• International Organization for Standardization (ISO)
published UML as an approved standard in 2005.
generalisation
dependence
associations to communicate
Need for UML Diagrams

• Complex applications need collaboration and


planning from multiple teams
• hence it requires a clear and concise way to
communicate amongst them.
• UML becomes essential to communicate the
following aspects with non programmers
• essential requirements, functionalities and processes
of the system.
• A lot of time is saved down the line when teams
are able to visualize processes, user interactions
and static structure of the system.
Classification of UML Diagrams

• Structural Diagrams
• Capture static aspects or structure of a system.
• Component Diagrams, Object Diagrams, Class
Diagrams and Deployment Diagrams.
• Behaviour Diagrams
• Capture dynamic aspects or behaviour of the
system.
• Use Case Diagrams, State Diagrams, Activity
Diagrams and Interaction Diagrams.
Use Case Diagram
• Use-case diagrams model the high-level
functions and scope of a system.
• Helps to identify the interactions between the
system and its actors.
• The use cases and actors in use-case diagrams
describe what the system does and how the
actors use it.
• but not how the system operates internally.
Elements of use case diagram
• Use cases

A use case describes a function that a system performs to achieve the user’s goal. A
use case must yield an observable result that is of value to the user of the system.
• Actors
An actor represents a role of a user that interacts with the system that you are
modeling.
• The user can be a human user, an organization, a machine, or another external system.
• Subsystems
In UML models, subsystems are a type of stereotyped component that represent
independent, behavioural units in a system.
• Subsystems are used in class, component, and use-case diagrams to represent large-scale
components in the system that you are modeling.
• Relationships in use-case diagrams
In UML, a relationship is a connection between model elements. A UML relationship
is a type of model element that adds semantics to a model by defining the structure
and behaviour between the model elements.
In simple terms, use cases help us understand what a system does for its users,
actors represent who interacts with the system, subsystems break down the
system into manageable parts, and relationships show how different parts are
connected in a diagram. These concepts are tools for modeling and
understanding complex systems.
Steps
• Analyze the whole system before starting with
drawing a use case diagram
• Find the system's functionalities
• List the actors that interact with the system
• Identify the relationship between the actor
and use case/ system.
• Basically, an actor can interact multiple times
with a use case or system at a particular
instance of time.
Example
• Create a use case diagram to depict the Online
Shopping website.
• the Web Customer actor makes use of any online shopping
website to purchase online.
• The top-level uses are as follows:
• View Items, Make Purchase, Checkout, Client Register.
• The View Items use case is utilized by the customer who
searches and view products.
• The Client Register use case allows the customer to
register itself with the website for availing gift vouchers,
coupons, or getting a private sale invitation.
• the Checkout is an included use case, which is part
of Making Purchase, and it is not available by itself.
last step before you officially buy something, whether online or in a
physical store.
Example
Use case: View Items
• The View Items is further extended by several use
cases such as.,
• Search Items, Browse Items, View Recommended Items,
Add to Shopping Cart, Add to Wish list.
• All of these extended use cases provide some functions to
customers, which allows them to search for an item.
• Both View Recommended Item and Add to Wish
List include the Customer Authentication use case, as
they necessitate authenticated customers.
• simultaneously item can be added to the shopping cart
without any user authentication.
Use case: View Items
Use case: Checkout
• the Checkout use case also includes the
following use cases:
• It requires an authenticated Web Customer, which
can be done by login page, user authentication
cookie ("Remember me"), or Single Sign-On (SSO).
• SSO needs an external identity provider's
participation.
• Web site authentication service is utilized in all
these use cases.
Use case: Checkout
• The Checkout use case involves Payment use case
that can be done either by the credit card and
external credit payment services or with PayPal.
Class diagram
• It depicts the static structure of a system by
showing system’s classes, interfaces, methods,
attributes, associations, collaboration, and
constraints imposed in the relationships.
• Helps to identify relationship between
different classes or objects.
Purpose of the class diagram
• Analysis and design of the static view of an
application.
• Describe responsibilities of a system.
• Base for component and deployment
diagrams.
• Forward and reverse engineering.
Steps
• Identify the meaningful name of the class diagram.
• Each element and their relationships should be identified in
advance.
• Responsibility (attributes and methods) of each class should be
clearly identified.
• For each class, minimum number of properties should be
specified, as unnecessary properties will make the diagram
complicated.
• Use notes whenever required to describe some aspect of the
diagram. At the end of the drawing it should be understandable to
the developer/coder.
• Finally, before making the final version, the diagram should be
drawn on plain paper and reworked as many times as possible to
make it correct.
Example
• Let us consider an example of an Order System of an
application. It describes a particular aspect of the entire
application.
• First of all, Order and Customer are identified as the two
elements of the system.
• They have a one-to-many relationship because a customer can
have multiple orders.
• Order class is an abstract class and it has two concrete
classes (inheritance relationship) SpecialOrder and
NormalOrder.
• The two inherited classes have all the properties as the
Order class.
• In addition, they have additional functions like dispatch () and
receive ().
Example
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
} As variables are declared in private, we can't assign them values directly. So, a constructor is
created with the same name as the class to initialize objects or attributes of the class with
desired values.
Constructors Example
class MyClass { // The class
public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
} the constructor is called automatically when an object
is created and is responsible for initializing the object,
};
while member functions are called explicitly to
perform actions or provide functionality.
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
from the same class int main() {
Example
// Create an object using the parameterized constructor
#include <iostream>
Wall wall1(10.5, 8.6);
using namespace std;
// declare a class
// Create another object using the copy constructor
class Wall {
Wall wall2 = wall1; or
private:
Wall wall2(wall1);
double length;
double height;
public:
// Calculate and display the area of both walls
cout << "Area of Wall 1: " << wall1.calculateArea() << " square units"
// initialize variables with parameterized constructor
Wall(double len, double hgt) { << endl;
length = len; cout << "Area of Wall 2: " << wall2.calculateArea() << " square units"
height = hgt; << endl;
}
return 0;
// copy constructor with a Wall object as parameter
// copies data of the obj parameter }
Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}
double calculateArea() {
return length * height;
}
};
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:
ouside the class---> return_type class_name : : operator op(argument_list)
{
// body of the function.
}

return_type operator symbol(argument_list){}


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 ++()


return_type operator symbol(argument_list){}
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;
}

You might also like