Std c notes 03, Study notes of Advanced Computer Programming

this is c programing notes

Typology: Study notes

2014/2015

Uploaded on 06/11/2015

lovebhogi
lovebhogi 🇳🇵

1 document

1 / 77

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Department of Cybernetics The University of Reading
SE2B2
Further Computer Systems
Course notes
Standard C++ programming
by
Dr Virginie F. Ruiz
November, 03
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d

Partial preview of the text

Download Std c notes 03 and more Study notes Advanced Computer Programming in PDF only on Docsity!

Department of Cybernetics

The University of Reading

SE2B

Further Computer Systems^ Course notes

Standard C++ programming

by

Dr Virginie F. Ruiz

November, 03

VFR November, 03^

SE2B2 Further Computer Systems

C^ REATING AND USING A COPY CONSTRUCTOR

........................................................................................ 27

STRUCTURE OF THE COURSE .........................................................................................................

USING DEFAULT ARGUMENTS

.................................................................................................................. 29

GENERALITY^ ...............................................................................................................................................

OVERLOADING AND AMBIGUITY

.............................................................................................................. 30

S^ IMPLE OBJECTS^ ..........................................................................................................................................

F^ INDING THE ADDRESS OF AN OVERLOADED FUNCTION

.......................................................................... 30

DERIVED^ C^ LASSES^ ......................................................................................................................................3 TEMPLATES^ .................................................................................................................................................

OPERATOR OVERLOADING........................................................................................................... 31

S^ TREAMS^ .....................................................................................................................................................

THE BASICS OF OPERATOR OVERLOADING

............................................................................................... 31 OVERLOADING BINARY OPERATORS

........................................................................................................ 32

C++ BOOKS .............................................................................................................................................

OVERLOADING THE RELATIONAL AND LOGICAL OPERATORS

................................................................. 34

F^ OR^ WINDOWS^ :........................................................................................

Error! Bookmark not defined.

OVERLOADING A UNARY OPERATOR

....................................................................................................... 34 USING FRIEND OPERATOR FUNCTIONS

..................................................................................................... 35

GENERALITY .........................................................................................................................................

A^ CLOSER LOOK AT THE ASSIGNMENT OPERATOR

................................................................................... 37

AN OVERVIEW OF^ C++................................................................................................................................

OVERLOADING THE^ [ ]^ SUBSCRIPT OPERATOR

......................................................................................... 38

OBJECT^ ORIENTED^ P^ ROGRAMMING

(OOP) ................................................................................................ DIFFERENCES BETWEEN^ C

AND^ C++ ..........................................................................................................

INHERITANCE..................................................................................................................................... 39

DIFFERENCES BETWEEN^ C++

AND^ S^ TANDARD^ C++ ..................................................................................

B^ ASE CLASS ACCESS CONTROL

................................................................................................................ 39 USING PROTECTED MEMBERS

.................................................................................................................. 40

C++ CONSOLE I/O .................................................................................................................................

C^ ONSTRUCTORS^ ,^ DESTRUCTORS

,^ AND INHERITANCE^ .............................................................................. 41

C AND C++ COMMENTS......................................................................................................................

MULTIPLE INHERITANCE .......................................................................................................................... 43 VIRTUAL BASE CLASSES^ ........................................................................................................................... 45

CLASSES ..................................................................................................................................................

VIRTUAL FUNCTIONS ...................................................................................................................... 46

FUNCTION OVERLOADING: AN INTRODUCTION .....................................................................

P^ OINTERS TO DERIVED CLASS

.................................................................................................................. 46 INTRODUCTION TO VIRTUAL FUNCTIONS

................................................................................................. 47

CONSTRUCTORS AND DESTRUCTORS FUNCTIONS ...............................................................

MORE ABOUT VIRTUAL FUNCTIONS

......................................................................................................... 49

C^ ONSTRUCTORS^ ........................................................................................................................................

APPLYING POLYMORPHISM

...................................................................................................................... 51

DESTRUCTORS^ ..........................................................................................................................................10 C^ ONSTRUCTORS THAT TAKE PARAMETERS

..............................................................................................

C++ I/O SYSTEM.................................................................................................................................. 53 S^ OME^ C++ I/O^ BASICS^ ............................................................................................................................. 53

INHERITANCE: AN INTRODUCTION ............................................................................................

C^ REATING YOUR OWN INSERTERS

........................................................................................................... 54

OBJECT POINTERS ............................................................................................................................

C^ REATING EXTRACTORS^

.......................................................................................................................... 55 MORE^ C++ I/O B^ ASICS^ ............................................................................................................................ 56

IN-LINE FUNCTIONS..........................................................................................................................

F^ ORMATTED^ I/O....................................................................................................................................... 57

AUTOMATIC IN^ - LINING^ .............................................................................................................................

USING WIDTH^ ( ),^ PRECISION

