OOPS_Concept.ppt

70
CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3 (Common to CSE & IT) Aim: To understand the concepts of object-oriented programming and master OOP using C++. Unit I 9 Object oriented programming concepts – objects – classes – methods and messages – abstraction and encapsulation – inheritance – abstract classes – polymorphism. Introduction to C++ – classes – access specifiers – function and data members – default arguments – function overloading – friend functions – const and volatile functions – static members – Objects – pointers and objects – constant objects – nested classes – local classes Unit II 9 Constructors – default constructor – Parameterized constructors – Constructor with dynamic allocation – copy constructor – destructors – operator overloading – overloading through friend functions – overloading the assignment operator – type conversion – explicit constructor Unit III 9 Function and class templates - Exception handling – try-catch-throw paradigm – exception specification – terminate and Unexpected functions – Uncaught exception. Unit IV 9 Inheritance – public, private, and protected derivations – multiple inheritance – virtual base class – abstract class – composite objects Runtime polymorphism – virtual functions – pure virtual functions – RTTI – typeid – dynamic casting – RTTI and templates – cross casting – down casting . Unit V 9 Streams and formatted I/O – I/O manipulators - file handling – random access – object serialization – namespaces - std namespace – ANSI String Objects – standard template library. Total: 45 TEXT BOOKS: 1. B. Trivedi, “Programming with ANSI C++”, Oxford University Press, 2007. REFERENCES: 1. Ira Pohl, “Object Oriented Programming using C++”, Pearson Education, Second Edition Reprint 2004.. 2. S. B. Lippman, Josee Lajoie, Barbara E. Moo, “C++ Primer”, Fourth Edition, Pearson Education, 2005. 3. B. Stroustrup, “The C++ Programming language”, Third edition, Pearson Education, 2004.

description

ppt

Transcript of OOPS_Concept.ppt

Page 1: OOPS_Concept.ppt

CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3 (Common to CSE amp IT)AimTo understand the concepts of object-oriented programming and master OOP using C++

Unit I 9Object oriented programming concepts ndash objects ndash classes ndash methods and messages ndash abstraction and encapsulation ndash inheritance ndash abstract

classes ndash polymorphism Introduction to C++ ndash classes ndash access specifiers ndash function and data members ndash default arguments ndash function overloading ndash friend functions ndash const and volatile functions ndash static members ndash Objects ndash pointers and objects ndash constant objects ndash nested classes ndash local classes

Unit II 9Constructors ndash default constructor ndash Parameterized constructors ndash Constructor with dynamic allocation ndash copy constructor ndash destructors ndash

operator overloading ndash overloading through friend functions ndash overloading the assignment operator ndash type conversion ndash explicit constructor

Unit III 9Function and class templates - Exception handling ndash try-catch-throw paradigm ndash exception specification ndash terminate and Unexpected functions ndash

Uncaught exceptionUnit IV 9Inheritance ndash public private and protected derivations ndash multiple inheritance ndash virtual base class ndash abstract class ndash composite objects Runtime

polymorphism ndash virtual functions ndash pure virtual functions ndash RTTI ndash typeid ndash dynamic casting ndash RTTI and templates ndash cross casting ndash down casting

Unit V 9Streams and formatted IO ndash IO manipulators - file handling ndash random access ndash object serialization ndash namespaces - std namespace ndash ANSI String

Objects ndash standard template library Total 45TEXT BOOKS1 B Trivedi ldquoProgramming with ANSI C++rdquo Oxford University Press 2007REFERENCES1 Ira Pohl ldquoObject Oriented Programming using C++rdquo Pearson Education SecondEdition Reprint 20042 S B Lippman Josee Lajoie Barbara E Moo ldquoC++ Primerrdquo Fourth EditionPearson Education 20053 B Stroustrup ldquoThe C++ Programming languagerdquo Third edition PearsonEducation 2004

Unit I

Object oriented programming concepts ndash objects ndash classes ndash methods and messages ndash abstraction and encapsulation ndash inheritance ndash abstract classes ndash polymorphism

Introduction to C++ ndash classes ndash access specifiers ndash function and data members ndash default arguments ndash function overloading ndash friend functions ndash const and volatile functions ndash static members ndash Objects ndash pointers and objects ndash constant objects ndash nested classes ndash local classes

3

Objects An object is an encapsulation of both functions and data

bull Objects are an Abstractionndash represent real world entitiesndash Classes are data types that define shared common properties or attributesndash Objects are instances of a classndash All objects have attributes (characteristics) this is sometimes referred to as state bull Objects have State ndash have a value at a particular time

bull Objects have Operations ndash associated set of operations called methods that describe how to carry out operations

(behavior)bull Objects have Messages

ndash request an object to carry out one of its operations by sending it a messagendash messages are the means by which we exchange data between objects

Classes

bull Class Whatever we can see in this world all the things are a object And all the objects are categorized in a special group That group is termed as a class

bull Class has many other features like creation and implementation of the object Inheritance etc

classesbull Every object belongs to (is an instance of) a classbull An object may have fields or variables

ndash The class describes those fieldsbull An object may have methods

ndash The class describes those methodsbull An Abstract Data Type (ADT) bundles together

ndash some data representing an object or thingndash the operations on that data

bull The operations defined by the ADT are the only operations permitted on its data

bull Example a CheckingAccount with operations deposit withdraw getBalance etc

Problem printing student mark sheetbull Class studentbull Real world entities student teacher subject mark sheet etc

Class student Public int RollNo string name string address void PrintDetails() cout ltltrollno cout ltltname cout ltlt address

TV-01 Class and 3 Instances

Object-Oriented Concept

bull The rectangle area problembull Define a class Rect

ndash Data width lengthndash Functions compute_area()

bull An object an instance of the class Rectndash To Solve the problem create an object of Rect

and request this object to return the area of the rectangle

Encapsulation

class Circle

privateint radius

public Circle(int r)

The area of a circle

int compute_area()

class Triangle

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

The area of a triangle

int compute_area()

Example Codeclass Rect

private

int width length

public

Rect (int w int l)

width = w

length = l

int compute_area()

return widthlength

main()

Rect rect1(35) int x

x=rect1compute_area()coutltltxltltendl

Methods amp Messages

bull Sending a message is our way ofndash interacting with objectsndash manipulating an objectrsquos statebull Tells the object what to do with itself Example To change the channel on TVndash We use the channel selection buttons This sends a message

