Inline Functions - PowerPoint PPT Presentation

1 / 107
About This Presentation
Title:

Inline Functions

Description:

asks compiler to copy code into program instead of function call ... variables are frequently disallowed. Remember. In line restrictions are implementation ... – PowerPoint PPT presentation

Number of Views:72
Avg rating:3.0/5.0
Slides: 108
Provided by: Eyas
Category:

less

Transcript and Presenter's Notes

Title: Inline Functions


1
Inline Functions
  • inline functions
  • reduce function-call overhead
  • asks compiler to copy code into program instead
    of function call
  • compiler can ignore inline
  • use with small, often-used functions

2
Example inline double cube( const double s )
return s s s
3
Inline functions
- Any function body is written only once in the
memory. - This saves memory. - Several calls
jump to the same body of the function in
memory. - The jump has overhead with it.
4
Inline functions
- To avoid this overhead we use inline
functions. - It is written like a normal
function in the source file but compiles into
inline code instead of into a function.
5
include ltiostream.hgt inline float lbstokg(float
pounds) // (must precede calls
// to it)
return 0.453592 pounds void main()
float lbs cout ltlt
"\nEnter your weight in pounds " cin gtgt
lbs cout ltlt "Your weight in kilograms is " ltlt
lbstokg(lbs)
6
Main()
Main()
Func1()
Func1()
Func1()
Func1()
Inline
Without inline
7
- inline is good for functions that are one or
two lines ( very short) - Here, the compiler
must see the function definition (not just the
declaration) before it gets to the first
call. - inline is just a request.
8
Overloading functions
- Two or more functions with the same
name. - It uses the number of arguments and
their data types to distinguish one function
from another. - Reduce the number of function
names to be remembered.
9
Question
Modify the following program so that it
will print the word Welcome without change
anything in the main program? includeltiostream.hgt
void main()
10
include ltiostreamgt using namespace std class
University public University() cout ltlt "
Welcome"ltltendl University JUST void
main()
11
Question
Create a class with three int variables called a,
b, c. After that add the required function(s) to
rotate these values. Thus a will be stored in b,
b in c and c in a. After that test your program.
Note that the values should be inserted through a
constructor.
12
Before solution After
solutions a 1 a 5 b 3 b 1 c
5 c 3
13
includeltiostreamgt using namespace std class
Ahmed int a,b,c public Ahmed(int a1,int b1,
int c1) a a1b b1 c c1 void
rotate () int temp temp c c b
b a a temp void Print() cout ltlt
" a " ltlt a ltlt endl cout ltlt " b " ltlt b ltlt
endl cout ltlt " c " ltlt c ltlt endl void
main() Ahmed Myobject(1,3,5) Myobject.rotate(
) Myobject.Print()
14
includeltiostreamgt using namespace std class
Ahmed int a,b,c public Ahmed(int a1,int b1,
int c1) a a1b b1 c c1 void
rotate () int temp temp c c b
b a a temp
15
void Print() cout ltlt " a " ltlt a ltlt
endl cout ltlt " b " ltlt b ltlt endl cout ltlt "
c " ltlt c ltlt endl void main() Ahmed
Myobject(1,3,5) Myobject.rotate() Myobject.Pri
nt()
16
Can you modify the previous program so that it
includes pointers in any place
17
Static class members
If a data item in a class is defined as static,
then only one such item is created for the entire
class, no matter how many objects there are. A
static data item is useful when all objects of
the same class must share a common item of
information.
18
Parameterized Constructors

They allow you to give member variables program-de
fined initial values when an an object is
created. You do this by passing arguments to an
objects constructor function.
19

Last meeting we talked about struct and how we
can convert a struct to a class. In C, a struct
cannot have private, public protected. In C, a
struct can have private, public, and protected.
20
Unions and Classes

A union is essentially a class in which all
the members are stored in the same
location. A union defines a class type. Can
contain a constructors and destructors.
All members are public by default.
21
includeltiostream.hgt union test int i char
ch2 test(int a) void showchars() test
test(int a) i a void
testshowchars() cout ltltch0 ltlt endl cout
ltltch1 ltlt endl cout ltltch2 ltlt endl cout
ltltch3 ltlt endl

