EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables...

39
EE4E. C++ Programming Lecture 1 Lecture 1 From C to C++ From C to C++

Transcript of EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables...

Page 1: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

EE4E. C++ Programming

Lecture 1Lecture 1

From C to C++From C to C++

Page 2: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Contents

IntroductionIntroduction VariablesVariables Pointers and referencesPointers and references FunctionsFunctions Memory managementMemory management

Page 3: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Introduction

C++ was developed at the Bell laboratories in the C++ was developed at the Bell laboratories in the mid 1980'smid 1980's

ANSI C is retained as a sub-set of C++ANSI C is retained as a sub-set of C++ C++ was designed to supportC++ was designed to support

Procedural programmingProcedural programming Modular programmingModular programming Data abstractionData abstraction Object-oriented programmingObject-oriented programming

Page 4: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Object-oriented v Procedural

C supports C supports proceduralprocedural programming programming The solution to a programming problem The solution to a programming problem

is through the use of a series of function is through the use of a series of function (or procedure) calls(or procedure) calls

These functions may well use data These functions may well use data structures but these are secondary to the structures but these are secondary to the solution of the problemsolution of the problem

Page 5: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

C++ supports C++ supports object orientedobject oriented programming programming The solution to a problem is through the design of The solution to a problem is through the design of

software units (objects) which have well controlled software units (objects) which have well controlled interactioninteraction

An object’s functions (methods) and data are on an An object’s functions (methods) and data are on an equal footingequal footing

There is a lot more to it than this (for example There is a lot more to it than this (for example inheritance and polymorphism)inheritance and polymorphism)

This course is intended to give you a good This course is intended to give you a good grounding in understanding object oriented grounding in understanding object oriented programming and designprogramming and design

First however, we must make the transition between First however, we must make the transition between C and C++C and C++

Page 6: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Variables C++ is much less restrictive than C in where C++ is much less restrictive than C in where

variables can be declared and initializedvariables can be declared and initialized In C++, variables can be declared and In C++, variables can be declared and

initialized anywhere, not just at the start of a initialized anywhere, not just at the start of a main program or function blockmain program or function block

However, this means the programmer has to However, this means the programmer has to have a good understanding of the rules of have a good understanding of the rules of variable scope and lifetime (which are fairly variable scope and lifetime (which are fairly obvious!)obvious!)

Page 7: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

A simple C++ program

int main() {

int k=1; // initializationif (k==1){

k++;int j; // declarationj=i+1;

}return 0;

}

Page 8: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

The scope and lifetime rules of variables are The scope and lifetime rules of variables are fairly obviousfairly obvious Typically the scope (and lifetime) of Typically the scope (and lifetime) of

automatic variables is the innermost automatic variables is the innermost program clauseprogram clause

Scope equals lifetime except for static Scope equals lifetime except for static variablesvariables

Scope errors are picked up by the Scope errors are picked up by the compilercompiler

Page 9: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Example

int main() {

int x=1; // Scope is the whole programint y=2; // Scope is the whole programif (x==y){

int z=x*y; }else{

int w=x+y; // OKz=2*w; // Scope error

}return 0;

}

Page 10: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Pointers and references

A pointer can be set up to access a variable A pointer can be set up to access a variable exactly as in C :exactly as in C :

int x = 1;

int* px=&x;

(*px)++; // increments x

(px)++; // increments the pointer

Page 11: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

1

x px

2(*px)++;

int x = 1;

int* px=&x;

px++;

Page 12: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

A A referencereference is an alternative name for a is an alternative name for a variablevariable The variable can be accessed through its The variable can be accessed through its

referencereference References can often be used in place of References can often be used in place of

pointerspointers

int x = 1;

int& rx=x; // reference to x

rx++; // increments x

Page 13: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

1

x, rx

2 rx++

int x = 1;

int& rx=x;

Page 14: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Comparison between pointers and references

A pointer occupies physical memoryA pointer occupies physical memory A pointers value can be changed (the A pointers value can be changed (the

pointer can be re-assigned)pointer can be re-assigned) A pointer can be nullA pointer can be null A reference can not be re-assignedA reference can not be re-assigned A reference must be initalizedA reference must be initalized

int& rx; // un-initialized reference!

Page 15: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Uses of references

The main use is in function arguments and return The main use is in function arguments and return valuesvalues They simplify the syntax of They simplify the syntax of pass by referencepass by reference

which, in C, is through the use of pointerswhich, in C, is through the use of pointers Also they can express object dependenciesAlso they can express object dependencies

One object can contain a One object can contain a referencereference to another to another which is more efficient than full object which is more efficient than full object aggregation (see later)aggregation (see later)

Page 16: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Functions

Function call and usage is the same as in C (but Function call and usage is the same as in C (but ANSI-style only!)ANSI-style only!)

Extra features of function usage include :Extra features of function usage include : Passing function arguments using referencesPassing function arguments using references Returning referencesReturning references Function overloadingFunction overloading Default parametersDefault parameters Inline functionsInline functions