that we want to select a new channelndash The TV responds to the message by selecting and executing a

methodndash The TV now receives a new signal which is the channel we

selected

Methodndash Tells the object how to respond to a messageOur TV-01 objects respond to thefollowing messagesndash Turn the television set on or offndash Change the channelndash Change the volume

Characteristics of OOPL

bull Encapsulation Combining data structure with actionsndash Data structure represents the properties the states or characteristics of

objectsndash Actions permissible behaviors that are controlled through the member

functions

Data hiding Process of making certain data inaccessible bull Inheritance Ability to derive new objects from old ones

ndash permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more generalbase class

ndash ability to define a hierarchical relationship between objects

bull Polymorphism Ability for different objects to interpret functions differently

O-O Principles and C++ Constructs

O-O Concept C++ Construct(s)

Abstraction Classes Encapsulation ClassesInformation Hiding Public and Private MembersPolymorphism Operator overloading

templates virtual functionsInheritance Derived Classes

OOP Features

bull 4 major features in OOPndash encapsulationndash information hidingndash inheritancendash overloading

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 2: OOPS_Concept.ppt

Unit I

Object oriented programming concepts ndash objects ndash classes ndash methods and messages ndash abstraction and encapsulation ndash inheritance ndash abstract classes ndash polymorphism

Introduction to C++ ndash classes ndash access specifiers ndash function and data members ndash default arguments ndash function overloading ndash friend functions ndash const and volatile functions ndash static members ndash Objects ndash pointers and objects ndash constant objects ndash nested classes ndash local classes

3

Objects An object is an encapsulation of both functions and data

bull Objects are an Abstractionndash represent real world entitiesndash Classes are data types that define shared common properties or attributesndash Objects are instances of a classndash All objects have attributes (characteristics) this is sometimes referred to as state bull Objects have State ndash have a value at a particular time

bull Objects have Operations ndash associated set of operations called methods that describe how to carry out operations

(behavior)bull Objects have Messages

ndash request an object to carry out one of its operations by sending it a messagendash messages are the means by which we exchange data between objects

Classes

bull Class Whatever we can see in this world all the things are a object And all the objects are categorized in a special group That group is termed as a class

bull Class has many other features like creation and implementation of the object Inheritance etc

classesbull Every object belongs to (is an instance of) a classbull An object may have fields or variables

ndash The class describes those fieldsbull An object may have methods

ndash The class describes those methodsbull An Abstract Data Type (ADT) bundles together

ndash some data representing an object or thingndash the operations on that data

bull The operations defined by the ADT are the only operations permitted on its data

bull Example a CheckingAccount with operations deposit withdraw getBalance etc

Problem printing student mark sheetbull Class studentbull Real world entities student teacher subject mark sheet etc

Class student Public int RollNo string name string address void PrintDetails() cout ltltrollno cout ltltname cout ltlt address

TV-01 Class and 3 Instances

Object-Oriented Concept

bull The rectangle area problembull Define a class Rect

ndash Data width lengthndash Functions compute_area()

bull An object an instance of the class Rectndash To Solve the problem create an object of Rect

and request this object to return the area of the rectangle

Encapsulation

class Circle

privateint radius

public Circle(int r)

The area of a circle

int compute_area()

class Triangle

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

The area of a triangle

int compute_area()

Example Codeclass Rect

private

int width length

public

Rect (int w int l)

width = w

length = l

int compute_area()

return widthlength

main()

Rect rect1(35) int x

x=rect1compute_area()coutltltxltltendl

Methods amp Messages

bull Sending a message is our way ofndash interacting with objectsndash manipulating an objectrsquos statebull Tells the object what to do with itself Example To change the channel on TVndash We use the channel selection buttons This sends a message

that we want to select a new channelndash The TV responds to the message by selecting and executing a

methodndash The TV now receives a new signal which is the channel we

selected

Methodndash Tells the object how to respond to a messageOur TV-01 objects respond to thefollowing messagesndash Turn the television set on or offndash Change the channelndash Change the volume

Characteristics of OOPL

bull Encapsulation Combining data structure with actionsndash Data structure represents the properties the states or characteristics of

objectsndash Actions permissible behaviors that are controlled through the member

functions

Data hiding Process of making certain data inaccessible bull Inheritance Ability to derive new objects from old ones

ndash permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more generalbase class

ndash ability to define a hierarchical relationship between objects

bull Polymorphism Ability for different objects to interpret functions differently

O-O Principles and C++ Constructs

O-O Concept C++ Construct(s)

Abstraction Classes Encapsulation ClassesInformation Hiding Public and Private MembersPolymorphism Operator overloading

templates virtual functionsInheritance Derived Classes

OOP Features

bull 4 major features in OOPndash encapsulationndash information hidingndash inheritancendash overloading

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 3: OOPS_Concept.ppt

3

Objects An object is an encapsulation of both functions and data

bull Objects are an Abstractionndash represent real world entitiesndash Classes are data types that define shared common properties or attributesndash Objects are instances of a classndash All objects have attributes (characteristics) this is sometimes referred to as state bull Objects have State ndash have a value at a particular time

bull Objects have Operations ndash associated set of operations called methods that describe how to carry out operations

(behavior)bull Objects have Messages

ndash request an object to carry out one of its operations by sending it a messagendash messages are the means by which we exchange data between objects

Classes

bull Class Whatever we can see in this world all the things are a object And all the objects are categorized in a special group That group is termed as a class

bull Class has many other features like creation and implementation of the object Inheritance etc

classesbull Every object belongs to (is an instance of) a classbull An object may have fields or variables

ndash The class describes those fieldsbull An object may have methods

ndash The class describes those methodsbull An Abstract Data Type (ADT) bundles together

ndash some data representing an object or thingndash the operations on that data

bull The operations defined by the ADT are the only operations permitted on its data

bull Example a CheckingAccount with operations deposit withdraw getBalance etc

Problem printing student mark sheetbull Class studentbull Real world entities student teacher subject mark sheet etc

Class student Public int RollNo string name string address void PrintDetails() cout ltltrollno cout ltltname cout ltlt address

TV-01 Class and 3 Instances

Object-Oriented Concept

bull The rectangle area problembull Define a class Rect

ndash Data width lengthndash Functions compute_area()

bull An object an instance of the class Rectndash To Solve the problem create an object of Rect

and request this object to return the area of the rectangle