22
main() test myobject(120) myobject.showchars
() return 0

23
In the text , it talks about the inline
functions. We cover this but one new point.

24
The inline is a request, not a command, that
the compiler generate inline code, There are
various situations that might prevent
the compiler from complying with the request.
Here are some examples

25
Some compilers will not generate inline
code if a function contains a loop, a switch,
or a goto. Often, you cannot have inline
recursive functions. Inline functions that
contain static variables are frequently
disallowed.

26
Remember In line restrictions are
implementation- dependent. You need to check
the compiler user manual. Any function that is
defined inside a class definition is
automatically made into an inline function

27
Arrays of objects

Can we create an array of objects ? Yes
28
include ltiostream.hgt const int MAX 100
// maximum number of elements class
Distance // English Distance
class private int feet
float inches public void getdist()
// get length from user cout
ltlt "\n Enter feet " cin gtgt feet
cout ltlt " Enter inches " cin gtgt
inches void showdist() //
display distance cout ltlt feet ltlt "\'-" ltlt
inches ltlt '\"' void main()
Distance distMAX // array of
distances

29
Distance distMAX // array of
distances int n0 //
count the entries char ans
// user response ('y' or 'n') cout ltlt endl
do // get distances
from user cout ltlt "Enter
distance number " ltlt n1
distn.getdist() // store distance in
array cout ltlt "Enter another (y/n)?
" cin gtgt ans
// quit if user types 'n' while( ans
! 'n' ) for(int j0 jltn j) //
display all distances cout ltlt
"\nDistance number " ltlt j1 ltlt " is "
distj.showdist()

30
Pointers to Objects

You can access a structure directly, or through a
pointer to that structure. In like fashion, you
can access an object either directly or by using
a pointer. To access an element of an object
when using the actual object itself, use the dot
operator. To access a specific element of an
object when using a pointer to the object, you
must use the arrow operator.
31
include ltiostream.hgt class Distance
private int feet float inches
public void getdist() // get
length from user cout ltlt "\nEnter
feet " cin gtgt feet cout ltlt "Enter
inches " cin gtgt inches void
showdist() // display distance
cout ltlt feet ltlt "\'-" ltlt inches ltlt '\"'

32
void main() Distance dist
dist.getdist() dist.showdist() //
with dot operator Distance distptr //
pointer to Distance distptr new Distance
distptr-gtgetdist() // access object
members distptr-gtshowdist() // with
-gt operator

33
  • End of Chapter

34
A Closer Look at Classes

We will cover - Friend Functions - Overloading
constructor functions - Passing objects to
functions - Returning objects from functions -
Copy constructor
35
Friend Functions

- The concept of encapsulation and data
hiding dictate that nonmember functions
should not be able to access and objects
private protected data. - The policy is If you
are not a member, you cant get in. - This
restriction leads to considerable
inconvenience.
36
Friend Functions

- It is possible to allow a non-member function
access to the private member of a class by
declaring it as a friend of the class.
Example
37
include ltiostream.hgt class beta //
needed for f1 declaration class alpha
private int data public
alpha() data 3 // no-arg
constructor friend int f1(alpha,
beta) // friend function class beta
private int data public
beta() data 7 // no-arg
constructor friend int f1(alpha, beta)
// friend function

38
int f1(alpha a, beta b) return( a.data
b.data ) void main() alpha aa
beta bb cout ltlt f1(aa, bb)


39
Notes - we want f1 have access to both of
the private data members, so we make it as
friend. - It is declared with the friend
keyword in both classes. - The declaration
friend int f1(alpha,beta) can be either public
or private.

40
Notes - In our example, the function will
take the two objects of the two classes as
arguments, and operate on their private data.
The friend function thus works as a bridge
between two classes.

41
Remember - In the previous program we wrote
class beta at the beginning. You must
remember that a class cant be referred to
until it has been declared. Class beta is
referred to in the declaration of the
function f1() in class alpha, so beta must be
declared before alpha. This is why we placed
at the beginning class beta

