0% found this document useful (0 votes)
20 views137 pages

Oodp Unit - I

Uploaded by

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

Oodp Unit - I

Uploaded by

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

18CS202J

Object Oriented Design and


Programming

Unit - 1
Comparison between procedural and object oriented
programming

Procedural Programming Object Oriented Programming


It deals with algorithms It deals with data
Programs are divided into functions Programs are divided into objects
Most of the functions share global data to Local declaration is possible
all the functions
Top down approach Bottom up approach
Doesn’t support exception handling Supports exception handling
Middle level language High level language
Data is not secured Data is hidden
OOPS features
1. Classes
• A class provides a template or a blueprint that describes the
structure and behavior of a set of similar objects.

• Once we have definition for a class, a specific instance of the


class can be easily created.

• Class is a collection of objects of similar type.

• Eg: fruit mango


class Student
{
private:
int rno;
char name[20]; Attributes/Data Members

float marks;
public:
get_details();
Operations/ Member function
show_details();
};
2. Objects

• Objects are the basic run time


entities in object oriented system.

• Object take up space in the


memory and have an associated
address like a record in pascal or a
structure in C.

• When a program is executed the


objects interact by sending
messages to one another.
3. Data Encapsulation

•The wrapping up of data and functions into a single unit is known as encapsulation.

•The data is not accessible to the outside world and only those functions which are
Wrapped in the class can access it.

•The insulation of the data from direct access by the program is called data hiding or
Information hiding.

4. Data Abstraction

•Abstraction refers to the act of representing essential features without including the
background details and explanations.
5. Inheritance

The inheritance is the process by which objects of one class acquire the properties of objects of
another class.

Base Class/ Parent/


Automobile Super class

Two Wheeler Three Wheeler Four Wheeler

Derived class/
Child/ Sub class
Scooter Motor Bike Auto Rickshaw Car Bus
Types of Inheritance

• Single level
• Multi level
• Multiple
• Hierarchical
• Hybrid
6. Polymorphism
• Ability to take more than one form.
• It includes
Function Overloading
Operator Overloading
7. Function Overloading
• Function Overloading refers to use of same function
name for different purposes. These functions differ from
each other by no. and types of arguments.

Draw()

Draw( int a ) Draw(int a , int b) Draw(int a , float b)


8. Operator Overloading

• Operator Overloading is a mechanism of redefining the


meaning of C++ operators.
• For example: +, - ,++, -- ,* etc.
9. Method and Message Passing

• A method is a function associated with a class.


• It defines the operations that the object can execute when it
receives a message.
• Objects communicate with one another by sending and
receiving information.
• Every object of the class has its own set of values.
10. Containership

• The ability of a class to contain objects of one or more classes


as member data.
• Eg: class 1 can have an object of class 2 as its data member.
• Containership is also called composition (has-a relationship).
• Class one is composed of class two.

Inheritance

composition
11. Genericity
• To reduce code duplication and generate short simpler code c+
+ supports the use of generic codes (or templates) to define the
same code for multiple data types.

• This means that a generic function can be invoked with


arguments of any compatible type.

Templates are of two types


• Function Template
• Class Template
Reusability & Delegation
• Developing codes that can be reused in same program or in
different programs.

• Reusability can be attained through inheritance, containership,


polymorphism and genericity.

• Delegation provides the maximum flexibility to generate


reusable codes.

• The property of delegation emphasizes on the ideology that a


complex object is made of several simpler objects.

• Delegate exhibits has-a relationship (Containership or


Composition).
Advantages of OOPs

• Data Security.
• Reusability of existing code.
• Creating new data types.
• Abstraction.
• Less development time.
• Reduce Complexity.
• Better Productivity.
Differences between C and C++

© Oxford University Press 2015. All rights r


eserved.
STRUCTURE OF C++ PROGRAM
Header files

input data output data

Keyboard executing Screen


program

• C++ treats input and output as a stream of characters.


• stream : sequence of characters (printable or nonprintable)
• The functions to allow standard I/O are in iostream header
file or iostream.h.
• Thus, we start every program with #include <iostream.h>
Insertion operator (<<)

• Variable cout is predefined to denote an output stream that


goes to the standard output device (display screen).

• The insertion operator << called “put to” takes 2 operands.

• The left operand is a stream expression, such as cout. The


right operand is an expression of simple type or a string
constant.
Extraction operator (>>)

• Variable cin is predefined to denote an input stream from


the standard input device (the keyboard)

• The extraction operator >> called “get from” takes 2