( ),^ AND FILL^ ( )............................................................................................. 58 USING^ I/O^ MANIPULATORS

...................................................................................................................... 59

MORE ABOUT CLASSES ...................................................................................................................14 ASSIGNING OBJECT^ ...................................................................................................................................

ADVANCE C++ I/O .............................................................................................................................. 60

P^ ASSING OBJECT TO FUNCTIONS

...............................................................................................................

C^ REATING YOUR OWN MANIPULATORS

................................................................................................... 60

R^ ETURNING OBJECT FROM FUNCTIONS

.....................................................................................................

F^ ILE^ I/O^ BASICS........................................................................................................................................ 60

F^ RIEND FUNCTIONS:^ AN INTRODUCTION

..................................................................................................

UNFORMATTED^ ,^ BINARY I/O ................................................................................................................... 63 MORE UNFORMATTED^ I/O

FUNCTIONS^ .................................................................................................... 64

ARRAYS, POINTERS, AND REFERENCES ....................................................................................

R^ ANDOM ACCESS^ ..................................................................................................................................... 65

ARRAYS OF OBJECTS^ .................................................................................................................................

C^ HECKING THE^ I/O^ STATUS

..................................................................................................................... 66

USING POINTERS TO OBJECTS

...................................................................................................................

C^ USTOMISED^ I/O^ AND FILES

.................................................................................................................... 67

THE^ THIS^ POINTER^ ...................................................................................................................................20 USING^ NEW^ AND^ DELETE......................................................................................................................

TEMPLATES AND EXCEPTION HANDLING............................................................................... 68

MORE ABOUT NEW AND DELETE

...............................................................................................................

GENERIC FUNCTIONS^ ................................................................................................................................ 68

R^ EFERENCES^ .............................................................................................................................................

GENERIC CLASSES^ .................................................................................................................................... 70

P^ ASSING REFERENCES TO OBJECTS

...........................................................................................................

EXCEPTION HANDLING^ ............................................................................................................................. 72

R^ ETURNING REFERENCES

.........................................................................................................................

MORE ABOUT EXCEPTION HANDLING

...................................................................................................... 74 HANDLING EXCEPTIONS THROWN BY NEW

.............................................................................................. 76

INDEPENDENT REFERENCES AND RESTRICTIONS

...................................................................................... FUNCTION OVERLOADING.............................................................................................................25 OVERLOADING CONSTRUCTOR FUNCTIONS

.............................................................................................. Standard C++ programming

VFR November, 03^

SE2B2 Further Computer Systems

GENERALITY An overview of C++ C++ is the object oriented extension of C. As for C there is an ANSI/ISOstandard ( final draft 1998) for the C++ programming language. This will ensurethat the C++ code is portable between computers. The C++ programming language teach here is the Standard C++. This is theversion^ of^ C++^ created

by^ the^ ANSI/ISO

2 standardisation^ committee.

The

Standard C++ contains several enhancements not found in the traditional C++.Thus, Standard C++ is a superset of traditional C++. Standard C++ is the one that is currently accepted by all major compilers.Therefore, you can be confident that what you learn here will also apply in thefuture. However, if you are using an older compiler it might not support one or more ofthe features that are specific to Standard C++. This is important because tworecent additions to the C++ language affect every program you will write. If youare using an older compiler that does not accept these knew features, don’t worry.There is an easy workaround, as you will in a later paragraph. Since C++ was invented to support object-oriented programming. OOP conceptswill be reminded. As you will see, many features of C++ are related to OOP in away or another. In fact the theory of OOP permeates C++. However, it isimportant to understand that C++ can be used to write programs that are and arenot object oriented. How you use C++ is completely up to you. A few comments about the nature and form of C++ are in order. For most partC++ programs look like C programs. Like a C program, a C++ program beginsexecution at^ m a i n ( ).

To include command-line arguments, C++ uses the same

a r g c ,^ a r g v^ convention that C uses. Although C++ defines its own, object-oriented library. It also supports all the functions in the C standard library. C++uses the same control structures as C. C++ includes all the build-in data typesdefined by C programming.

Object Oriented Programming (OOP) Although structured programming has yielded excellent results when applied tomoderately complex programs, even it fails at some point, after a program reachesa certain size. To allow more complex programs to be written, object-orientedprogramming has been invented. OOP takes the best of the ideas in structuredprogramming and combines them with powerful new concepts that allow you toorganise your programme more efficiently. Object oriented programming encourage you to decompose a problem into itsconstituent parts. Each^ component^

becomes^ a^ self-contained

object^ that^ contains

its^ own

instructions and data that relate to that object. In this way, complexity is reducedand the programmer can manage larger program. All OOP languages, including C++, share three common defining traits. Encapsulation Encapsulation^ is^ the

mechanism^ that^

binds^ together^ code

and^ the^ data^ it

manipulates, and keeps them both safe from outside. In an object-orientedlanguage, code and data can be combined in such a way that a self-contained‘black box’ is created. When code and data are link together in this fashion , an object^ is created:

