OOPS_Concept.ppt
description
Transcript of 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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-