Encapsulation

class Circle

privateint radius

public Circle(int r)

The area of a circle

int compute_area()

class Triangle

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

The area of a triangle

int compute_area()

Example Codeclass Rect

private

int width length

public

Rect (int w int l)

width = w

length = l

int compute_area()

return widthlength

main()

Rect rect1(35) int x

x=rect1compute_area()coutltltxltltendl

Methods amp Messages

bull Sending a message is our way ofndash interacting with objectsndash manipulating an objectrsquos statebull Tells the object what to do with itself Example To change the channel on TVndash We use the channel selection buttons This sends a message

that we want to select a new channelndash The TV responds to the message by selecting and executing a

methodndash The TV now receives a new signal which is the channel we

selected

Methodndash Tells the object how to respond to a messageOur TV-01 objects respond to thefollowing messagesndash Turn the television set on or offndash Change the channelndash Change the volume

Characteristics of OOPL

bull Encapsulation Combining data structure with actionsndash Data structure represents the properties the states or characteristics of

objectsndash Actions permissible behaviors that are controlled through the member

functions

Data hiding Process of making certain data inaccessible bull Inheritance Ability to derive new objects from old ones

ndash permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more generalbase class

ndash ability to define a hierarchical relationship between objects

bull Polymorphism Ability for different objects to interpret functions differently

O-O Principles and C++ Constructs

O-O Concept C++ Construct(s)

Abstraction Classes Encapsulation ClassesInformation Hiding Public and Private MembersPolymorphism Operator overloading

templates virtual functionsInheritance Derived Classes

OOP Features

bull 4 major features in OOPndash encapsulationndash information hidingndash inheritancendash overloading

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 4: OOPS_Concept.ppt

Classes

bull Class Whatever we can see in this world all the things are a object And all the objects are categorized in a special group That group is termed as a class

bull Class has many other features like creation and implementation of the object Inheritance etc

classesbull Every object belongs to (is an instance of) a classbull An object may have fields or variables

ndash The class describes those fieldsbull An object may have methods

ndash The class describes those methodsbull An Abstract Data Type (ADT) bundles together

ndash some data representing an object or thingndash the operations on that data

bull The operations defined by the ADT are the only operations permitted on its data

bull Example a CheckingAccount with operations deposit withdraw getBalance etc

Problem printing student mark sheetbull Class studentbull Real world entities student teacher subject mark sheet etc

Class student Public int RollNo string name string address void PrintDetails() cout ltltrollno cout ltltname cout ltlt address

TV-01 Class and 3 Instances

Object-Oriented Concept

bull The rectangle area problembull Define a class Rect

ndash Data width lengthndash Functions compute_area()

bull An object an instance of the class Rectndash To Solve the problem create an object of Rect

and request this object to return the area of the rectangle

Encapsulation

class Circle

privateint radius

public Circle(int r)

The area of a circle

int compute_area()

class Triangle

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

The area of a triangle

int compute_area()

Example Codeclass Rect

private

int width length

public

Rect (int w int l)

width = w

length = l

int compute_area()

return widthlength

main()

Rect rect1(35) int x

x=rect1compute_area()coutltltxltltendl

Methods amp Messages

bull Sending a message is our way ofndash interacting with objectsndash manipulating an objectrsquos statebull Tells the object what to do with itself Example To change the channel on TVndash We use the channel selection buttons This sends a message

that we want to select a new channelndash The TV responds to the message by selecting and executing a

methodndash The TV now receives a new signal which is the channel we

selected

Methodndash Tells the object how to respond to a messageOur TV-01 objects respond to thefollowing messagesndash Turn the television set on or offndash Change the channelndash Change the volume

Characteristics of OOPL

bull Encapsulation Combining data structure with actionsndash Data structure represents the properties the states or characteristics of

objectsndash Actions permissible behaviors that are controlled through the member

functions

Data hiding Process of making certain data inaccessible bull Inheritance Ability to derive new objects from old ones

ndash permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more generalbase class

ndash ability to define a hierarchical relationship between objects

bull Polymorphism Ability for different objects to interpret functions differently

O-O Principles and C++ Constructs

O-O Concept C++ Construct(s)

Abstraction Classes Encapsulation ClassesInformation Hiding Public and Private MembersPolymorphism Operator overloading

templates virtual functionsInheritance Derived Classes

OOP Features

bull 4 major features in OOPndash encapsulationndash information hidingndash inheritancendash overloading

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 5: OOPS_Concept.ppt

classesbull Every object belongs to (is an instance of) a classbull An object may have fields or variables

ndash The class describes those fieldsbull An object may have methods

ndash The class describes those methodsbull An Abstract Data Type (ADT) bundles together

ndash some data representing an object or thingndash the operations on that data

bull The operations defined by the ADT are the only operations permitted on its data

bull Example a CheckingAccount with operations deposit withdraw getBalance etc

Problem printing student mark sheetbull Class studentbull Real world entities student teacher subject mark sheet etc

Class student Public int RollNo string name string address void PrintDetails() cout ltltrollno cout ltltname cout ltlt address

TV-01 Class and 3 Instances

Object-Oriented Concept

bull The rectangle area problembull Define a class Rect

ndash Data width lengthndash Functions compute_area()

bull An object an instance of the class Rectndash To Solve the problem create an object of Rect

and request this object to return the area of the rectangle

Encapsulation

class Circle

privateint radius

public Circle(int r)

The area of a circle

int compute_area()

class Triangle

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

The area of a triangle

int compute_area()

Example Codeclass Rect

private

int width length

public

Rect (int w int l)

width = w

length = l

int compute_area()

return widthlength

main()

Rect rect1(35) int x

x=rect1compute_area()coutltltxltltendl

Methods amp Messages

bull Sending a message is our way ofndash interacting with objectsndash manipulating an objectrsquos statebull Tells the object what to do with itself Example To change the channel on TVndash We use the channel selection buttons This sends a message

that we want to select a new channelndash The TV responds to the message by selecting and executing a

methodndash The TV now receives a new signal which is the channel we

selected

Methodndash Tells the object how to respond to a messageOur TV-01 objects respond to thefollowing messagesndash Turn the television set on or offndash Change the channelndash Change the volume

Characteristics of OOPL

bull Encapsulation Combining data structure with actionsndash Data structure represents the properties the states or characteristics of

objectsndash Actions permissible behaviors that are controlled through the member

functions