42
Advantage of a friend functions It adds
flexibility to the language.

43
Disadvantages of friend functions It does not
keep the philosophy that only member functions
can access a classs private data.

44
Question How serious is the breach of
data integrity when friend functions are used ?

45
Answer A friend function must be
declared within the class whose data it
will access. Thus, a programmer who does not
have access to the source code for the class
cannot make a function into a friend .

46
Friend functions are conceptually messy, and
potentially lead to a spaghetti-code situation
if numerous friends muddy the clear boundaries
between classes. For this reason friend
functions should be used sparingly. If you find
yourself using many friends, you may need to
rethink the design of your program.

47
Quiz 1)- What is the
purpose of the constructor ? 2)- Is it
possible for the constructor to have a type
? 3)- How you can distinguish between
default constructor, user-defined constructor
and copy constructor
48
Overloading Constructor Functions

To overload a classs constructor, declare the
various forms it will take and define each
action relative to these forms A previous example
49
include ltiostream.hgt class Distance
// English Distance class private
int feet float inches public
Distance() // constructor (no
args) Distance(int ft, float in) //
constructor (two args) feet ft inches
in void getdist() // get
length from user cout ltlt "\nEnter feet
" cin gtgt feet cout ltlt "Enter inches " cin
gtgt inches

50
Dynamic Initialization to Constructors

- Local and global variables can be
initialized at run time. This is called dynamic
initialization. - You can initialize a variable
using other variables and/or function calls.
51
includeltiostream.hgt includeltstdlib.hgt includeltt
ime.hgt class timer int seconds public
timer(char t) seconds atoi(t)
timer(int t) seconds t void run()

52
void timerrun() clock_t t1,t2 t1 t2
clock()/CLOCKS_PER_SEC while(seconds) if
(( t1 / CLOCKS_PER_SEC1 ) lt (t2clock()) /
CLOCKS_PER_SEC) seconds-- t1
t2

53
main() timer a(3)char str80 a.run() cout
ltlt"Enter number of seconds" cingtgtstr timer
b(str) b.run()

54
  • Clock() returns the number of systems clock
    ticks since the program began running. Diving
    this value by CLOCKS_PER_SEC converts the return
    value of clock() into seconds

55
A potential Problem when passing objects

Run the following program and see what kind of
error message it will give.
56
include ltiostream.hgt include ltstdlib.hgt class
myclass int p public myclass ( int I )
myclass ( ) int getval ( ) return p


57
myclassmyclass ( int I ) cout ltlt "
Allocating memory \n" p new int if (
!p) cout ltlt "Allocation failure" exit ( 1
) p I myclassmyclass( ) cout
ltlt " Freeing p\n" delete p

58
void display ( myclass ob ) cout ltlt ob.getval(
) ltlt endl void main ( ) myclass
a(10) display ( a )

59
The computer generates an error message which
depends on the compiler. It might give the
following error message Allocating
memory 10 Freeing P Freeing P Null pointer
assignment

60
This program has two problems 1)-When a is
constructed within main(), memory is allocated
and assigned to a.p. When a is passed to
display(), a is copied into the parameter ob.
This means that both a and ob will have the same
value for p. This is, both objects will have
their copies of p pointing to the same
dynamically allocated memory. When display()
terminates, ob is destroyed, and its destructor
is called. This causes ob.p to be freed.
However, the memory freed by ob.p is the same
that is still in use by a.p

61

The second problem is when the program
terminates. At this time the destructor is
called one more time. Thus, it is freeing the
memory
62

The solution to this problem is to pass the
object by pointer or by reference. Thus, not
copy is made. Thus, no destructor is called when
the functions returns.
63
include ltiostream.hgt include ltstdlib.hgt class
myclass int p public myclass ( int I )
myclass ( ) int getval ( ) return p


64
myclassmyclass ( int I ) cout ltlt "
Allocating memory \n" p new int if (
!p) cout ltlt "Allocation failure" exit ( 1
) p I myclassmyclass( ) cout
ltlt " Freeing p\n" delete p