2 ANSI: American National Standards InstituteISO: International Standard Organisation

Within an object, code, data, or both may be

private^ to that object or

public.

Private code or data is known to and accessible only by another part of the object(i.e. cannot be accessed by a piece of the program that exists outside the object. Public code or data can be accessed by other parts of the program even though itis defined within an object. Public parts of an object are used to provide a controlled interface to the privateelements of the object.

OBJECT^ Data Methods: code

Standard C++ programming

VFR November, 03^

SE2B2 Further Computer Systems

An object is a variable of a user-defined type. Each time you define a new type ofobject, you are creating a new data type. Each specific instance of this data type isa compound variable. Polymorphism Polymorphism is the quality that allows one name to be used for two or morerelated but technically different purposes. Polymorphism allows one name to specify a general class of actions. Within ageneral class of actions, the specific action to be applied is determined by the typeof data. For example, in C, the absolute value action requires three distinctfunction names:^ a b s ( )

for integer,^ la bs( )

for long integer, and

f a b s ( )^ for

floating-point value. However in C++, each function can be called by the samename, such as^ a b s (

).^ The type of data used to call the function determines

which specific version of the function is actually executed. In C++ it is possible to use one function name for many different purposes. Thistype of polymorphism is called

function overloading

Polymorphism can also be applied to operators. In that case it is called

operator

overloading. More generally the concept of polymorphism is characterised by the idea ‘oneinterface, multiple methods’. The key point to remember about polymorphism isthat it allows you to handle greater complexity by allowing the creation ofstandard interfaces to related activities. Inheritance Inheritance is the process by which one object can acquire the properties ofanother. An object can inherit a general set of properties to which it can add thosefeatures that are specific only to itself. Inheritance is important because it allows an object to support the concept of hierarchical classification.

Most information is made manageable by hierarchical

classification. The child class inherits all those qualities associated with the parent and adds tothem its own defining characteristics. Differences between C and C++ Although C++ is a subset of C, there are some small differences between the two,and few are worth knowing from the start. First, in C, when a function takes no parameters, its prototype has the word

v o id

inside its function parameter list. For example if a function

f 1 (^ )^ takes no

parameters (and returns a

c h a r ), its prototype will look like this: char f1( void );^ /*^ C version^

In C++, the^ void^ is optional. Therefore the prototype for

f1( )^ is usually

written as:^ char^ f1( );

// C++ version

this means that the function

has no parameters

. The use of^ v o id^

in C++ is not

illegal; it is just redundant. Remember these two declarations are equivalent. Another difference between C and C++ is that in a C++ program,

all functions

must be prototyped. Remember in C prototypes are recommended but technicallyoptional. As an example from the previous section show, a member function’sprototype contained in a class also serves as its general prototype, and no otherseparate prototype is required. A third difference between C and C++ is that in C++, if a function is declared asreturning a value, it must return a value. That is, if a function has a return typeother than^ v o id^ , any

r e t u r n^ statement within the function must contain a value.

In C, a non^ v o id^ function is not required to actually return a value. If it doesn’t, agarbage value is ‘returned’. In C++, you^ must explicitly declare the return type

of all functions.

Another difference is that in C, local variables can be declared only at the start ofa block, prior to any ‘action’ statement. In C++, local variables can be declaredanywhere. Thus, local variables can be declared close to where they are first useto prevent unwanted side effects. C++ defines the^ b o o l

date type, which is used to store Boolean values. C++ also

defines the keywords

t r u e^ and^ f a l s e ,^ which are the only values that a value of

type^ b o o l^ can have. In C, a character constant is automatically elevated to an integer, whereas in C++it is not. In C, it is not an error to declare a global variable several times, even though it isbad programming practice. In C++, this is an error. In C an identifier will have at least 31 significant characters. In C++, allcharacters are considered significant. However, from practical point of view,extremely long identifiers are unwieldy and seldom needed. In C, you can call^ m a i n ( )

from within the program. In C++, this is not allowed.

Standard C++ programming

VFR November, 03^

SE2B2 Further Computer Systems

using namespace std

; C++ CONSOLE^ I/O

Since C++ is a superset of C, all elements of the C language are also contained inthe C++ language. Therefore, it is possible to write C++ programs that look justlike C programs. There is nothing wrong with this, but to take maximum benefitfrom C++, you must write C++-style programs. This means using a coding style and features that are unique to C++. The most common C++-specific feature used is its approach to console I/O.While you still can use functions such as

p r i n t f ( )^ and^ s c a n f ( ) ,

C++ I/O is

performed using^ I/O operators

instead of I/O functions.

The output operator is

<<. To output to the console, use this form of the

<< operator:^ cout^ <<^ expression; where expression can be any valid C++ expression, including another outputexpression.^ cout^ <<^ "This string is output to the screen.\n"

cout <<^ 236.99; The input operator is^ >>. To input values from keyboard, use cin^ >>^ variables; Example: #include^ <^ iostream

using namespace

std; int^ main ( ) {^ //^ local variables^ int^ i;^ float^ f;^ //^ program code^ cout^ <<^ "Enter an integer then a float ";^ //

no automatic newline cin >> i >> f;^ //^ input an integer and a float

cout^ <<^ "i= " << i

<<^ " f= "^ <<^ f

<<^ "\n"; //^ output i then f and newline return 0; }

You can input any items as you like in one input statement. As in C, individualdata items must be separated by whitespace characters (spaces, tabs, or newlines). When a string is read, input will stop when the first whitespace character isencountered.

C^ AND^ C++ C

OMMENTS /*^ This is a C-like comment.^ The program determines whether^ an integer is odd or even. */ #include^ <^ iostream

using namespace

std; int^ main ( ) {^ int^ num;^ //

This is a C++ single-line comment. // read the number cout << "Enter number to be tested: "; cin >> num; // see if even or odd if ((num%2)==0)^ cout <<^ "Number is even\n"; else cout << "Number is odd\n"; return 0;

} Multiline comments cannot be nested but a single-line comment can be nestedwithin a multiline comment. /* This is a multiline comment^ Inside which

//^ is nested a single-line comment

Here is the end of the multiline comment. */

Standard C++ programming

VFR November, 03^

SE2B2 Further Computer Systems

CLASSES

In C++, a class is declared using the

class^ keyword. The syntax of a class

declaration is similar to that of a structure. Its general form is,^ class^ class-name

{ // private functions and variables public: // public functions and variables

}^ object-list ; In a class declaration the^ object-list

is optional.

The^ class-name^ is technically optional. From a practical point of view it isvirtually always needed. The reason is that the

class-name^ becomes a new type

name that is used to declare objects of the class. Functions and variables declared inside the class declaration are said to be members^ of the class. By default, all member functions and variables are

private^ to that class. This

means that they are accessible by other members of that class. To declare^ public^ class members, the

public^ keyword is used, followed by a

colon.^ All^ functions

and^ variables^ declared

after^ the^ public

specifier are

accessible both by other members of the class and by any part of the program thatcontains the class.^ #include^ <

iostream^ > using namespace^ std; // class declaration class myclass^ { // private members to myclass int a; public: // public members to myclass void set_a( int^ num); int get_a( ); };

This class has one private variable, called

a^ , and two public functions

s e t _ a ( )

and^ g e t _ a ( ).^ Notice that the functions are declared within a class using theirprototype forms. The functions that are declared to be part of a class are called member functions.

Since^ a^ is private it is not accessible by any code outside

m y c l a s s.^ However

since^ s e t _ a ( )^ and

g e t _ a ( )^ are member of

m y c l a s s ,^ they have access to

a

and as they are declared as public member of

m y c l a s s ,^ they can be called by

any part of the program that contains

m y c l a s s.

The member functions need to be defined. You do this by preceding the functionname with the class name followed by two colons (::

are called scope resolution

operator ). For example, after the class declaration, you can declare the memberfunction as^ //^ member functions declaration^ void^ myclass::set_a(

int^ num) {

a=num; } int myclass::get_a( ) { return^ a; } In general to declare a member function, you use this form: return-type^ class-name