operands. The left operand is a stream expression, such as
cin--the right operand is a variable of simple type.

• Operator >> attempts to extract the next item from the


input stream and store its value in the right operand
variable
Syntax for output statements

SYNTAX
cout << Expression << Expression . . . ;

cout statements can be linked together using << operator.


These examples yield the same output:

cout << “The answer is “ ;


cout << 3 * 4 ;

cout << “The answer is “ << 3 * 4 ;


Output: The answer is 12
Output statements

• String constants (in double quotes) are to be printed as is,


without the quotes.

cout<<“Enter the number of candy bars ”;


OUTPUT: Enter the number of candy bars
“Enter the number of candy bars ” is called a prompt.

• All user inputs must be preceded by a prompt to tell the user


what is expected.

• You must insert spaces inside the quotes if you want them in
the output.
Syntax for input statements

SYNTAX
cin >> Variable >> Variable . . . ;

cin statements can be linked together using >> operator.


These examples yield the same output:

cin >> x;
cin >> y;

cin >> x >> y;


User inputs: 3 4
Assigns x = 3 and y = 4
Cascading of Input or Output Operators

• We can use the << operator multiple times in the same line.
This is called cascading.
• Similar to cout, cin can also be cascaded. For example,
Reading and Writing Characters and Strings

string name;
getline(cin, name);
cout<“Welcome “<<name;
Formatted Input and Output Operations
Formatting with flags

• The setf() is a member function of the ios 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 and 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 .
• cout.setf(ios::left, ios::adjustfield);
• cout.setf(ios::left);
Formatting Output Using Manipulators
• C++ has a header file iomanip.h that contains
certain manipulators to format the output
Data Types in C++
C++ Data Types

simple structured

integral enum floating array struct union class

char short int long bool

address
float double long double

pointer reference
What is a Variable?

• A variable is a memory address where


data can be stored and changed.

• Declaring a variable means specifying


both its name and its data type.
Variable Declaration

• All variables must declared before use.


– At the top of the program
– Just before use.
• Commas are used to separate identifiers of
the same type.
int count, age;

• Variables can be initialized to a starting


value when they are declared
int count = 0;
int age, count = 0;
What Does a
Variable Declaration Do?

• A declaration tells the compiler to


allocate enough memory to hold a value
of this data type, and to associate the
identifier with the location.
• int ageOfDog;
• char middleInitial; 
• float taxRate;
Reference Variables
• Reference variable is a new feature added to C++. A reference variable
basically assigns an alternative name (alias) to an existing variable.
• For example, if we want a variable num to be a reference to the variable n ,
then n and num can be interchangeably used to represent that variable.
• This is same as if someone calls us by our nick name or by our formal
name, both names refer to the same person.
• Therefore, if we write
Constants
• Syntax: const type identifier = value;
• Ex: const double TAX_RATE = 0.08;
• Convention: use upper case for constant
ID.
C++ Constants are also like normal variables. But, only difference is, their
values can not be modified by the program once they are defined.
Constants refer to fixed values. They are also called as literals
Constants may be belonging to any of the data type.
Syntax:

const data_type variable_name;


Example
Const float TAX =0.08;

Types of C constant:
Numeric Constant
Integer constants ex. 10 20 -30
Real or Floating point constants ex 10.34 -90.30 0.6e4
Character Constant
Character constants ex. ‘3’ ‘a’
String constants ex.”Chennai” “preethi”
Type Conversions
• Concept of converting the value of one type into
another type.
• Two types of conversion
– Implicit Conversion
• Conversion done automatically
• Loss of data will be there, no control in our side.
– Explicit Conversion
• We have control of converting it from one type to another.
• We can prevent loss of data.
int main()
{
int a;
double b=12.5;
a=b;
Implicit Type Conversion
cout<<a;
a=int (b);
Explicit Type Conversion
cout<<a;
}
Explicit type conversion
int main()
Output
{ a=25
b=35.87
int a = 25; Converts int to float = 25.00
Converts float to int = 35
float b = 35.87;
cout<<“a=“<<a;
cout<<“b=“<<b;
cout<<“ converts int to float”<<float(a);
cout<<“converts float to int”<<int(b);
return 0;
}
Pointers
• A pointer is a variable whose value is the address of
another variable.
• type *var-name;
• int *ip; // pointer to an integer
• double *dp; // pointer to a double
• float *fp; // pointer to a float
• char *ch // pointer to character
(a) We define a pointer variable.
(b) Assign the address of a variable to a pointer.
(c) Finally access the value at the address available in the
pointer variable.
Classes
Access specifier
• Access modifiers or Access Specifiers in a class are used to
set the accessibility of the class members.
• There are 3 types of access modifiers available in C++
– Public
– Private
– Protected
Public - The members declared as Public are accessible from
outside the Class through an object of the class.
Protected - The members declared as Protected are accessible
from outside the class BUT only in a class derived from it.
Private - These members are only accessible from within the
class. No outside Access is allowed.
Member Functions in Classes