65
void display ( myclass myobject ) cout ltlt
myobject.getval( ) ltlt endl void main (
) myclass a(10) display ( a )

66
Write a program with the corresponding
functions that returns object(s).

67
include ltiostream.hgt include ltstring.hgt Class
Irbid char s80 public void show ( )
cout ltlt s ltlt "\n" void set( char str )
strcpy ( s, str ) Irbid input (
) char inputstr80 Irbid str cout ltlt "
Enter a string " cingtgt inputstr str.set(inputs
tr) return str

68
void main ( ) Irbid myobject myobject
input( ) myobject.show ( )

69
A potential problem when returning objects

When an object is returned by a function,
a temporary object is automatically created,
which holds the return value. It is this object
that is actually returned by the function.
After the value has been returned, this object
is destroyed. The destruction of this temporary
object may cause unexpected side effects in some
situations.
70
For example, if the object returned by
the function has a destructor that
frees dynamically allocated memory, that memory
will be freed even though the object that is
assigned the return value is still using it.

71
Solution Return either a pointer or a
reference. However this is not always feasible.
Another way to solve this problem involves the
use of a copy constructor and, in some cases,
and overloaded assignment operator

72
An example is written in book C from the
ground Up

73
Revisiting Copy Constructor
- Problems occur when an object is passed or
returned from a function - The copy constructor
avoid these problems. - When an object is
passed to a a function, an exact copy of that
object is made and given to the function
parameter that receives the object.

74
- There are cases when this identical copy is
not desirable.

75
As an example if the object contains a pointer
to allocated memory, then the copy will point to
the same memory as does the original object.
Therefore, if the same copy makes a change to the
contents of this memory, it will be changed for
the original object. In other words, when the
function terminates, the copy will be destroyed.

76
A similar situation occurs when an object is
returned by a function. Usually, the compiler
will generate a temporary object that holds a
copy of the value returned by the function. This
is done automatically and is beyond your
control. This temporary object goes out of
scope once the value is returned to calling
routine,causing the temporary objects destructor
to be called.

77
Solution To prevent this, you need to define
precisely what occurs when a copy of an object
is made so that you can avoid undesired side
effects. The way you accomplish this is by
creating a copy constructor. By defining a copy
constructor, you fully specify exactly what
occurs when a copy of an object is made.

78
Assignment

One object is given to another by
Initialization
79
When an object is used to initialize another in
a declaration statement

