The C++ programming language

Slides:



Advertisements
Similar presentations
Programming in C Chapter 10 Structures and Unions
Advertisements

The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Chapter 7: User-Defined Functions II
CSCI 171 Presentation 11 Pointers. Pointer Basics.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
Informática II Prof. Dr. Gustavo Patiño MJ
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers Applications
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
Pointers and Arrays Beyond Chapter Pointers and Arrays What are the real differences? Pointer Holds the address of a variable Can be pointed.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Computer Graphics 3 Lecture 1: Introduction to C/C++ Programming Benjamin Mora 1 University of Wales Swansea Pr. Min Chen Dr. Benjamin Mora.
C LANGUAGE Characteristics of C · Small size
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
LThe C++ programming language Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 4./0. lThe object oriented view of the world.
LThe C++ programming language Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 5./0. lExample on definition of an object having.
C++ Programming Michael Griffiths Corporate Information and Computing Services The University of Sheffield
Memory Management.
Secure Coding Rules for C++ Copyright © 2016 Curt Hill
Expressions and Assignment Statements
The C++ Data Types Fundamental Data Types
The C++ programming language
Chapter 7: User-Defined Functions II
A bit of C programming Lecture 3 Uli Raich.
C Programming Tutorial – Part I
Programming Languages and Paradigms
Functions Separate Compilation
Pointers and Memory Overview
Programming Paradigms
C Basics.
Secure Coding Rules for C++ Copyright © Curt Hill
Programmazione I a.a. 2017/2018.
Lecture 6 C++ Programming
Pointers and References
This pointer, Dynamic memory allocation, Constructors and Destructor
Object Oriented Programming COP3330 / CGS5409
Chapter 15 Pointers, Dynamic Data, and Reference Types
7 Arrays.
Pointers, Dynamic Data, and Reference Types
More About Data Types & Functions
CSC 533: Programming Languages Spring 2015
Dynamic Memory Allocation
Chapter 15 Pointers, Dynamic Data, and Reference Types
Constructors and Other Tools
Classes, Constructors, etc., in C++
The C++ programming language
Pointers and Arrays Beyond Chapter 16
7 Arrays.
The C++ programming language
Pointers Pointers point to memory locations
The C++ programming language
Data Structures and Algorithms Introduction to Pointers
The C++ programming language
Programming Languages and Paradigms
CS1201: Programming Language 2
CSC 533: Programming Languages Spring 2018
Pointers, Dynamic Data, and Reference Types
EECE.2160 ECE Application Programming
CSC 533: Programming Languages Spring 2019
SPL – PS2 C++ Memory Handling.
Presentation transcript:

The C++ programming language Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./0. The C++ programming language Non object oriented novelties of C++ For definition of struct type variables the identifier is enough without struct type name Reference type The new and delete operators for handling dynamic memory Default input values for arguments of functions Function overloading: the same function name, different input and functioning Inline functions Variable definition between instructions Single line comments