Data hiding Process of making certain data inaccessible bull Inheritance Ability to derive new objects from old ones

ndash permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more generalbase class

ndash ability to define a hierarchical relationship between objects

bull Polymorphism Ability for different objects to interpret functions differently

O-O Principles and C++ Constructs

O-O Concept C++ Construct(s)

Abstraction Classes Encapsulation ClassesInformation Hiding Public and Private MembersPolymorphism Operator overloading

templates virtual functionsInheritance Derived Classes

OOP Features

bull 4 major features in OOPndash encapsulationndash information hidingndash inheritancendash overloading

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 6: OOPS_Concept.ppt

Problem printing student mark sheetbull Class studentbull Real world entities student teacher subject mark sheet etc

Class student Public int RollNo string name string address void PrintDetails() cout ltltrollno cout ltltname cout ltlt address

TV-01 Class and 3 Instances

Object-Oriented Concept

bull The rectangle area problembull Define a class Rect

ndash Data width lengthndash Functions compute_area()

bull An object an instance of the class Rectndash To Solve the problem create an object of Rect

and request this object to return the area of the rectangle

Encapsulation

class Circle

privateint radius

public Circle(int r)

The area of a circle

int compute_area()

class Triangle

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

The area of a triangle

int compute_area()

Example Codeclass Rect

private

int width length

public

Rect (int w int l)

width = w

length = l

int compute_area()

return widthlength

main()

Rect rect1(35) int x

x=rect1compute_area()coutltltxltltendl

Methods amp Messages

bull Sending a message is our way ofndash interacting with objectsndash manipulating an objectrsquos statebull Tells the object what to do with itself Example To change the channel on TVndash We use the channel selection buttons This sends a message

that we want to select a new channelndash The TV responds to the message by selecting and executing a

methodndash The TV now receives a new signal which is the channel we

selected

Methodndash Tells the object how to respond to a messageOur TV-01 objects respond to thefollowing messagesndash Turn the television set on or offndash Change the channelndash Change the volume

Characteristics of OOPL

bull Encapsulation Combining data structure with actionsndash Data structure represents the properties the states or characteristics of

objectsndash Actions permissible behaviors that are controlled through the member

functions

Data hiding Process of making certain data inaccessible bull Inheritance Ability to derive new objects from old ones

ndash permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more generalbase class

ndash ability to define a hierarchical relationship between objects

bull Polymorphism Ability for different objects to interpret functions differently

O-O Principles and C++ Constructs

O-O Concept C++ Construct(s)

Abstraction Classes Encapsulation ClassesInformation Hiding Public and Private MembersPolymorphism Operator overloading

templates virtual functionsInheritance Derived Classes

OOP Features

bull 4 major features in OOPndash encapsulationndash information hidingndash inheritancendash overloading

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 7: OOPS_Concept.ppt

TV-01 Class and 3 Instances

Object-Oriented Concept

bull The rectangle area problembull Define a class Rect

ndash Data width lengthndash Functions compute_area()

bull An object an instance of the class Rectndash To Solve the problem create an object of Rect

and request this object to return the area of the rectangle

Encapsulation

class Circle

privateint radius

public Circle(int r)

The area of a circle

int compute_area()

class Triangle

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

The area of a triangle

int compute_area()

Example Codeclass Rect

private

int width length

public

Rect (int w int l)

width = w

length = l

int compute_area()

return widthlength

main()

Rect rect1(35) int x

x=rect1compute_area()coutltltxltltendl

Methods amp Messages

bull Sending a message is our way ofndash interacting with objectsndash manipulating an objectrsquos statebull Tells the object what to do with itself Example To change the channel on TVndash We use the channel selection buttons This sends a message

that we want to select a new channelndash The TV responds to the message by selecting and executing a

methodndash The TV now receives a new signal which is the channel we

selected

Methodndash Tells the object how to respond to a messageOur TV-01 objects respond to thefollowing messagesndash Turn the television set on or offndash Change the channelndash Change the volume

Characteristics of OOPL

bull Encapsulation Combining data structure with actionsndash Data structure represents the properties the states or characteristics of

objectsndash Actions permissible behaviors that are controlled through the member

functions

Data hiding Process of making certain data inaccessible bull Inheritance Ability to derive new objects from old ones

ndash permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more generalbase class

ndash ability to define a hierarchical relationship between objects

bull Polymorphism Ability for different objects to interpret functions differently

O-O Principles and C++ Constructs

O-O Concept C++ Construct(s)

Abstraction Classes Encapsulation ClassesInformation Hiding Public and Private MembersPolymorphism Operator overloading

templates virtual functionsInheritance Derived Classes

OOP Features

bull 4 major features in OOPndash encapsulationndash information hidingndash inheritancendash overloading

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 8: OOPS_Concept.ppt

Object-Oriented Concept

bull The rectangle area problembull Define a class Rect

ndash Data width lengthndash Functions compute_area()

bull An object an instance of the class Rectndash To Solve the problem create an object of Rect

and request this object to return the area of the rectangle

Encapsulation

class Circle

privateint radius

public Circle(int r)

The area of a circle

int compute_area()

class Triangle

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

The area of a triangle

int compute_area()

Example Codeclass Rect

private

int width length

public

Rect (int w int l)

width = w

length = l

int compute_area()

return widthlength

main()

Rect rect1(35) int x

x=rect1compute_area()coutltltxltltendl

Methods amp Messages

bull Sending a message is our way ofndash interacting with objectsndash manipulating an objectrsquos statebull Tells the object what to do with itself Example To change the channel on TVndash We use the channel selection buttons This sends a message

that we want to select a new channelndash The TV responds to the message by selecting and executing a

methodndash The TV now receives a new signal which is the channel we

selected

Methodndash Tells the object how to respond to a messageOur TV-01 objects respond to thefollowing messagesndash Turn the television set on or offndash Change the channelndash Change the volume

Characteristics of OOPL

bull Encapsulation Combining data structure with actionsndash Data structure represents the properties the states or characteristics of

objectsndash Actions permissible behaviors that are controlled through the member

functions

Data hiding Process of making certain data inaccessible bull Inheritance Ability to derive new objects from old ones

ndash permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more generalbase class

ndash ability to define a hierarchical relationship between objects

bull Polymorphism Ability for different objects to interpret functions differently

O-O Principles and C++ Constructs

O-O Concept C++ Construct(s)