:: func-name ( parameter- list

{^ //^ body of function } Here the^ class-name^ is the name of the class to which the function belongs. The declaration of a class does not define any objects of the type

m y c l a s s.^ It

only defines the type of object that will be created when one is actually declared.To create an object, use the class name as type specifier. For example,^ //^ from previous examples^ void main ( ) {^ myclass ob1, ob2;//

these are object of type myclass

// ...^ program code } Remember that an object declaration creates a physical entity of that type. That is,an object occupies memory space, but a type definition does not. Once an object of a class has been created, your program can reference its publicmembers by using the dot operator in much the same way that structure membersare accessed. Assuming the preceding object declaration, here some examples, ...

Standard C++ programming

8

VFR November, 03^

SE2B2 Further Computer Systems

//^ abs( ) for double double^ abs ( double

n) { cout << "In double abs( )\n"; return n<0? -n : n;

} The compiler automatically calls the correct version of the function based uponthe type of data used as an argument. Overloaded functions can also differ in the number of arguments. But, you mustremember^ that^ the^ return

type^ alone^ is^ not

sufficient^ to^ allow

function

overloading. If two functions differ only in the type of data they return, thecompiler will not always be able to select the proper one to call. For example, thefollowing fragment is incorrect,^ //^ This is incorrect and will not compile^ int^ f1 ( int

a); double f1 ( int^ a); ... f1(10); // which function does the compiler call??? CONSTRUCTORS AND^ DESTRUCTORS

FUNCTIONS Constructors When applied to real problems, virtually every object you create will requiresome sort of initialisation. C++ allows a