Page 17: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Passing function arguments by reference

In C++ (and C) function arguments are In C++ (and C) function arguments are passed by value and by referencepassed by value and by reference Pass by reference in C is implemented Pass by reference in C is implemented

through the use of pointersthrough the use of pointers A side effect is that the function may A side effect is that the function may

change the value of its actual argument change the value of its actual argument on exiton exit

Page 18: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

void func(int arg1, int* arg2)void func(int arg1, int* arg2){{

// arg1 passed by value, arg2 passed by reference// arg1 passed by value, arg2 passed by referencearg1++;arg1++;(*arg2)++;(*arg2)++;

}}

void main() void main() {{

int i,j ;int i,j ;i=j = 0;i=j = 0;func(i,&j);func(i,&j);

// i=0, j=1// i=0, j=1}

Page 19: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

We can get the same effect by passing a We can get the same effect by passing a reference to the actual argument(s)reference to the actual argument(s)

void func(int arg1, int& arg2)void func(int arg1, int& arg2){{

// arg1 passed by value, arg2 passed by reference// arg1 passed by value, arg2 passed by referencearg1++;arg1++;arg2++;arg2++;

}}

void main() void main() {{

int i,j ;int i,j ;i=j = 0;i=j = 0;func(i,j);func(i,j);

// i=0, j=1// i=0, j=1}

Page 20: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Simpler syntax as we don’t need to remember to de-Simpler syntax as we don’t need to remember to de-reference formal arguments inside the functionreference formal arguments inside the function

However, functions with side-effects which change However, functions with side-effects which change the values of the arguments is not good programmingthe values of the arguments is not good programming

Better to get the functions to return an updated Better to get the functions to return an updated argumentargument

One situation which is common however is to pass One situation which is common however is to pass large objects by referencelarge objects by reference

Removes the overhead of actual->formal Removes the overhead of actual->formal argument copying if passed by valueargument copying if passed by value

A constant reference is used to prevent updating A constant reference is used to prevent updating the object inside the functionthe object inside the function

Page 21: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

void func(const large_structure& arg1)void func(const large_structure& arg1){{

// Constant reference prevents updating// Constant reference prevents updating....

}}

Page 22: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Functions returning references

A function can return a reference to an A function can return a reference to an object object

Allows function calls to be used as Allows function calls to be used as lvalueslvalues They can appear on the left hand side of They can appear on the left hand side of

assignmentsassignments This is a nice programming trick as long This is a nice programming trick as long

as we know what we are doingas we know what we are doing

Page 23: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Exampleint a[20];int a[20];

int zero=0;int zero=0;

int& access(int index)int& access(int index){{

if ((index>=0)&&(index<20))if ((index>=0)&&(index<20))return a[index];return a[index];

elseelsereturn zero;return zero;

}}

void main() void main() {{

int val1=access(7);int val1=access(7); // val1=a[7]// val1=a[7]access(8)=20;access(8)=20; // a[8]=20// a[8]=20

}

Page 24: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

The second assignment only works because The second assignment only works because access()access() returns a reference returns a reference

Essentially it returns an alternative name for Essentially it returns an alternative name for a[index]a[index] which means it can then be updated which means it can then be updated

Note that this function can not simply Note that this function can not simply return 0return 0

It has to return something that we can take the It has to return something that we can take the address of (an address of (an lvalue)lvalue)

Hence it returns Hence it returns zerozero – a variable containing 0 – a variable containing 0

Page 25: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Overloaded function names

Function overloading Function overloading enables several enables several functions with the same name to be definedfunctions with the same name to be defined

These functions must have different sets of These functions must have different sets of arguments (either type or number of arguments (either type or number of arguments)arguments)

The C++ compiler selects the function The C++ compiler selects the function with the with the bestbest match of the arguments list match of the arguments list to the one that has been calledto the one that has been called

Page 26: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Example – an overloaded power() function

We can supply several implementations of We can supply several implementations of the the power() power() function depending on the function depending on the argument typesargument types Integer exponentInteger exponent Floating point exponentFloating point exponent

Page 27: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

double power(double a, int b)double power(double a, int b) // Integer exponent// Integer exponent{{

// Computes a// Computes abb

if (b == 0)if (b == 0)return 1.0return 1.0

else if (b > 0)else if (b > 0){{

double r = 1.0;double r = 1.0;for (int i = 0; i < b; i++)for (int i = 0; i < b; i++)

r *= a;r *= a;return r;return r;

}}elseelse{{

double r = 1.0;double r = 1.0;for (int i = 0; i < b; i++)for (int i = 0; i < b; i++)

r /= a;r /= a;return r;return r;

}}}}

Page 28: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

double power(double a, float b)double power(double a, float b) // Floating point exponent// Floating point exponent{{

return(exp(b * log(a)));return(exp(b * log(a)));}}

int main(void)int main(void){{

double c = power(2.0,4)double c = power(2.0,4) // c=2// c=244 (Integer exponent) (Integer exponent)  

double d = power(2.7182818,0.5)double d = power(2.7182818,0.5) // d = // d = e e

}}

Page 29: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

This is a powerful feature and allows the This is a powerful feature and allows the power()power() function to be implemented for a range of (user function to be implemented for a range of (user defined) data typesdefined) data types

Complex numbersComplex numbers

MatricesMatrices

Function overloading is very often used to enable Function overloading is very often used to enable us to initialize objects in different ways (see later)us to initialize objects in different ways (see later)

C++ also allows us to redefine the actions of C++ also allows us to redefine the actions of operators (operators (operator overloadingoperator overloading) (see later)) (see later)

Page 30: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Functions with default arguments

This is a simple feature of C++ whereby This is a simple feature of C++ whereby we we can provide default values for can provide default values for trailingtrailing function arguments function arguments Useful for functions with long argument Useful for functions with long argument

listslists

Page 31: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

double power(double a, double b = 2.0)double power(double a, double b = 2.0){{

return(exp(b * log(a)));return(exp(b * log(a)));}}    int main(void)int main(void){{

double c = power(4.0)double c = power(4.0) // c = 4// c = 422

double d = power(4.0,10.0)double d = power(4.0,10.0) // d = 4// d = 41010 }}

Page 32: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Inline functions

The use of inline functions is a technique for The use of inline functions is a technique for increasing the speed of small functionsincreasing the speed of small functions

The compiler performs inline code expansion to The compiler performs inline code expansion to replace function calls with the actual code of the replace function calls with the actual code of the functionfunction

This is more efficient than performing a jump to This is more efficient than performing a jump to the memory location of the functionthe memory location of the function

Increases the size of the executable codeIncreases the size of the executable code Only use if the function body is a few lines of Only use if the function body is a few lines of

codecode

Page 33: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Keyword Keyword inlineinline indicates that the function is indicates that the function is inlineinline

Often used to define class methods within Often used to define class methods within the class declaration (see later)the class declaration (see later)

inline int max(int a, int b)inline int max(int a, int b){{

return (a >= b) ? a : b;return (a >= b) ? a : b;}}  

Page 34: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Memory management C++ has an identical memory management system C++ has an identical memory management system

to Cto C

There are 3 types of memory (variables)There are 3 types of memory (variables)

AutomaticAutomatic

DynamicDynamic

StaticStatic

Like C (but unlike Java) C++ does not have Like C (but unlike Java) C++ does not have automatic garbage collectionautomatic garbage collection

Page 35: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Automatic variablesAutomatic variables Memory allocated each time the variable Memory allocated each time the variable

definition is executed and automatically definition is executed and automatically destroyed when the containing block destroyed when the containing block terminatesterminates

Dynamic variables Dynamic variables Memory is allocated and de-allocated by Memory is allocated and de-allocated by

the programmer on the the programmer on the free store free store or or heapheap Static variablesStatic variables

Memory allocated once and not freed Memory allocated once and not freed until the program terminatesuntil the program terminates

Page 36: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

Dynamic variables Dynamic variable allocation is handled in C with the Dynamic variable allocation is handled in C with the

malloc()malloc() and and calloc()calloc() functions functions C++ also provides a C++ also provides a new new operator with which dynamic operator with which dynamic

variables can be createdvariables can be created Like Like malloc() malloc() and and calloc()calloc(), , newnew returns a pointer to the returns a pointer to the

variable allocatedvariable allocated C++ also provides a C++ also provides a deletedelete operator which frees up operator which frees up

dynamic memorydynamic memory new[]new[] and and delete[]delete[] can be used to allocate and de- can be used to allocate and de-

allocate dynamic arraysallocate dynamic arrays

Page 37: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

void main()void main(){{

int* p;int* p;p = new int;p = new int; // dynamically allocates an integer// dynamically allocates an integerif (p!=0)if (p!=0){{

(*p)=2;(*p)=2;}}delete p;delete p;

// dynamically allocate a 10 integer array// dynamically allocate a 10 integer arrayint* q = new int[10];int* q = new int[10];q[0]=1; q[9]=2;q[0]=1; q[9]=2;delete[ ] q; delete[ ] q;

}}

Page 38: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

An important point to note for advanced An important point to note for advanced usage is that usage is that newnew is an is an operatoroperator and not a and not a function (unlike function (unlike calloc()calloc() and and malloc()malloc())) newnew can be overloaded can be overloaded (re-defined) so, (re-defined) so,

for example, smart memory management for example, smart memory management routines can be created for user defined routines can be created for user defined objectsobjects

Page 39: EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.

And finally…… We have looked at some enhancements C++ provides to C for We have looked at some enhancements C++ provides to C for

procedural programmingprocedural programming Variable usageVariable usage ReferencesReferences Function overloadingFunction overloading Memory managementMemory management

The next lectures will cover major additional features of C++ The next lectures will cover major additional features of C++ for object oriented programmingfor object oriented programming ClassesClasses InheritanceInheritance PolymorphismPolymorphism