Abstraction Classes Encapsulation ClassesInformation Hiding Public and Private MembersPolymorphism Operator overloading

templates virtual functionsInheritance Derived Classes

OOP Features

bull 4 major features in OOPndash encapsulationndash information hidingndash inheritancendash overloading

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 9: OOPS_Concept.ppt

Encapsulation

class Circle

privateint radius

public Circle(int r)

The area of a circle

int compute_area()

class Triangle

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

The area of a triangle

int compute_area()

Example Codeclass Rect

private

int width length

public

Rect (int w int l)

width = w

length = l

int compute_area()

return widthlength

main()

Rect rect1(35) int x

x=rect1compute_area()coutltltxltltendl

Methods amp Messages

bull Sending a message is our way ofndash interacting with objectsndash manipulating an objectrsquos statebull Tells the object what to do with itself Example To change the channel on TVndash We use the channel selection buttons This sends a message

that we want to select a new channelndash The TV responds to the message by selecting and executing a

methodndash The TV now receives a new signal which is the channel we

selected

Methodndash Tells the object how to respond to a messageOur TV-01 objects respond to thefollowing messagesndash Turn the television set on or offndash Change the channelndash Change the volume

Characteristics of OOPL

bull Encapsulation Combining data structure with actionsndash Data structure represents the properties the states or characteristics of

objectsndash Actions permissible behaviors that are controlled through the member

functions

Data hiding Process of making certain data inaccessible bull Inheritance Ability to derive new objects from old ones

ndash permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more generalbase class

ndash ability to define a hierarchical relationship between objects

bull Polymorphism Ability for different objects to interpret functions differently

O-O Principles and C++ Constructs

O-O Concept C++ Construct(s)

Abstraction Classes Encapsulation ClassesInformation Hiding Public and Private MembersPolymorphism Operator overloading

templates virtual functionsInheritance Derived Classes

OOP Features

bull 4 major features in OOPndash encapsulationndash information hidingndash inheritancendash overloading

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 10: OOPS_Concept.ppt

Example Codeclass Rect

private

int width length

public

Rect (int w int l)

width = w

length = l

int compute_area()

return widthlength

main()

Rect rect1(35) int x

x=rect1compute_area()coutltltxltltendl

Methods amp Messages

bull Sending a message is our way ofndash interacting with objectsndash manipulating an objectrsquos statebull Tells the object what to do with itself Example To change the channel on TVndash We use the channel selection buttons This sends a message

that we want to select a new channelndash The TV responds to the message by selecting and executing a

methodndash The TV now receives a new signal which is the channel we

selected

Methodndash Tells the object how to respond to a messageOur TV-01 objects respond to thefollowing messagesndash Turn the television set on or offndash Change the channelndash Change the volume

Characteristics of OOPL

bull Encapsulation Combining data structure with actionsndash Data structure represents the properties the states or characteristics of

objectsndash Actions permissible behaviors that are controlled through the member

functions

Data hiding Process of making certain data inaccessible bull Inheritance Ability to derive new objects from old ones

ndash permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more generalbase class

ndash ability to define a hierarchical relationship between objects

bull Polymorphism Ability for different objects to interpret functions differently

O-O Principles and C++ Constructs

O-O Concept C++ Construct(s)

Abstraction Classes Encapsulation ClassesInformation Hiding Public and Private MembersPolymorphism Operator overloading

templates virtual functionsInheritance Derived Classes

OOP Features

bull 4 major features in OOPndash encapsulationndash information hidingndash inheritancendash overloading

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 11: OOPS_Concept.ppt

Methods amp Messages

bull Sending a message is our way ofndash interacting with objectsndash manipulating an objectrsquos statebull Tells the object what to do with itself Example To change the channel on TVndash We use the channel selection buttons This sends a message

that we want to select a new channelndash The TV responds to the message by selecting and executing a

methodndash The TV now receives a new signal which is the channel we

selected

Methodndash Tells the object how to respond to a messageOur TV-01 objects respond to thefollowing messagesndash Turn the television set on or offndash Change the channelndash Change the volume

Characteristics of OOPL

bull Encapsulation Combining data structure with actionsndash Data structure represents the properties the states or characteristics of

objectsndash Actions permissible behaviors that are controlled through the member

functions

Data hiding Process of making certain data inaccessible bull Inheritance Ability to derive new objects from old ones

ndash permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more generalbase class

ndash ability to define a hierarchical relationship between objects

bull Polymorphism Ability for different objects to interpret functions differently

O-O Principles and C++ Constructs

O-O Concept C++ Construct(s)

Abstraction Classes Encapsulation ClassesInformation Hiding Public and Private MembersPolymorphism Operator overloading

templates virtual functionsInheritance Derived Classes

OOP Features

bull 4 major features in OOPndash encapsulationndash information hidingndash inheritancendash overloading

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 12: OOPS_Concept.ppt

Methodndash Tells the object how to respond to a messageOur TV-01 objects respond to thefollowing messagesndash Turn the television set on or offndash Change the channelndash Change the volume

Characteristics of OOPL

bull Encapsulation Combining data structure with actionsndash Data structure represents the properties the states or characteristics of

objectsndash Actions permissible behaviors that are controlled through the member

functions

Data hiding Process of making certain data inaccessible bull Inheritance Ability to derive new objects from old ones

ndash permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more generalbase class

ndash ability to define a hierarchical relationship between objects

bull Polymorphism Ability for different objects to interpret functions differently

O-O Principles and C++ Constructs

O-O Concept C++ Construct(s)

Abstraction Classes Encapsulation ClassesInformation Hiding Public and Private MembersPolymorphism Operator overloading

templates virtual functionsInheritance Derived Classes

OOP Features

bull 4 major features in OOPndash encapsulationndash information hidingndash inheritancendash overloading

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 13: OOPS_Concept.ppt

Characteristics of OOPL

bull Encapsulation Combining data structure with actionsndash Data structure represents the properties the states or characteristics of

objectsndash Actions permissible behaviors that are controlled through the member

functions

Data hiding Process of making certain data inaccessible bull Inheritance Ability to derive new objects from old ones

ndash permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more generalbase class

ndash ability to define a hierarchical relationship between objects

bull Polymorphism Ability for different objects to interpret functions differently

O-O Principles and C++ Constructs

O-O Concept C++ Construct(s)