constructor function

to be included in a

class declaration. A class’s constructor is called each time an object of that classis created. Thus, any initialisation to be performed on an object can be doneautomatically by the constructor function. A constructor function has the same name as the class of which it is a part a partand has not return type. Here is a short example,^ #include^ <

iostream^ > using namespace^ std; // class declaration class myclass^ { int a; public:

myclass(^ );^ //

constructor void^ show( ); }; myclass::myclass( ) { cout <<^ "In constructor\n"; a=10; } myclass::show( ) { cout^ << a; } int main ( ) { int^ ob; //^ automatic call to constructor ob.show( ); return^ 0; } In this simple example the constructor is called when the object is created, and theconstructor initialises the private variable a to 10. For a global object, its constructor is called once, when the program first beginsexecution. For local objects, the constructor is called each time the declaration statement isexecuted. Destructors The complement of a constructor is the

destructor. This function is called when

an object is destroyed. For example, an object that allocates memory when it iscreated will want to free that memory when it is destroyed. The name of a destructor is the name of its class preceded by a

∼. For example,

#include^ <^ iostream

using namespace

std; //^ class declaration class^ myclass^ {^ int^ a;^ public:^ myclass(^ );

// constructor ∼myclass( );^ // destructor void show( ); }; myclass::myclass( ) {^ cout <<^ "In constructor\n";

Standard C++ programming

VFR November, 03^

SE2B2 Further Computer Systems

a=10; } myclass::∼myclass( ) { cout <<^ "Destructing...\n"; } // ... A class’s destructor is called when an object is destroyed. Local objects are destroyed when they go out of scope. Global objects aredestroyed when the program ends. It is not possible to take the address of either a constructor or a destructor. Note that having a constructor or a destructor perform actions not directly relatedto initialisation^ or^ orderly^

destruction^ of^ an^

object^ makes^ for^

very^ poor

programming style and should be avoided. Constructors that take parameters It is possible to pass one or more arguments to a constructor function. Simply addthe^ appropriate^ parameters

to^ the^ constructor

function’s^ declaration

and

definition. Then, when you declare an object, specify the arguments.^ #include^ <

iostream^ > using namespace^ std; // class declaration class myclass^ { int a; public: myclass( int^ x); // constructor void show( ); }; myclass::myclass( int^ x) { cout << "In constructor\n"; a=x; } void myclass::show( ) { cout << a <<"\n"; } int main ( ) { myclass ob(4); ob.show( );

return^ 0; } Pay particular attention to how

o b^ is declared in^ main

( ). The value 4, specified

in the parentheses following

o b ,^ is the argument that is passed to

myclass ( )’s

parameter^ x^ that is used to initialise

a. Actually, the syntax is shorthand for this

longer form:^ myclass ob = myclass(4); Unlike constructor functions

, destructors cannot have parameters.

Although the previous example has used a constant value, you can pass anobject’s constructor any valid expression, including variables.^ I^ NHERITANCE

:^ AN INTRODUCTION

Although inheritance will discuss more fully later. It is needs to be introduce atthis time. Inheritance is the mechanism by which one class can inherit theproperties of another. It allows a hierarchy of classes to be build, moving from themost general to the most specific. When one class is inherited by another, the class that is inherited is called the base class. The inheriting class is called the

derived class.

In general, the process of inheritance begins with the definition of a base class.The base class defines all qualities that will be common to any derived class. Inessence, the base class represent the most general description of a set of traits.The derived class inherits those general traits and adds properties that are specificto that class. Let’s see a simple example that illustrates many key-features of inheritance. To start, here the declaration for the base class:^ //^ Define base class^ class^ B {^ int^

i; public: void set_i( int^ n); int get_i( ); };

Standard C++ programming

VFR November, 03^

SE2B2 Further Computer Systems

OBJECT POINTERS

So far, you have been accessing members of an object by using the dot operator.This is the correct method when you are working with an object. However, it isalso possible to access a member of an object via a pointer to that object. When apointer is used, the arrow operator (

-> ) rather than the dot operator is employed.

You declare an object pointer just as you declare a pointer to any other type ofvariable. Specify its class name, and then precede the variable name with anasterisk. To obtain the address of an object, precede the object with the

&^ operator, just as

you do when taking the address of any other type of variable. Just as pointers to other types, an object pointer, when incremented, will point tothe next object of its type. Here a simple example,^ #include^ <

iostream^ > using namespace^ std; class myclass { int a; public: myclass( int^ x);^ //

constructor int^ get( ); }; myclass :: myclass( int

x) { a=x; } int^ myclass :: get( ) { return^ a; } int main ( ) {^ myclass ob(120);

// create object myclass^ ***** p;^

// create pointer to object p= & ob;^ //

put address of ob into p cout <<^ "value using object: "

<<^ ob. get( ); cout^ <<^ "\n"; cout <<^ "value using pointer: "

<<^ p -> get( ); return^ 0;

} Notice how the declaration myclass^ * p; creates a pointer to an object of myclass. It is important to understand thatcreation of an object pointer