Department of Information Engineering INFORMATION TECHNOLOGY dr Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./1. For definition of struct type variables the identifier is enough without struct type name struct studenttype {char name [20]; char group [5]; } ; studenttype studentvect [120] ; void main() { typedef struct planettype {char name[15] ; unsigned int diameter ; long int distance ; float circulation_duration ; char yearorday[4] ; } ; planettype planets[9] ; struct complextype {double Re ; double Im ;} ; complextype cmp, *cmpptr ; //... } Lényeg: a C-hez képest a struct szavak a változódefiniálásokból elhagyhatók. Első eset: globális hallgatorektip tipus deklarálása. Második eset: lokálisan megengedett, bár felesleges a typedef-fel történő struktúra típusnév deklarálás. Harmadik eset: a struct szó önmagában, typedef nélkül is típusértékű.

var = 11; printf(“%d”, varref ); // 11 Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./2. Reference type The reference type variable is substitutional name (alias) for an existing variable. They point to the same memory. int var ; int& varref = var ; var = 11; printf(“%d”, varref ); // 11 The reference variable and the substituted variable can be interchanged in operations. It is not allowed to define a reference variable as individual variable. The substituted variable has to be given at definition using assignment operation. What it is for if it is equivalent to the substituted variable?

Value passing by address to function using reference variable Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./3. Value passing by address to function using reference variable To get back modified value in the parameter of the function a pointer variable had to be used till now : void extremums (int a, int b, int* max, int* min) { if (a>b) { *max = a; *min= b; } else { *max = b ; *min = a ;} ; } // applying the function: int c=3, d=5, big, small ; extremums (c, d, &big, &small ); The * indirection operator has to be used in the body of the function and the & address operator needed in function call. This complicated method to get back value in function parameter is required in C language because of missing value passing by address possibility.

void extremums (int a, int b, int& max, int& min) Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./4. The solution of C++: value passing by address using reference variable! void extremums (int a, int b, int& max, int& min) { if (a>b) { max = a; min= b; } else { max = b; min = a;} ; } // applying the function : int c=3, d=5, big, small ; extremums (c, d, big, small ); //change of max is perceptible in the //global big too This solution is similar to solution of Pascal for value passing by address using var in parameter list. Applying the reference variable, parameters passed for modification can be distinguished from arrays, e.g. strings passed expediently with pointers. Passing big arrays using reference variable is advantageous too because copying them to stack is avoidable.

The new and delete operators for handling dynamic memory Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./5. The new and delete operators for handling dynamic memory For allocating memory in dynamic area the malloc() and calloc() functions are used in C language. Theirs disadvantage that the programmer has to give the type conversion (casting) and the size of the area that has to be allocated. Allocation in the Heap of a real vector having 200 elements is given as a reminder : #include <alloc.h> float * vectptr ; vectptr = (float*) calloc(200, sizeof(float)); //… free(vectptr ); The new and delete operators that handle the dynamic memory form part of C++ language.

Usage of the new and delete operators Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./6. Usage of the new and delete operators Example on dynamic allocation of a scalar and a vector : float * realptr ; float * vectptr ; realptr = new float; vectptr = new float[200]; if (! realptr || ! vectptr) // The value of pointers is NULL if unsuccessful {puts(“Memory allocation is unsuccessful! ”); exit(1);} // Usage of created dynamic variable is here delete[ ] vectptr; delete realptr;

Remarks on using new and delete operators Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./7. Remarks on using new and delete operators Important: every allocated memory has to be freed so the new and delete operators have to form pairs! Small variables have to be defined as local variables allowing the stack manager to handle theirs allocation and deallocation. But data structures having big size have to be managed by the programmer: allocation and deallocation on the Heap using new and delete operators. Pointers not initialised at definition has to be set to NULL immediately! Do not delete pointers having non NULL value more than one time! After clearing pointers by delete set them to NULL! Arrays allocated dinamically have to be freed using delete[] operator!

Default input values for arguments of functions Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./8. Default input values for arguments of functions The two aims of application of default values for function parameters: To avoid possible causes of errors that come from lack of parameters that can be skipped in C and C++ too. Extension of initialisation for parameters of functions. The initialisation is an important topic in C++. The default value assigned at initialisation of function parameter will have effect when the parameter is skipped, left in function call. The parameters can be left starting from the end of the parameter list when the function is called. Assigning of default parameter value is expedient to parameter that gets the same value in most of the cases of function calls.

Examples on functions using initialised parameters Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./9. Examples on functions using initialised parameters Let us make a function that draws a filled ellipse! The function draws filled circle if the fourth parameter - the vertical half axis - is not given. void MyFillellipse(int x, int y, int xradius, int yradius= 0) {if (yradius) fillellipse(x, y, xradius, yradius) ; else fillellipse(x, y, xradius, xradius); } // The function call: MyFillellipse(100,100,50); // filled circle with radius=50 MyFillellipse(200,200,70,30); // filled ellipse Remark: it would be elegant but only constant initialiser is allowed: void MyFillellipse(int x, int y, int xradius, int yradius= xradius) {...}

Examples on functions using initialised parameters, 2. Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./10. Examples on functions using initialised parameters, 2. Let us make a string copy function that substitutes the strcpy(), strncpy() and the Right§(); function, which is used in BASIC. The Right§() gives the given number character from the right hand side of the string. void MyStrncpy(char * tgt, char* source, int from=0, int count=2000) { //Right§-like acting: copies from from index to the '\0' character: if (count==2000) strncpy(tgt, source+from, strlen(source)-from+1); else strncpy(tgt, source+from, count); //acts at strncpy()-like call } //Examples on function calls: char target [20], str [20]={"outstanding"}; //strcpy()-like acting for string copy: MyStrncpy(target , str); // from =0; count =2000; target=="outstanding" //Right§()-like acting for copying the right hand side: MyStrncpy(target , str, 3); // from =3; count =2000; target =="standing" //strncpy()-like acting for copying a substring without '\0' : MyStrncpy(target , str, 3, 5); // from =3; count =5; target =={'s','t','a','n','d'}

int abs(int x); double fabs(double x); Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./11. Function overloading After learning Pascal language the type sensitiveness is disturbing, e.g. the absolute value function has different names depending on the type of the argument: int abs(int x); double fabs(double x); long int labs(long int x); double cabs(struct complex z); To eliminate this drawback of C language the C++ introduces the function overloading possibility. Functions having the same name but different number or type of parameters (different parameter signature) may have different function body, different working. This possibility shows good accordance to actions having the same names in real world. For example the next expressions cover different actions: to get a job, to get a disease, to get hauled over the coals.

The resolution of problem using the function overloading possibility Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./12. The resolution of problem using the function overloading possibility Calculation of absolute values in C++ can be performed using the abs() function after giving the definitions of functions having different parameter signatures : int abs(int x); // this macro is given double abs(double x) // parameter signature: double {return fabs(x);} long int abs(long int x) // parameter signature : long int {return labs(x);} double abs(complex z) // parameter signature : complex {return cabs(z);} Really the compiler makes functions with different names using the connected parameter signature to make differences.

The usage of namesake-functions got as a result of overloading Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./13. The usage of namesake-functions got as a result of overloading double r, v=23.456; int i, j ; r = abs(v); //the fabs( ) function works really i = abs(-12); //ERROR!! The compiler can not discriminate among //possible functions!! Solution: assigning the value to a variable, or //usage of explicit type conversion (casting): j = -12; i = abs( j ); //the signature is unambiguous: int i = abs( (int)-12 ); //type cast gives unambiguous signature: int The explicit type casting generally can be used if the signature is not suitable. The type of the function is not part of the signature! The next two prototypes cause compilation error : int funct( ); double funct( ); //ERROR!!

E.g.: inline long int square(int x) {return x*x;} Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./14. Inline functions The inline functions have short function body. The compiled code can be inserted into program code without significant growth of size of program. E.g.: inline long int square(int x) {return x*x;} Two reasons of introducing it in C++ are: The building elements of object oriented programming are objects that have a lot of small functions among member functions of a class definition. These functions do not require separated prototype and definition. The function macros of C language that play similar role can produce dangerous errors, especially after calling them with arguments applying incrementing operators. E.g.: #define square(x) (x)*(x) //calling the macro function: int x= 2, y; y= square(++x); // waited y == 9, resulted: y ==16

Variable definition between instructions Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./15. Variable definition between instructions The local variables of C language had to be defined in the beginning of blocks, before instructions. In addition to this C++ language allows variable definitions between instructions. In every place where an instruction is allowed can stand variable definition too. Such a type of variable will be created in the stack when its definition is reached and it can be referenced from this point to the end of block. The advantages of this possibility that variables are close to theirs application area and theirs initialisation is obvious in place of usage. As a consequence the chance of referencing to an earlier defined un-initialised variable is small. The typical example is defining the for cycle variables in the for cycle itself : for (int i =1, int sum=0; i<=100; i++) sum += i; //summation to 100

// this line have to be treated as a comment Department of Information Engineering INFORMATION TECHNOLOGY dr. László Dudás 26./16. Single line comments The C language uses the next form for placing comments in the source program: /* comment */ In addition to this C++ introduced the single line comments using the next syntax: // this line have to be treated as a comment The old and the new format can be used in mixed style too: // new new new /* old old old */ new new new new new /* old old old old old old // new new new new new new new old old old old old old old old old old old old old */