Presentation is loading. Please wait.

Presentation is loading. Please wait.

The C++ programming language

Similar presentations


Presentation on theme: "The C++ programming language"— Presentation transcript:

1 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

2 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ű.

3 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?

4 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.

5 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.

6 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.

7 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;

8 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!

9 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.

10 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) {...}

11 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'}

12 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.

13 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.

14 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!!

15 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

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

17 // 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 */


Download ppt "The C++ programming language"

Similar presentations


Ads by Google