does not^ create an object. It creates just a pointer to

one. The address of

o b^ is put into^ p^ by using the statement: p=&ob;

Finally, the program shows how the members of an object can be accessedthrough a pointer. We will come back to object pointer later. For the moment, here are severalspecial features that relate to them.

I^ N-^ LINE FUNCTIONS

In C++, it is possible to define functions that are not actually called but, rather,are expanded in line, at the point of each call. This is much the same way that aC-like parameterised macro works. The advantage of in-line functions is that they can be executed much faster thannormal functions. The disadvantage of in-line functions is that if they are too large and called tooften, your program grows larger. For this reason, in general only

short^ functions

are declared as in-line functions. To declare an in-line function, simply precede the function’s definition with the inline^ specifier. For example,^ // example of an in-line function^ #include^ <

iostream^ > using namespace^ std; inline int even( int^ x) { return^ !(x%2); } int main ( ) { if (even(10))^ cout <<

"10 is even\n";

Standard C++ programming

VFR November, 03^

SE2B2 Further Computer Systems

if^ (even(11))^ cout <<

"11 is even\n";

return^ 0; } In this example the function^ e v e n ( )

which return^ t r u e

if its argument is even,

is declared as being in-line. This means that the line^ if^ (even(10))

cout <<^ "10 is even\n";

is functionally equivalent to^ if^ (!(10%2))

cout <<^ "10 is even\n";

This example also points out another important feature of using

inline : an in-

line function must be define

before^ it is first called. If it is not, the compiler has

no way to know that it is supposed to be expanded in-line. This is why

e v e n ( )

was defined before^

m a i n ( )^.

Depending upon the compiler, several restrictions to in-line functions may apply.If any in-line restriction is violated the compiler is free to generate a normalfunction. Automatic in-lining If a member function’s definition is short enough, the definition can be includedinside the class declaration. Doing so causes the function to automatically becomean in-line function, if possible. When a function is defined within a classdeclaration, the^ inline

keyword is no longer necessary. However, it is not an

error to use it in this situation.^ // example of the divisible function^ #include^ <

iostream^ > using namespace^ std; class samp { int i, j; public: samp(int a, int b); // divisible is defined here and // automatically in-lined int divisible( ) { return !(i%j); } }; samp :: samp(int a, int b){ i = a; j = b; }

int main ( ) {^ samp ob1(10, 2), ob2(10, 3);^ // this is true^ if (ob1.divisible( ))

cout<<^ "10 divisible by 2\n"; // this is false if^ (ob2.divisible( ))

cout <<^ "10 divisible by 3\n"; return^ 0; } Perhaps the most common use of in-line functions defined within a class is todefine constructor and destructor functions. The samp class can more efficientlybe defined like this: //... class^ samp {^ int^ i, j; public:^ // inline constructor^ samp(int a, int b) { i = a; j = b; }^ int^ divisible( ) { return !(i%j); } }; //...^ MORE ABOUT CLASSES Assigning object One object can be assigned to another provided that both are of the same type. Bydefault, when one object is assigned to another, a bitwise copy of all the datamembers is made. For example, when an object called

o 1^ is assigned to an

object called^ o 2^ , the contents of all

o 1 ’^ s data are copied into the equivalent

members of^ o 2.^ // an example of object assignment.^ //...^ class^ myclass {^ int a, b;^ public:^ void set(int i, int j) { a = i; b = j; };^ void show( ) { cout << a << " " << b << "\n"; }^ };^ int main ( ) {

Standard C++ programming

VFR November, 03^

SE2B2 Further Computer Systems

//^ Set o.i to its square. //^ This affect the calling argument void^ sqr_it(samp o) {^ o->set(o->get_i( )o->get_i( )); } // ... int main ( ) {^ samp a(10);^ sqr_it(&a);

//^ pass a’s address to sqr_it

// ... } Notice that when a copy of an object is created because it is used as an argumentto a function, the constructor function is not called. However when the copy isdestroyed^ (usually^ by^ going

out^ of^ scope^ when

the^ function^ returns),

the

destructor function is called. Be careful, the fact that the destructor for the object that is a copy of the argumentis^ executed^ when^

the^ function^ terminates

can^ be^ a^ source

of^ problems.

Particularly, if the object uses as argument allocates dynamic memory and freesthat that memory when destroyed, its copy will free the same memory when itsdestructor is called. One way around this problem of a parameter’s destructor function destroying dataneeded by the calling argument is to pass the address of the object and not theobject itself. When an address is passed no new object is created and therefore nodestructor is called when the function returns. A better solution is to use a special type of constructor called

copy constructor,

which we will see later on. Returning object from functions Functions can return objects. First, declare the function as returning a class type.Second, return an object of that type using the normal