Abstraction Classes Encapsulation ClassesInformation Hiding Public and Private MembersPolymorphism Operator overloading

templates virtual functionsInheritance Derived Classes

OOP Features

bull 4 major features in OOPndash encapsulationndash information hidingndash inheritancendash overloading

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 14: OOPS_Concept.ppt

O-O Principles and C++ Constructs

O-O Concept C++ Construct(s)

Abstraction Classes Encapsulation ClassesInformation Hiding Public and Private MembersPolymorphism Operator overloading

templates virtual functionsInheritance Derived Classes

OOP Features

bull 4 major features in OOPndash encapsulationndash information hidingndash inheritancendash overloading

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 15: OOPS_Concept.ppt

OOP Features

bull 4 major features in OOPndash encapsulationndash information hidingndash inheritancendash overloading

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 16: OOPS_Concept.ppt

Encapsulationbull an object encapsulates both its attributes amp

methodsbull implications

ndash an attribute method is attached to an object classndash when you mention an attribute methods you have to

specify which object class it comes frombull why encapsulation

ndash when you get hold of an object you also get hold of its data amp behaviour components

ndash good for reuse

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 17: OOPS_Concept.ppt

Information Hiding

bull an object can hide its internal detailsndash eg you donrsquot know how your mobilersquos electronics works

except punching the buttonsbull can selectively show some details to the outside

worldndash eg your mobile only shows the number it dials

bull defines an ldquointerfacerdquo to interact with the outside worldndash eg your mobile interacts with your through the buttons amp

screen

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 18: OOPS_Concept.ppt

Why Information Hiding

bull the object can have a complex internal but simple interfacendash making interaction with the outside world easier

bull you donrsquot need to know about the internal of an objectndash only the interface is importantndash ie how to interact with it

bull facilitate code reusendash hiding any internal change from the outside world by

keeping the interface unchanged

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 19: OOPS_Concept.ppt

Inheritance

bull a class may be similar to another class but being more specialisedndash eg the class ldquostudentrdquo is similar to the class

ldquopersonrdquo but ldquostudentrdquo is more specialisedbull a person has attributes like sex age namebull a student has all these + a student no

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 20: OOPS_Concept.ppt

Inheritance (contrsquod)bull a subclass

ndash extends specialises a superclassndash inherits attributes amp methods from its superclassndash may have more attributes methods than its superclassndash may change the content procedure of an inherited

methodbull ie same method name signature but different behaviour

bull why inheritancendash reuse existing class definitionndash customise specialise if needed

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 21: OOPS_Concept.ppt

Overloading

bull different functions procedures methods can have the same namendash provided that the parameters are of different types

bull giving a unique ldquosignaturerdquondash the system will figure out which one to invokendash eg you can have 2 procedures both named ldquocallrdquo

taking a ldquodogrdquo or ldquopersonrdquo object as parameter respectively Depending on you give it a ldquodogrdquo or ldquopersonrdquo object as the parameter Java will know which one to use

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 22: OOPS_Concept.ppt

Why Overloading

bull you can call the same method (name) but invoke different behaviourndash dynamic binding of method

bull which method to invoke is determined at runtime

bull code reusendash in term of the ldquocallingrdquo code

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 23: OOPS_Concept.ppt

bull Encapsulation is the mechanism that binds together code and data and keeps both safe from outside interference or misuse

1 Both data and member functions treated as single unit2 Abstract focuses on behavior of object encapsulation focuses on actual implementation 3 Encapsulation achieved through data hiding 4 For abstractions to work implementations must be encapsulated

bull

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 24: OOPS_Concept.ppt

Abstract Types

class Shape

public Shape()

Calculate the area for this shapevirtual int compute_area() = 0

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 25: OOPS_Concept.ppt

ABSTRACTION AND ENCAPSULATION

1048707 Definition Data Encapsulation or Information Hiding is theconcealing of the implementation details of a data objectfrom the outside world1048707 Definition Data Abstraction is the separation betweenthe specification of a data object and its implementation1048707 Definition A data type is a collection of objects and a setof operations that act on those objects1048707 Definition An abstract data type (ADT) is a data typethat is organized in such a way that the specification of theobjects and the specification of the operations on theobjects is separated from the representation of the objectsand the implementation of the operation

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 26: OOPS_Concept.ppt

bull Advantages of Data Abstraction andData Encapsulation1048707 Simplification of software development1048707 Testing and Debugging1048707 Reusability1048707 Modifications to the representation of a data

type

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 27: OOPS_Concept.ppt

Abstract Classes

May Contain abstract methodsbull Some methods and data may be definedabstract class ColouredShape private Colour c storage allocated for eachpublic abstract void draw()public Colour getColour() return cpublic abstract void erase()bull No instances allowedbull Subclasses must implement all abstract methods orthey are also abstract

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 28: OOPS_Concept.ppt

Florida Community College at Jacksonville

Object-oriented Principle - Inheritance

bull Inheritance is the process by which one object acquires the properties of another object By use of inheritance an object need only define all of its characteristics that make it unique within its class it can inherit its general attributes from its parent

29 of 10 slides

Account

Checking Mortgage Loan

COP 2551 Object-Oriented Programming OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 29: OOPS_Concept.ppt

Florida Community College at Jacksonville

Object-oriented Principle ndash Encapsulation

bull Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safe from outside interference and misuse

30 of 10 slides

A Class

Private variables and methods

Public variables and methods

Public variables is not recommended

COP 2551 Object-Oriented Programming OO Concepts Overview

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 30: OOPS_Concept.ppt

bull Encapsulationbull Hides the implementation details of a classbull Forces the user to use an interface to access

databull Makes the code more maintainablebull API doc as an example

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 31: OOPS_Concept.ppt

Inheritance and Polymorphismclass Circle public Shape

privateint radius

public Circle (int r)int

compute_area()

class Triangle public Shape

privateint edgea edgeb

edgecpublic

Triangle (int a int b int c)

int compute_area()int sum_area(Shape s1 Shape s2)

return s1compute_area() + s2compute_area()

Example of polymorphism

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 32: OOPS_Concept.ppt

INTRODUCTION TO C++

Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 33: OOPS_Concept.ppt

Basic C++ Extension from C comments

You can still use the old comment style but you must be very careful about mixing them Its best to use this style for 1 line or partial lines And use this style when your comment

consists of multiple lines

cin and cout (and include ltiostreamhgt)cout ltlt ldquoHellochar name[10]cin gtgt namecout ltlt ldquoHi ltlt name ltlt nice name ltlt endl

