CT 1
CT 1
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
• 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:
• 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
• 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=∑
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:
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?
• 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
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
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
• 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>()
{
}
• Example
#include <iostream>
using namespace std;
class Test {
public:
Test() {
cout << "\n Constructor executed"; }
~Test()
Polymorphism
}
Operator Overloading