r e t u r n^ statement.

Remember that when an object is returned by a function, a temporary object isautomatically created which holds the return value. It is this object that is actuallyreturned by the function. After the value is returned, this object is destroyed. Thedestruction of the temporary object might cause unexpected side effects in somesituations (e.g. when freeing dynamically allocated memory).^ // Returning an object^ // ...^ class^ samp {

char^ s[80]; public: void^ show( ) {^

cout^ << s << "\n"; } void^ set( char^ *str) {

strcpy (s, str); } }; // Return an object of type samp samp^ input( ) {^ char^ s[80];^ samp^ str;^ cout^ << "Enter a string: ";^ cin^ >> s;^ str.set(s);^ return^ str; } int main ( ) {^ samp ob;^ // assign returned object to ob^ ob = input( );^ ob.show( );^ return^ 0; } Friend functions: an introduction There will be time when you want a function to have access to the privatemembers of a class without that function actually being a member of that class.Towards this, C++ supports friend functions. A friend function is not a memberof a class but still has access to its private elements. Friend functions are useful with operator overloading and the creation of certaintypes of I/O functions. A friend function is defined as a regular, nonmember function. However, insidethe class declaration for which it will be a friend, its prototype is also included,prefaced by the keyword^

friend.^ To understand how this works, here a short

example:^ // Example of a friend function^ // ...^ class^ myclass {^ int^

n, d; public: myclass( int^ i,^ int^

j) { n = i; d = j; } // declare a friend of myclass

Standard C++ programming

VFR November, 03^

SE2B2 Further Computer Systems

friend int^ isfactor(myclass ob); }; /* Here is friend function definition. It returns true if d is a factor of n. Notice that the keyword friend is not used in the definition of isfactor( ). */ int isfactor(myclass ob) { if^ ( !(ob.n % ob.d) )

return^ 1; else return^ 0; } int main ( ) { myclass ob1(10, 2), ob2(13, 3); if (isfactor(ob1))

cout^ << "2 is a factor of 10\n";^ else cout

<< "2 is not a factor of 10\n"; if (isfactor(ob2))^ cout^ << "3 is a factor of 13\n";^ else cout

<< "3 is not a factor of 13\n"; return 0;

} It is important to understand that a friend function is not a member of the class forwhich it is a friend. Thus, it is not possible to call a friend function by using anobject name and a class member access operator (dot

or arrow). For example,

what follows is wrong.^ ob1.isfactor( );

// wrong isfactor is not a member^ // function

Instead friend functions are called just like regular functions. Because friends are not members of a class, they will typically be passed one ormore objects of the class for which they are friends. This is the case with i s f a c t o r ( ).^ It is passed an object of

m y c l a s s , called^ o b

. However, because

i s f a c t o r (^ )^ is a friend of myclass, it can access

o b^ ’s private members. If

i s f a c t o r ( )^ had not been made a friend of

m y c l a s s^ it would not have access to

o b. d^ or^ o b. n^ since

n^ and^ d^ are private members of

m y c l a s s.

A friend function is not inherited. That is, when a base class includes a friendfunction, that friend function is not a friend function of the derived class. A friend function can be friends with more than one class. For example,^ // ...

class^ truck;^ //

This is a forward declaration class^ car {^ int^ passengers;^ int^ speed;^ public:^ car( int^ p,

int^ s) { passengers = p; speed =s; } friend int sp_greater(car c, truck t); }; class^ truck {^ int^ weight;^ int^ speed;^ public:^ truck( int^

w,^ int^ s) { weight = w; speed = s; } friend int sp_greater(car c, truck t);

}; int^ sp_greater(car c, truck t) {^ return^ c.speed - t.speed; } int main ( ) {^ // ... } This program also illustrates one important element: the

forward declaration

(also

called a^ forward reference

), to tell the compiler that an identifier is the name of a

class without actually declaring it. A function can be a member of one class and a friend of another class. Forexample,^ // ...^ class^ truck; //

forward declaration class^ car {^ int^ passengers;^ int^ speed;^ public:^ car( int^ p,

int^ s) { passengers = p; speed =s; } int sp_greater( truck t); }; class^ truck {^ int^ weight;^ int^ speed;

Standard C++ programming

17

VFR November, 03^

SE2B2 Further Computer Systems

You can also have multidimensional arrays of objects. Here an example,^ //^ Create a two-dimensional array of objects^ // ...^ class^ samp {^ int^

a; public: samp( int^ n) {a = n; } int get_a( ) {^ return

a; } }; int main ( ) {^ samp ob[4][2] = {

1, 2, 3, 4, 5, 6, 7, 8^ };

int^ i; for^ (i=0; i<4; i++)

cout^ << ob[i][0].get_a( ) << "

cout^ << ob[i][1].get_a( ) << "\n"; } cout^ << "\n"; return^ 0; } This program displays, 1 23 45 67 8 When a constructor uses more than one argument, you must use the alternativeformat, // ... class samp { int^ a, b; public: samp( int^ n,^ int^ m) {a = n; b = m; } int^ get_a( ) {^ return

