Oodp Unit 1
Oodp Unit 1
Oodp Unit 1
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.
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.
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;;
}
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;
return 0;
}
Output:
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.
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.
Usage of pointer
In c language, we can dynamically allocate memory using malloc() and calloc() functions
where pointer is used.
Pointers in c language are widely used in arrays, functions and structures. It reduces the code
and improves the performance.
Symbols used in pointer
#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:
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.
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;
■ 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
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
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.
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 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.
This statement creates in integer object int1 and passes the values 0 and 100 to it.
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.
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;
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.