cout ltlt endl print a blank line declaring variables almost anywhere

declare a variable when you need it for (int k = 1 k lt 5 k++)

char a=lsquomrsquo

cout ltlt k ltlt a

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 34: OOPS_Concept.ppt

CLASSES

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 35: OOPS_Concept.ppt

A Graphical Representation of Classes

colournamewhere

attributes(data

component)

methods(proceduralcomponent)

interfaceto the

outside world walkswimbark

the Dog classthe Person class

nameown

walkinstruct

write_email

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 36: OOPS_Concept.ppt

A Graphical Representation of Objects

colour whitebrownname Lassiewhere Annur

walkswimbark

name Raviown Lassie

walkinstruct

write_email

Ravi a Person object Lassie a Dog objectcolour yellow

name Pakiwhere xxx

walkswimbark

Paki a Dog object

hellip another Dog object

nameRajaown null

walkinstruct

write_email

Raja a Person object

hellip another Dog objecthellip another Person object

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 37: OOPS_Concept.ppt

Access specifiers

bull Specify whether the data defined will be available to the users of the objects of the class

bull Publicbull Privatebull Protectedbull Public the data defined under public is available to

objectsbull Private data defined under private is not available to

objects

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 38: OOPS_Concept.ppt

Class student Public int RollNo private string name string address

public

void PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo does not work since name is privatestudent1address= ldquoYrdquo does not work since name is private Student1PrintDetails()

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 39: OOPS_Concept.ppt

Function and data memberbull Functions can be defined either inside or outside the classbull Defining function members outside class1 very simple to define functions outside class2 If the functions are bigmdashdefine outsidebull Static data members of class1 Static members are stored at a location where they are retained

throughout the execution of the program and are not stored with class objects

2 Stored only as a single copyndash similar to member functions3 All the static data members are initialized to zero at the time of

declaration

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 40: OOPS_Concept.ppt

Class student defining function members outside classPublic int RollNo string name string address void PrintDetails() prototype

void student PrintDetails() cout ltltrollno cout ltltname cout ltlt address void main() student student1 student1RollNo= 7 student1name= ldquoXrdquo student1address= ldquoYrdquo Student1PrintDetails()

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 41: OOPS_Concept.ppt