a; } int^ get_b( ) {^

return^ b; } }; int main ( ) {^ samp ob[4][2] = {

samp(1, 2), samp(3, 4),

samp(5, 6), samp(7, 8), samp(9, 10), samp(11, 12), samp(13, 14), samp(15, 16) }; // ... Note you can always the long form of initialisation even if the object takes onlyone argument. It is just that the short form is more convenient in this case. Using pointers to objects As you know, when a pointer is used, the object’s members are referenced usingthe arrow (- >) operator instead of the dot (.) operator. Pointer arithmetic using an object pointer is the same as it is for any other datatype: it is performed relative to the type of the object. For example, when anobject pointer is incremented, it points to the next object. When an object pointeris decremented, it points to the previous object. //^ Pointer to objects // ... class^ samp {^ int^ a, b;^ public:^ samp( int^ n,

int^ m) {a = n; b = m; } int get_a( ) {^ return^ a; } int get_b( ) {^ return^ b; } }; int main ( ) {^ samp ob[4] = {

samp(1, 2), samp(3, 4), samp(5, 6), samp(7, 8) }; int^ i; samp *p; p = ob;^ //^ get starting address of array for^ (i=0; i<4; i++) {^ cout^ << p->get_a( ) << "

cout^ << p->get_b( ) << "\n"; p++;^ //^ advance to next object } // ...

Standard C++ programming

VFR November, 03^

SE2B2 Further Computer Systems

The THIS pointer C++ contains a special pointer that is called

this^.^ this^ is a pointer that is

automatically passed to any member function when it is called, and it points to theobject that generates the call. For example, this statement,^ ob.f1( );^

//^ assume that ob is an object

the function^ f 1 ( )^ is automatically passed as a pointer to

o b ,^ which is the object

that invokes the call. This pointer is referred to as

t h i s.

It is important to understand that only member functions are passed a

this

pointer. For example a friend does not have a

this^ pointer.

//^ Demonstrate the this pointer # include^ <^ iostream

include^ <^ cstring

using namespace

std; class^ inventory {^ char^ item[20];^ double^ cost;^ int^ on_hand;^ public:^ inventory(

char^ *i,^ double

c,^ int^ o) { // access members through // the this pointer strcpy ( this ->item, i); this ->cost = c; this ->on_hand = o; } void^ show( ); }; void inventory::show( ) { cout^ <<^ this ->item;

// use this to access members cout^ << ": £" <<

this ->cost; cout^ << "On hand: " <<

this ->on_hand <<"\n";

} int main ( ) {^ // ... } Here the member variables are accessed explicitly through the

this^ pointer. Thus,

within^ s h o w( ) ,^ these two statements are equivalent:^ cost = 123.23;^ this ->cost = 123.23;

In fact the first form is a shorthand for the second. Though the second form isusually not used for such simple case, it helps understand what the shorthandimplies. The^ this^ pointer has several uses, including aiding in overloading operators (seelater). By default, all member functions are automatically passed a pointer to theinvoking object. Using NEW and DELETE When memory needed to be allocated, you have been using

m a l l o c (^ )^ and

f r e e ( )^ for freeing the allocated memory. Of course the standard C dynamicallocation functions are available in C++, however C++ provides a safer and moreconvenient way to allocate and free memory. In C++, you can allocate memoryusing^ new^ and release it using

d e l e t e. These operator take the general form,

p-var^ =^ new^ type

delete^ p-var ; Here type^ is the type of the object for which you want to allocate memory and

p-

var^ is a pointer to that type.

new^ is an operator that returns a pointer to

dynamically allocated memory that is large enough to hold an object of type type.^ d e l e t e^ releases that memory when it is no longer needed.

d e l e t e^ can be

called only with a pointer previously allocated with

new.^ If you call^

d e l e t e

with an invalid pointer, the allocation system will be destroyed, possibly crashingyour program. If there is insufficient memory to fill an allocation request, one of two actions willoccur. Either^ new^

will return a null pointer or it will generate an exception. In

standard C++, the default behaviour of

new^ is to generate an exception. If the

exception is not handle by your program, your program will be terminated. Thetrouble is that your compiler may not implement

new^ as in defined by Standard

C++. Although^ new^ and

d e l e t e^ perform action similar to

m a l l o c ( )^ and^ f r e e ( ) ,

they have several advantages. First,

new^ automatically allocates enough memory

to hold an object of the specified type. You do not need to use

s i zeo f.^ Second,

new^ automatically returns a pointer of the specified type. You do not need to usean explicit type cast the way you did when you allocate memory using

m a l l o c (

).^ Third, both^ new

and^ d e l e t e^ can be overloaded, enabling you to easily

Standard C++ programming

20