• There are 2 ways to define a member function:


– Inside class definition
– Outside class definition

• To define a member function outside the class


definition we have to use the scope resolution ::
operator along with class name and function name.
• // C++ program to demonstrate function • // Definition of printname using scope resolution
• // declaration outside class operator ::
• void student::printname()
• #include <bits/stdc++.h> • {
• using namespace std; • cout << “Name is: " << name;
• class student • }
• { • int main() {
• public: •
• string name; • student obj1;
• int id; • obj1.name = "xyz";
• • obj1.id=15;
• // printname is not defined inside •
class defination • // call printname()
• void printname(); • obj1.printname();
• • cout << endl;
• // printid is defined inside class •
defination • // call printid()
• void printid() • obj1.printid();
• { • return 0;
• cout << " Id is: " << id; • }
• }
• };
• // C++ program to demonstrate function • // Definition of printname using scope resolution
• // declaration outside class operator ::
• void student::printname()
• #include <bits/stdc++.h> • {
• using namespace std; • cout << “Name is: " << name;
• class student • }
• { • int main() {
• public: •
• string name; • student obj1;
• int id; • obj1.name = "xyz";
• • obj1.id=15;
• // printname is not defined inside •
class defination • // call printname()
• void printname(); • obj1.printname();
• • cout << endl;
• // printid is defined inside class •
defination • // call printid()
• void printid() • obj1.printid();
• { • return 0;
• cout << " Id is: " << id; • }
• }
• };
Output:
Name is: xyz
Id is: 15
Accessing Object Members
• class sample • }
• { • };
• private: • int main()
• int a; • {
• void fun1() • sample s;
Wrong, Private cannot be accessed in main()
• { • s.a=1;
Wrong, fun1() is private
• ….. • s.fun1();
Right, b is public
• } • s.b=2;
Right, fun2 is public
• public: • s.fun2();
• int b; • a=3;
Wrong because of
• void fun2() • b=4; Without objects

• { • fun2();
• ….. • }
Nested Member function
• A member function can be called by using its name inside another
member function of the same class is known as nesting of member
functions.
class rectangle
{
private:
float length;
float breadth;
public:
void get_data() { cin>>length>>breadth;}
voidshow_data()
{cout<<“length”<<length<<“breadth”<<breadth<<“area=“<<area(); }
int area()
{ return length*breadth;}
};
Inline Member Function
• A member function that is defined inside its class member list is called
an inline member function. Member functions containing a few lines of code
are usually declared inline.
class rectangle
{
private:
float length;
float breadth;
public:
void get_data() { cin>>length>>breadth;}
void show_data();
};
inline void rectangle :: show_data(void)
{
cout<<“length”<<length<<“breadth”<<breadth;
}
Pointers

• int main()
• {
• int *pnum
• char *pch;
• float *pfnum;
• double *pdnum;
• cout<<sizeof(pnum);
• cout<<sizeof(pch);
• cout<<sizeof(pfnum);
• cout<<sizeof(pdnum);
Pointers

• int main()
• { Output
8
• int *pnum 8
• char *pch; 8
8
• float *pfnum;
• double *pdnum;
• cout<<sizeof(pnum);
• cout<<sizeof(pch);
• cout<<sizeof(pfnum);
• cout<<sizeof(pdnum);
Dereferencing Pointers
int main()
{
int num,*pnum;
pnum=&num;
cout<<“Enter the number”;
cin>>num;
cout<<*pnum;
cout<<&num;
}
Dereferencing Pointers
int main()
{
int num,*pnum;
pnum=&num;
cout<<“Enter the number”; Output
cin>>num; Enter the number : 15
15
cout<<*pnum; FFDC
cout<<&num;
}
Rules for Pointer Operations
• A pointer variable can be assigned the address of another
variable (of the same type).
• A pointer variable can be assigned the value of another
pointer variable (of the same type).
• A pointer variable can be initialized with a NULL (or 0) value.
• Prefix and postfix increment and decrement operators can be
applied on a pointer variable.
• An integer value can added or subtracted from a pointer
variable.
• A pointer variable cannot be multiplied by a constant.
• A pointer variable cannot be added to another pointer
variable.
• A pointer variable can be compared with another pointer
variable of the same type using relational operators.
Example Program for Pointers
• #include <iostream>
• using namespace std;
• int main()
• {
• int p,*pv=NULL;
• int *pv2=0,*pv3=0;
• cin>>p;
• pv=&p;
• cout<<*pv<<endl;
• cout<<pv;
• pv2=pv;
• cout<<*pv2<<endl;
Example Program for Pointers
• #include <iostream>
• using namespace std;
• int main()
• {
• int p,*pv=NULL; //Rule 3 pointer variable INITIALIZED to NULL
• int *pv2=0,*pv3=0; // Rule 3 pointer variable initialized to zero
• cin>>p;
• pv=&p; //"1.Pointer variable assigned to the address of another variable“
• cout<<*pv<<endl;
• cout<<pv;
• pv2=pv; //pv2 is assigned with the address of p
• //"2.Pointer variable assigned to the value of another ptr variable“
• cout<<*pv2<<endl;
• cout<<"4.Pointer variable can use ++and -- operators"<<pv2--<<endl;
• cout<<"4.Pointer variable can use ++and -- operators"<<*pv2--<<endl;
• cout<<"4...Pointer variable can use ++and -- operators"<<++pv<<endl;
• cout<<"5... Added or subtracted from the pointer variable"<<pv+5<<endl;
• cout<<"5... Added or subtracted from the pointer variable"<<pv-3<<endl;
• cout<<"6... multiplied to a constant"<<*pv**pv2<<endl;
• const int z=5;
• cout << pv2*z; //is not possible
• cout<<pv+pv2; //is not possible
• return 0;
• }
Null Pointer
• Null pointer which is a special pointer value that is known not
to point anywhere.
• Null pointer does not point to any valid memory address.

• You can check whether a given pointer variable stores address


of some variable or contains a null
If (ptr==NULL)
{
Sts block;
}
• You may also initialize a pointer as a NULL pointer by using a
constant 0.
Pointers to Pointers
• C++ use pointers that point to pointers. The pointers in turn
point to data (or even to other pointers).
• To declare pointers to pointers add an asterisk (*) for each
level of reference.
int x=10;
int *px; x px ppx
int **ppx;
10 1002 2004
px=&x;
1002 2004 4008
ppx=&px;
Cout<<**ppx;
Pointers and Arrays

• assigning the address of array to pointer


don’t use ampersand sign(&)
#include <iostream>
using namespace std;
int main(){ OUTPUT:
//Pointer declaration 1
int *p; 2
//Array declaration 3
int arr[]={1, 2, 3, 4, 5, 6}; 4
//Assignment 5
p = arr; 6
for(int i=0; i<6;i++){
cout<<*p<<endl;
//++ moves the pointer to next int position
p++;
}
return 0;
}
Function using pointers
void swap(int *a,int *b)
#include<iostream> {
int c;
using namespace std;
c=*a;
void swap(int *a ,int *b ); *a=*b;
//Call By Reference *b=c;
int main() }
{
int p,q; Output:
cout<<"\nEnter Two Number You Want To Swap \n"; Enter Two Number You Want to Swap
cin>>p>>q; 10 20
swap(&p,&q); After Swapping Numbers Are Given below
20 10
cout<<"\nAfter Swapping Numbers Are Given below\n\n";
cout<<p<<" "<<q<<" \n";
return 0;
}
Constant Pointer
• A constant pointer is a pointer that cannot change the
address it is storing.
• Once assigned the address of a variable the constant
pointer cannot be made to point to any other variable.
• The value at the address pointed by the constant
pointer may be changed.
datatype *const ptr_var = init address;
• char *const ptr = &c;
• *ptr =‘B’
Class and objects

Class:

• Class is a user defined data type,


• It holds its own data members and member functions,
• It can be accessed and used by creating instance of that class.
• The variables inside class definition are called as data members and
the functions are called member functions
• Class name must start with an uppercase letter(Although this is not mandatory).
Example,
class Student
• Classes contain, data members and member functions, and the access of these
data members and variable depends on the access specifiers.
• Class's member functions can be defined inside the class definition or outside
the class definition.
• class defaults to private access control,
• Objects of class hold separate copies of data members. We can create as many
objects of a class as we need.
• No storage is assigned when we define a class.
Define a Class Type
Syntax: Example:
Name of the
class
class Rectangle
keyword class Class_name {
{ private:
int width;
permission_label:
member; int length;
Body
public:
permission_label: void set(int w, int l);
member;
int area();
...
};
};
- Data members Can be of any type, built-in or
user-defined.
This may be,
• non-static data member
Each class object has its own copy

• static data member


Acts as a global variable

71
• Static data member is declared using the static keyword.
• There is only one copy of the static data member in the
class. All the objects share the static data member.
• The static data member is always initialized to zero when
the first class object is created.

Syntax:
static data_type datamember_name;
Here
static is the keyword.
data_type – int , float etc…
datamember_name – user defined

72
Static Data Member
Rectangle r1;
class Rectangle Rectangle r2;
{ Rectangle r3;
private:
int width;
int length; count

static int count;


r1 r2
public: width width
void set(int w, int l); length length

int area(); width


r3 length
}
Member Functions

• Used to
– access the values of the data members (accessor)
– perform operations on the data members
(implementor)
• Are declared inside the class body
• Their definition can be placed inside the class
body, or outside the class body
• Can access both public and private members of
the class
• Can be referred to using dot or arrow member
access operator

74
Member function
keyword Class Name
class Rectangle
{ int main()
private: {
int width, length; Rectangle r2; Object creation
public: r1.set(5,8); Inside the
void set (int w, int l); int x=r1.area(); function
member
int area() cout<<"x value in r1 "<<x;
function
{ r2.set(4,9);
inside the class return width*length; x=r2.area();
} class name cout<<"x value in r2 "<<x;
}r1; Member function }
Object void Rectangle :: set (int w, int l)
creation {
width = w; outside the class
length = l;
}
scope operator
Const Member Function
• The const member functions are the functions which are declared as constant in
the program.
• The object called by these functions cannot be modified.
• It is recommended to use const keyword so that accidental changes to object
are avoided.
• A const member function can be called by any type of object.
• Note: Non-const functions can be called by non-const objects only.

User defined
Syntax: keyword

datatype function_name const();


Const Member Function
class Time
{
private : function declaration
int hrs, mins, secs ;

public :
void Write ( ) const ;
function definition
};

void Time :: Write( ) const


{
cout <<hrs << “:” << mins << “:” << secs << endl;
}

77
What is an object?

OBJECT
set of methods
Operations (member functions)

Data internal state


(values of private data members)

78
Object:
• Objects are instances of class, which holds the data variables declared in
class and the member functions work on these class objects.
• Each object has different data variables.
• Objects are initialized using special class functions called Constructors.
• Destructor is special class member function, to release the memory reserved
by the object.

Syntax of creating object :


Class_name object_name;
Declaration of an Object

class Rectangle
main()
{ {
private: Rectangle r1;
Rectangle r2;
int width;
int length; r1.set(5, 8);
public: cout<<r1.area()<<endl;

void set(int w, int l); r2.set(8,10);


int area(); cout<<r2.area()<<endl;
}
};

80
Another Example

#include <iostream.h> // member function definitions

class circle void circle::store(double r)


{ {
radius = r;
private: }
double radius;
double circle::area(void)
public: {
return 3.14*radius*radius;
void store(double); }
double area(void);
void display(void); void circle::display(void)
{
cout << “r = “ << radius <<
}; endl;
}
int main(void) {
circle c; // an object of circle class
c.store(5.0);
cout << "The area of circle c is " << c.area() << endl;
c.display();
}

81
Declaration of an Object
class Rectangle
{
private:
int width;
int length; main()
{
public: Rectangle r1;
void set(int w, int l); r1.set(5, 8);
int area(); }
};
r1
width = 5
length = 8
void Rectangle :: set(int w, int l)
{
width=w;
length=l;
}
82
Declaration of an Object

r2 is a pointer to a Rectangle object


class Rectangle
{ main()
{
private: Rectangle r1;
int width; r1.set(5, 8); //dot notation

int length; Rectangle *r2;


r2 = &r1;
public: r2->set(8,10); //arrow notation
void set(int w, int l); }

int area();
r1 r2
}; width = 8
5
length = 10
8 5000
???

5000 6000

83
Object Initialization
1. By Assignment

#include <iostream.h>
• Only work for public data
members
class circle
{ • No control over the operations
public: on data members
double radius;
};
int main()
{
circle c1; // Declare an instance of the class circle
c1.radius = 5; // Initialize by assignment

84
Object Initialization
2. By Public Member Functions

#include <iostream.h>
class circle
{
private:
double radius;
public:
void set (double r)
{radius = r;}
double get_r ()
{return radius;}
};
int main(void) {
circle c; // an object of circle class
c.set(5.0); // initialize an object with a public member function
cout << "The radius of circle c is " << c.get_r() << endl;
// access a private data member with an accessor
}

85
UML diagram Introduction
• Unified Modeling Language (UML) is a general purpose
modelling language. The main aim of UML is to define a
standard way to visualize the way a system has been designed.
• UML is not a programming language, it is rather a visual
language. We use UML diagrams to portray the behavior and
structure of a system.
Diagrams in UML can be broadly classified as:
• Structural Diagrams – Capture static aspects or structure of
a system. Structural Diagrams include: Component Diagrams,
Object Diagrams, Class Diagrams and Deployment Diagrams.
• Behavior Diagrams – Capture dynamic aspects or behavior
of the system. Behavior diagrams include: Use Case Diagrams,
State Diagrams, Activity Diagrams and Interaction Diagrams.
Object Oriented Concepts Used in UML

• Class – A class defines the blue print i.e. structure and


functions of an object.
• Objects – Objects help us to decompose large systems and
help us to modularize our system.
• An object is the fundamental unit (building block) of a system
which is used to depict an entity.
• Inheritance – Inheritance is a mechanism by which child
classes inherit the properties of their parent classes.
• Abstraction – representing essential features without
including the background details and explanations.
• Encapsulation – Binding data together and protecting it from
the outer world is referred to as encapsulation.
• Polymorphism – Mechanism by which functions or entities
are able to exist in different forms.
The building blocks of UML can be defined as
• Things
• Relationships
• Diagrams
Things
Things are the most important building blocks of
UML. Things can be −
• Structural
• Behavioral
• Grouping
• Annotational
UML Diagrams
UML includes the following nine diagrams
• Class diagram
• Object diagram
• Use case diagram
• Sequence diagram
• Collaboration diagram
• Activity diagram
• Statechart diagram
• Deployment diagram
• Component diagram
Class Notation: Static Structure
• A class is drawn as a rectangle with three components separated by
horizontal lines.

• The top name compartment holds the class name, other general properties of
the class, such as attributes, are in the middle compartment, and the bottom
compartment holds a list of operations.

• Either or both the attribute and operation compartments may be suppressed.

• A separator line is not drawn for a missing compartment if a compartment is


suppressed; no inference can be drawn about the presence or absence of
elements in it.
• The class name and other properties should be displayed in up to three
sections.
Classes
Access specifier
• Access modifiers or Access Specifiers in a class are used to
set the accessibility of the class members.
• There are 3 types of access modifiers available in C++
– Public +
– Private -
– Protected #
Public - The members declared as Public are accessible from
outside the Class through an object of the class.
Protected - The members declared as Protected are accessible
from outside the class BUT only in a class derived from it.
Private - These members are only accessible from within the
class. No outside Access is allowed.
Aggregation implies a relationship where the child can exist
independently of the parent. Example: Class (parent) and Student
(child). Delete the Class and the Students still exist.

Composition implies a relationship where the child cannot exist


independent of the parent. Example: House (parent) and Room
(child). Rooms don't exist separate to a House.
Aggregation
• Aggregation is a form of association.
• A hollow diamond is attached to the end of the path
to indicate aggregation.
Composition
• It also know as the a-part-of, is a form of aggregation with
strong ownership to represent the component of a complex
object.
• Composition also is referred to as a part-whole relationship.
• The UML notation for composition is a solid diamond at the
end of a path.
• Alternatively, the UML provides a graphically nested form
that, in many cases, is more convenient for showing
composition.
Composition
Generalization vs Specialization
• Generalization is a mechanism for combining similar classes of objects
into a single, more general class. Generalization identifies commonalities
among a set of entities. The commonality may be of attributes, behavior, or
both.
• A superclass has the most general attributes, operations, and relationships
that may be shared with subclasses. A subclass may have more specialized
attributes and operations.
• Specialization is the reverse process of Generalization means creating new
sub classes from an existing class.
Multiplicity (Cardinality)
• Place multiplicity notations near the ends of an association.
• These symbols indicate the number of instances of one class
linked to one instance of the other class.
• For example, one company will have one or more employees,
but each employee works for just one company.
Abstraction
• Abstraction is specifying the framework and hiding the
implementation level information.
• Abstraction reduces the complexity by hiding low level
details.
• Example: A wire frame model of a car.
• Abstract classes cannot have any objects.
• Exist only for other classes to inherit from it.
• Concrete classes are used to instantiate objects.
Association Role
• A simple association –the technical term for it is binary association
– is drawn as a solid line connecting two class symbols.
• The end of an association, where it connects to a class, shows the
association role.
• The role is part of the association, not part of the class.
• Each association has two or more roles to which it is connected.
• The UML uses the term association navigation or navigability to
specify a role affiliated with each end of an association relationship.
• An arrow may be attached to the end of the path to indicate that
navigation is supported in the direction of class pointed to.
• An arrow may be attached to neither, one, or both ends of the
path.
Person BankAccount
Binary association notation
• A binary association is drawn as a solid path connecting two
classes, or both ends may be connected to the same class.
• An association may have an association name.
• The association name may have an optional black triangle in
it, the point of the triangle indicating the direction in which to
read the name.
• The end of an association, where it connects to a class, is
called the association role.

Person

marriedTo
Class Interface notation
• Class interface notation is used to describe the externally visible
behavior of a class; for example, an operation with public visibility.
• The UML notation for an interface is a small circle with the name of
the connected to the class.
• A class that requires the operations in the interface may be
attached to the circle by a dashed arrow .
• The dependent class is not required to actually use all of the
operations.
• For example, a person object may need to interact with the
BankAccount object to get the balance; this relationship is depicted
with UML class interface notation.

Person BankAccount
Object Diagram
• A static object diagram is an instance of a class
diagram.
• It shows a snapshot of the detailed state of
the system at a point in time.
• Notation is the same for an object diagram
and a class diagram.
Object Notation
• The object is represented in the same way as the
class. The only difference is the name which is
underlined.
• As the object is an actual implementation of a class,
which is known as the instance of a class. Hence, it
has the same usage as the class.

Mrs.B.Ida Seraphim AP/CSE


Static
• Static elements are allocated storage only once in a
program lifetime in static storage area.

• They have a scope till the program lifetime.

Static Keyword can be used with following,


– Static variable in functions
– Static Class Objects
– Static member Variable in class
– Static Methods in class
Static Variables inside Functions
• Static variables when used inside function are initialized only
once, and then they hold their value even through function
calls.
• These static variables are stored on static storage area , not in
stack.
Static Class Objects
• Static keyword works in the same way for class objects too.

• Objects declared static are allocated storage in static storage


area, and have scope till the end of program.

• Static objects are also initialized using constructors like


other normal objects.

• Assignment to zero, on using static keyword is only for


primitive data types, not for user defined data types.
Output
Constructor
END
destructor
Static Data Member in Class
• Static data members of class are those members which are
shared by all the objects.

• Static member variables (data members) are not initialized


using constructor, because these are not dependent on object
initialization.

• Once the definition for static data member is made, user


cannot redefine it. Though, arithmetic operations can be
performed on it.
Output
1
Static Member Functions

• These functions work for the class as whole rather


than for a particular object of a class.

• It can be called using an object and the direct


member access . operator.

• But, its more typical to call a static member function


by itself, using class name and scope
resolution :: operator.
Output
Static Member Function
Static Member Function
• These functions cannot access ordinary data
members and member functions, but only static
data members and static member functions.

• It doesn't have any "this" keyword which is the


reason it cannot access ordinary members.
Constructor
A constructor is a special member function of a class which is
automatically invoked at the time of creation of an object to
initialize or construct the values of data members of the object.
Features of constructor
• Constructor has same name as the class itself.
• A constructor must be declared in the public section.
• Constructor should not be called explicitly because a constructor is
automatically invoked when an object of a class is created.
• A constructor never return any value.
• A constructor cannot be inherited or virtual.
• The address of a constructor cannot be referred to in programs.
• A constructor cannot be declared as static or const.
• Like normal function, constructor function can also be overloaded.
• Like normal function, constructor function also have default
arguments.
Types of Constructors
Dummy Constructor (Do Nothing
Constructor)
• Dummy constructor which does not perform any action.
• Action means does not initialize any data member and thus
the variable acquire a garbage value.

Output
X=3938 (garbage value)
Default Constructors
• Default constructor is the constructor which doesn’t
take any argument. It has no parameters.

Output
a: 10
b: 20
Parameterized Constructors

• It is possible to pass arguments to constructors.

• Arguments help initialize an object when it is created.

• To create a parameterized constructor, simply add parameters


to it the way you would to any other function.

• When you define the constructor’s body, use the parameters


to initialize the object.
Output
X=10
Copy Constructor
• A copy constructor takes an object of the class as an
argument and copies data values of members of one object
into the values of members of another object.

• Since it takes only one argument it is also called one argument


constructor.

• The primary use of copy constructor is to create a new object


from an existing one by initialization.

• The copy constructor takes the reference to an object of the


same class as an argument.
Output
X=10
X=10
Destructor
• Like constructor a destructor is also a member
function that is automatically invoked.

• Job of destructor is to destroy the object.

• It deallocates the memory that is dynamically


allocated to the variable or perform other clean up
operations.
Features of Destructor
• The name of the destructor is same as that of class name but it should
preceded by the tilde symbol ~.
• Destructor is called when the object goes out of scope.
• It is called when the programmer explicitly deletes an object using the
delete operator.
• Like constructor, a destructor also declared in the public section.
• The order of invoking a destructor is the reverse of invoking a
constructor.
• Destructor do not take any arguments and thus cannot be
overloaded.
• A destructor does not return any value.
• A destructor must be specifically defined to free the resources such
as memory.
• The address of the destructor cannot be accessed in the program.
• Constructor or destructor cannot be inherited.
• Unlike constructors, destructor can be virtual.
Output
constructor called for object with value: 1
constructor called for object with value: 2
constructor called for object with value: 3
Destructor called for object with value: 3
Destructor called for object with value: 2
Destructor called for object with value: 1
Friend Function

• If a function is defined as a friend function then, the private


and protected data of a class can be accessed using the
function.

• The complier knows a given function is a friend function by


the use of the keyword friend.

• For accessing the data, the declaration of a friend function


should be made inside the body of the class (can be anywhere
inside class either in private or public section) starting with
keyword friend.

• Friend function help implement data encapsulation in c++.


• Declaration of friend function
Features of Friend Function
• Friend function is the normal external function that is given
special access privileges.
• The friend declaration can be placed either in the private or
public section.
• A friend function of the class can be a member and friend of
some other class.
• A friend function of one class can be friend of another class.
• Since friend function are non members of the class they do not
require this pointer.
• The keyword friend is placed only in the function declaration
and not in the function definition.
• A friend function can access the class members directly using
the object name and dot operator followed by the specific
member.
• A function can be declared as friend in any number of classes.
Friend function

Output
Mean value: 32.5
Friend Class

Output
Sum:55
Use Case diagram
• The purpose of use case diagram is to capture the dynamic aspect of a
system.
• Used for describing a set of user scenarios
• Mainly used for capturing user requirements
• Work like a contract between end user and software developers.
• Use case Core components
• Actors: A role that a user plays with respect to the system, including
human users and other systems. e.g.,inanimate physical objects (e.g. robot);
an external system that needs some information from the current system.
• Use case: A set of scenarios that describing an interaction between a user
and a system, including alternatives.

• System boundary: Rectangle diagram representing the boundary


between the actors and the system.
Use Case Diagram(core relationship)

• Include: a dotted line labeled <<include>> beginning at base


use case and ending with an arrows pointing to the include use
case. The include relationship occurs when a chunk of
behavior is similar across more than one use case. Use
“include” in stead of copying the description of that behavior.
<<include>>

• Extend: a dotted line labeled <<extend>> with an arrow toward the


base case. The extending use case may add behavior to the base use case.
The base class declares “extension points”.
<<extend>>
Use Case Diagrams

Boundary Use Case


Actor
Library System

Borrow
Employee
Client

Order Title

Fine Remittance

Supervisor

• A generalized description of how a system will be used.


• Provides an overview of the intended functionality of the system
Use Case Diagrams(cont.)

(TogetherSoft, Inc)
Class and objects
• class student "<<endl;
• { • cin >> total;
• private: • perc=total/500*100;
• char name[30]; • }
• int rollNo; • //member function definition, outside of the
• int total; class
• float perc; • void student::putDetails(void){
• public: • cout << "Student details:\n";
• //member function to get student's details • cout << "Name:"<< name<<endl << "Roll
• void getDetails(void); Number:" << rollNo <<endl<< "Total:" <<
total<<endl << "Percentage:" << perc<<endl;
• //member function to print student's details
• }
• void putDetails(void);
• };
• int main()
• //member function definition, outside of the
class • {
• void student::getDetails(void){ • student std; //object creation
• cout << "Enter name: " <<endl; • std.getDetails();
• cin >> name; • std.putDetails();
• cout << "Enter roll number: "<<endl; • return 0;
• cin >> rollNo; • }
• cout << "Enter total marks outof 500:
Output
Enter name: Ram
Enter roll number: 123
Enter total marks out of 500: 455
Student details:
Name: Ida
Roll Number:123
Total:455
Percentage:91
GCD of two numbers

Output
62 8
GCD of 62 and 8 is 2

You might also like