class student public static int PassingMark int SubjectMark[5] bool fail void DisplayMarks() for (int i=0ilt5++i) cout ltltldquoMarks of subject Nordquo cout ltltiltltldquoisrdquo ltltSubjectMark[i] void SetMarks (int Marks[5] for (int i=0 ilt5 ++i) SubjectMarks[i]=Marks[i] bool CheckPassing() fail=false for (int i=0ilt5 ++i) if (SubjectMark[i]ltPassingMark) fail= true if (fail) cout ltlt ldquocongratulations You are passingnrdquo else cout ltltldquosorry You are failingnrdquo return fail

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 42: OOPS_Concept.ppt

int student PassingMarkrequired definition

void main()studentPassingMark=35student Xstudent Yint Xmarks[]=7555655689int Ymarks[]=15251009889XSetMarks(Xmarks)YSetMarks(Ymarks)XCheckPassing()YCheckPassing()

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 43: OOPS_Concept.ppt

Default Arguments

bull A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call

bull Syntax

return_type f(hellip type x = default_valuehellip)

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 44: OOPS_Concept.ppt

Default Arguments (Examples)

bull The default value of the 2nd argument is 2bull This means that if the programmer calls

pow(x) the compiler will replace that call with pow(x2) returning x2

double pow(double x int n=2) computes and returns xn

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 45: OOPS_Concept.ppt

Default Arguments (Rules)

bull Once an argument has a default value all the arguments after it must have default values

bull Once an argument is defaulted in a function call all the remaining arguments must be defaulted

int f(int x int y=0 int n) illegal

int f(int x int y=0 int n=1) legal

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 46: OOPS_Concept.ppt

Function overloading

bull Function redefined with different set of argumentsEX bull add(float float)bull Add(int int)bull Add (int int int)bull Function overloading is useful when similar function is

required to be called with either variable number of arguments or arguments of different type or both

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 47: OOPS_Concept.ppt

Function Overloading

bull Two or more functions can have the same name but different parameters

bull Example

int max(int a int b) if (agt= b)

return aelse

return b

float max(float a float b) if (agt= b)

return aelse

return b

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 48: OOPS_Concept.ppt

What is a Friend Function bull A friend function is used for accessing the non-public members of a class A class can allow non-member

functions and other classes to access its own private data by making them friends Thus a friend function is an ordinary function or a member of another class

How to define and use Friend Function in C++ bull The friend function is written as any other normal function except the function declaration of these

functions is preceded with the keyword friend The friend function must have the class to which it is declared as friend passed to it in argument

Some important pointsbull The keyword friend is placed only in the function declaration of the friend function and not in the

function definition

It is possible to declare a function as friend in any number of classes

bull When a class is declared as a friend the friend class has access to the private data of the class that made this a friend

bull It is possible to declare the friend function as either private or public

bull The function can be invoked without the use of an object

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 49: OOPS_Concept.ppt

Friend functionclass class1privateint numpublicvoid get()coutltltNumbercingtgtnumfriend void display(class1 cl)void display(class1 c1)coutltltC1NUMint main()class1 clsclsget()display(cls)

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 50: OOPS_Concept.ppt

static member friend function matrix multiplication includeltiostreamhgtincludeltconiohgt class matrixvectorstatic int a[3][3]static int b[3]static int c[3]publicvoid getmatrix(void)void getvector(void)friend int multiply(matrixvector mv) int matrixvectora[3][3]int matrixvectorb[3]int matrixvectorc[3] void matrixvectorgetmatrix(void)coutltltn enter the matrix value nfor(int i=0ilt3i++)

for(int j=0jlt3j++)cingtgta[i][j]

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 51: OOPS_Concept.ppt

void matrixvectorgetvector(void)coutltltn

coutltltn enter the vector for(int k=0 klt3k++)

cingtgtb[k]

int multiply(matrixvector mv)coutltltmatrix - vector multiplication ncoutltltn the vector n

for(int m=0mlt3m++)coutltltncoutltltmvb[m]

coutltltn the matrix n

for(int i=0ilt3i++)for (int j=0 jlt3 j++)coutltltmva[i][j]coutltltt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 52: OOPS_Concept.ppt

coutltltn

for(int e=0elt3e++)

for(int d=0dlt3d++)mvc[e]=mvc[e]+mva[e][d]mvb[d]

coutltltn the result is nfor(int n=0nlt3n++)coutltltmvc[n]coutltltnreturn 0 int main()clrscr()matrixvector mvmvgetvector()mvgetmatrix()multiply(mv)getch()return 0

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 53: OOPS_Concept.ppt

const member functionsbull A function which guarantees not to modify the

invoking object

bull If the body of the const function contains a statement that modifies the invoking object the program does not compile

bull One exception here is the mutable member A mutable data member can be modified by const function

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 54: OOPS_Concept.ppt

void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address rollno=4 error If rollno definition is changed to mutable int rollnoin the student class then there will not be an error

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 55: OOPS_Concept.ppt

Volatile functions

bull A member function invoked by a volatile object

bull A volatile object lsquos value can be changed by external parameters which are not under the control of the program

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 56: OOPS_Concept.ppt

volatile member functions Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object

class B int x public void f() volatile volatile member function

int main() volatile B b b is a volatile object bf() call a volatile member function safely The object b is declared volatile Calling a non-volatile member function from this

object is unsafe because bs state might have been changed by a different thread in the meantime

To ensure that f() can be called safely for a volatile object its declared volatile too

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 57: OOPS_Concept.ppt

Pointers and objects

int x = 10int p

p = ampx

p gets the address of x in memory

p

x10

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 58: OOPS_Concept.ppt

What is a pointer

int x = 10int p

p = ampx

p = 20

p is the value at the address p

p

x20

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 59: OOPS_Concept.ppt

What is a pointer

int x = 10int p = NULL

p = ampx

p = 20

Declares a pointer to an integer

amp is address operator gets address of x

dereference operator gets value at p

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 60: OOPS_Concept.ppt

Allocating memory using new

Point p = new Point(5 5)

bull new allocates space to hold the objectbull new calls the objectrsquos constructorbull new returns a pointer to that object

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 61: OOPS_Concept.ppt

Deallocating memory using delete

allocate memoryPoint p = new Point(5 5)

free the memorydelete p

For every call to new there must beexactly one call to delete

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 62: OOPS_Concept.ppt

Using new with arrays

int x = 10

int nums1 = new int[10] ok

int nums2 = new int[x] ok

bull Initializes an array of 10 integers on the heap

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 63: OOPS_Concept.ppt

bull A pointer can point to an object created by a classbull Object pointers are useful in creating objects at run time student s1 student ptr = amps1 s1 getdata() s1show() equivalent to ptr-gtgetdata() ptr-gt show() or (ptr)show()bull we can also create the objects using pointers and new operator student ptr = new studentbull This allocates enough memory for the data members in the object

structure and assigns the address of the memory space to ptrbull We can also create an array of objects using pointers student ptr = new student[5]

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 64: OOPS_Concept.ppt

constant objects const student s1(xy) object s1 is constantbull Any attempt to modify the values of x and y will generate compile

time errorbull A constant object can call only constant member functions void PrintDetails()const cout ltltrollno cout ltltname cout ltlt address

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 65: OOPS_Concept.ppt

nested classesbull It is an another way of inheriting properties of one class into

anotherbull From this we can understand that an object can be collection of

many other objects that is a class can contain objects of other classes as its members

class alpha(hellip) class beta(hellip) class gamma alpha a1 beta b1 All objects of gamma class will contain the objects a1 and b1 This

kind of relationship is called containership or nesting

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 66: OOPS_Concept.ppt

local classesbull Classes can be defined and used inside a function or a block Such classes are called local classes void test(int a) function hellip class student local class hellip class definitionhellip helliphellip student s1(a) create student objecthelliphellipLocal classes can use global variables and static variables declared inside the functionEnclosing function cannot access the private member of a local class

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 67: OOPS_Concept.ppt

Basic C++ Extension from C (II)bull const

ndash In Cdefine statements are handled by the preprocessor so there is no type checking

ndash In C++ the const specifier is interpreted by the compiler and type checking is applied

bull New data typendash Reference data type ldquoamprdquo Much likes pointer

int ix ix is real variable int amp rx = ix rx is alias for ix ix = 1 also rx == 1

rx = 2 also ix == 2

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 68: OOPS_Concept.ppt

C++ - Advance Extensionbull C++ allow function overloading

ndash In C++ functions can use the same names within the same scope if each can be distinguished by its name and signature

ndash The signature specifies the number type and order of the parameters

ndash The name plus signature then uniquely identifies a function

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message
Page 69: OOPS_Concept.ppt

Take Home Message

bull There are many different kinds of programming paradigms OOP is one among them

bull In OOP programmers see the execution of the program as a collection of dialoging objects

bull The main characteristics of OOPL include encapsulation inheritance and polymorphism Not only OOPL can do OOP but also others

  • CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
  • Unit I
  • Objects
  • Classes
  • classes
  • Problem printing student mark sheet
  • TV-01 Class and 3 Instances
  • Object-Oriented Concept
  • Encapsulation
  • Slide 10
  • Methods amp Messages
  • Slide 12
  • Slide 13
  • Characteristics of OOPL
  • O-O Principles and C++ Constructs
  • OOP Features
  • Slide 17
  • Information Hiding
  • Why Information Hiding
  • Inheritance
  • Inheritance (contrsquod)
  • Overloading
  • Why Overloading
  • Slide 24
  • Slide 25
  • ABSTRACTION AND ENCAPSULATION
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • CLASSES
  • A Graphical Representation of Classes
  • A Graphical Representation of Objects
  • Access specifiers
  • Function and data member
  • Slide 41
  • Slide 42
  • Slide 43
  • Default Arguments
  • Default Arguments (Examples)
  • Default Arguments (Rules)
  • Function overloading
  • Function Overloading
  • Slide 49
  • Friend function
  • Slide 51
  • Slide 52
  • Slide 53
  • const member functions
  • Slide 55
  • Volatile functions
  • Slide 57
  • Pointers and objects
  • What is a pointer
  • Slide 60
  • Allocating memory using new
  • Deallocating memory using delete
  • Using new with arrays
  • Slide 64
  • constant objects
  • nested classes
  • local classes
  • Basic C++ Extension from C (II)
  • C++ - Advance Extension
  • Take Home Message