When an object is passed as a parameter to a
function
Initialization
When a temporary object is created for use as a
return value by a function
80
- The copy constructor is applied to
initialization, not to an assignment - When an
initialization occurs, the compiler will provide
a default copy constructor that duplicates the
object.
81
However, it is possible to define a
copy constructor that specifies precisely how one
object will initialize another. Once defined,
the copy constructor is called whenever an object
is used to initialize Remember copy
constructor do not affect assignment operation.
82
General Form of copy constructor
Classname (const classname obj) body of the
constructor Note obj is a reference to an
object that is being used to initialize another
object
83
Example 1 Consider a1, a2, and a3 as object a1
a2 invokes the assignment
operator myclasse a3(a1) invokes the copy
constructor myclass a3 a1 invokes the copy
constructor
84
Example 2 Consider a1, a2, and a3 as
object function1(a1) a2 function2() //a2
receives a returned
object
85
As we see in function1(a1), an object is passed
to a function as an argument, a copy constructor
is called to make the copy . Consider the
following example
86
include ltiostream.hgt include ltstdlib.hgt class
myclass int p public myclass ( const
myclass ob ) myclass (int i) myclass ( )
int getval ( ) return p
87
myclassmyclass (const myclass ob ) p new
int if ( !p) cout ltlt "\nAllocation
failure" exit ( 1 ) p ob.p cout
ltlt"\nCopy Constructor called" myclassmyclass
(int i ) cout ltlt "\nAllocating an object" p
new int if ( !p) cout ltlt "Allocation
failure" exit ( 1 ) p i
88
myclassmyclass (int i ) cout ltlt
"\nAllocating an object" p new int if (
!p) cout ltlt "Allocation failure" exit ( 1
) p i myclassmyclass( ) cout ltlt
" Freeing p\n" delete p
89
void display (myclass b ) cout ltlt "\n"ltlt
b.getval( ) ltlt endl void main ( ) myclass
a(10) display ( a )
90
As you can see, the normal constructor is called
for object a. However, when a is used to
initialize b, the copy constructor is invoked.
The use of the copy constructor ensures that b
will allocate its own memory. Without the copy
constructor, b would simply be an exact copy of
a, and a.p would point to the same memory as
b.p.
91
Remember The copy constructor is called for
only initializations. For example, the
following sequence does not call the copy
constructor defined in the preceding
program. Myclass a(2),b(3) b a b a
performs the assignment operation, not a copy
operation.
92
Using a copy constructor when an object is
returned
The copy constructor is called when a temporary
object is created as the result of a function
returning an object. As an example
93
includeltiostream.hgt class myclass public
myclass() cout ltlt "\nNormal constructor"
myclass(const myclass obj ) cout ltlt"\n
Copy constructor" myclass function1() mycl
ass myobject return myobject
94
main() myclass a a function1() return
0
95
This pointer
Each time a member function is invoked, it
is automatically passed a pointer, call this,
to the object that has invoked it. The this
pointer is an implicit parameter to all member
functions. Therefore, inside a member
function, this may be used to refer to the
invoking object.
96
Previous Exam Question
Under what circumstance would you need to define
a default constructor, a copy constructor, an
overloaded assignment operator, and a destructor
for a class? If a class contains a
dynamically allocated data member.
97
Previous Exam Question
What does the copy constructor prevent in this
case? The copy constructor prevents
aliasing, that is two pointers pointing to the
same area of memory which would occur if default
memberwise copy were used in passing an object of
the class by value or returning an object of the
class from a function
98
Previous Exam Question
Why do you need the destructor ?? The destructor
prevents memory leak, that is, chunks of memory
that should be available for reuse but are not
because they were not properly deallocated.
Without a destructor such leaks would occur
when an object of the class is explicitly deleted
or leaves scope.
99
  • Copy Constructor
  • A copy constructor is automatically provided
  • for each class.
  • The default copy constructor is adequate
  • for many classes.
  • It is not adequate for classes which
  • directly manage memory to create space
  • for data members.
  • Copy constructors always pass a reference
  • to an existing object. Why?
  • To avoid an infinite recursion.

100
Copy Constructor
initialize an object based on another object.
There is a difference in C between
initialization and the assignment. The
initialization constructs a new object and
gives it a value at the same time. Assignment
changes the value of an object that has already
been constructed. This kind of
initialization could actually be implemented
as a call to the default constructor allowed
by a call to the assignment operator.
101
Copy Constructor It is a bit
like the default constructor and a bit like the
assignment operator. For example, it is named
like the default constructor and takes a
parameter like the assignment operator. The
copy constructor is called when an object is
constructed based on another object of the
same class.
102
Copy Constructor The copy
constructor is implemented using the member
functions that implement the default
constructor and the assignment
operator. Class members that are instances of
classes are automatically default constructed
before the body of the constructor executes.
103
Example of Copy Constructor
104
include ltiostream.hgt class alpha private
int data public alpha()
// no-arg constructor
alpha(int d) data d //
one-arg constructor alpha(alpha a)
// copy constructor data a.data
cout ltlt "\nCopy constructor invoked"
void display() cout ltlt data // display
void operator (alpha a) // overloaded
operator data a.data cout ltlt
"\nAssignment operator invoked"
105
void main() alpha a1(37) alpha a2
a2 a1 // invoke
overloaded cout ltlt "\na2" a2.display()
// display a2 alpha a3(a1) //
invoke copy constructor // alpha a3 a1
// equivalent definition of a3 cout ltlt
"\na3" a3.display() // display a3
106
In general copy constructor may be invoked
when 1- A new object is defined. Ex. alpha
a3(a1) 2- When arguments are passed by
value to functions 3- When values are returned
from functions.
107
  • End of Chapter
Write a Comment
User Comments (0)
About PowerShow.com