C For Scientific Computing - Heidelberg University

2y ago
3 Views
2 Downloads
853.35 KB
107 Pages
Last View : 27d ago
Last Download : 3m ago
Upload by : Julia Hutchens
Transcription

C for Scientific ComputingStefan LangInterdisciplinary Center for Scientific Computing, University of Heidelberg15. Oktober 2015Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 20151 / 85

C für Wissenschaftliches Rechnen I1234567891011Why C ?MotivationConcepts of C Basic LiteratureBasic TechniquesThe first ProgramCompiling and LinkingFundamental C Data TypesControl FlowFunctionsPointer and ReferencesMemory Management in C Abstract Data Types and Their Realisation in C ClassesConstructors and DestructorsTemplates and Generic ProgrammingThe Standard Template Library (STL)Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 20152 / 85

C für Wissenschaftliches Rechnen II12131415161718192021Example of a Container Class: VectorsThe Iterator InterfaceBuilt-in Algorithms of the STLInheritance in C Virtual Functions and Abstract Base ClassesVirtual FunctionsPure Virtual Functions and Abstract Base ClassesStatic vs. Dynamic PolymorphismDynamic PolymorphismStatic Polymorphism and EnginesTraits and PoliciesTraitsTemplate Meta ProgrammingTemplate SpecialisationSingletonsExceptionsAdvanced LiteratureStefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 20153 / 85

Why C ?MotivationRequirements onto the programming language Efficiency. . . of program of development Hardware-related programming language Integration with existing code Abstraction Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 20154 / 85

Why C ?MotivationComparison of C with other languagesFortran & C –only procedural language–low flexibility–bad maintainability–difficult to optimize–mostly more memory consumptionfast codegood optimizationC good maintainability fast code good integration with Fortran and Clibraries high degree of abstractionStefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 20155 / 85

Why C ?Concepts of C Concepts of C C is an object-oriented languagethis means C supports1Abstraction by classes and objects,2Inheritance and3Polymorphism during runtime.Polymorphism means Many Shapes“:” A variable can change its type during runtime, A function with polymorphic arguments, A function name, that is used by functions with different impelementation.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 20156 / 85

Basic LiteratureLiteratureLiterature for C B. Stroustrup: C – The Programming Language (The Bible) B. Eckel: Thinking in C , Volume 1 2 A. Willms: C Programmierung (well for beginners!)Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 20157 / 85

Basic TechniquesBasic C KnowledgeTo exhaust the advantages of C abstract techniques are necessary. Thefollowing basic concepts are as a basis imperative: Basic data types and control structures: int, double, bool, char, . conditionals: if, switch, . loops: for, while Basic program structures: Functions Recursive and iterative programming Pointers and References Classes and Inheritance class and struct private, public, protectedConstructors and Destructorspublic, private inheritance(pure) virtual functions abstract base classes Polymorphism of functions, operator overloading Dynamic memory management (new, delete) Exception handlingStefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 20158 / 85

The first ProgramHello World!12// include I/O-library# include iostream 3456789// main is always the first function to be called// argc: program argument counter// argv: pointer to C-Strings containing the argumentsint main ( int argc , char ** argv ){std :: cout " Hello , world . " std :: endl ;10// return value of mainreturn 0;111213}Establishing the executable necessitates only a compiler (g ):SourceCodeStefan Lang (IWR, Heidelberg)CompilerC for Scientific ComputingProgram15. Oktober 20159 / 85

The first ProgramCompilation with LinuxFor larger projects the C -build process is typically quite complicated.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201510 / 85

Compiling and LinkingCompilation Process in C The fine granular construction of an executable program in C is coordinated inseveral steps:Build Process The preprocessor analyzises the code and performs substitutions on textualbasis (i.e. the substitution of macros and equivalent). The compiler generates herefrom the object code, this means, it analyzeseswhich objects are necessary and have to be constructed. The object code is linked by the linker with other libraries and construct theexecutable program. The control of the process is performed via makefiles, that are howevernowadays mostly hidden in the IDE.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201511 / 85

Compiling and LinkingCompilation Process in C The following figure shows an overview of the steps to construct an executableprogram in C :source filesinclude fan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201511 / 85

Fundamental C Data TypesData Types in C The elementary data types in C are:intlongcharfloatdoubleboolIntegersLarge IntegersCharactersFloating point numbers 4ByteFloating point numbers 8Byteboolean valuesStefan Lang (IWR, Heidelberg)C for Scientific Computingint a 2;long a 1e15;char a ’b’;float b 3.14;double c 3.1415;bool d false;15. Oktober 201512 / 85

Fundamental C Control FlowBranchesif-branches:1# include iostream 2345678910111213int main ( int argc , char ** argv ){int a 5; // an integer variableif ( a 0){std :: cout " Hello , World . " std :: endl ;}else{return 1; // emit an error}14return 0;1516}Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201513 / 85

Fundamental C Control FlowRealisation of Loops for loops, while loops, do.while loops.1# include iostream 23456int main ( int argc , char ** argv ){for ( int i 1; i 10; i )std :: cout " i : " i std :: endl ;7int j 5;while ( j 0){std :: cout " j : " j std :: endl ;j - -;}891011121314return 0;1516}Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201514 / 85

Fundamental C FunctionsFunctionsFunctionsFunctions are needed for encapsulation of program sections and can be calledwhen necessary.In C their syntax always isreturn - value function - name ( parameter1 , parameter2 , .) ;Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201515 / 85

Fundamental C FunctionsAn Example Program with Function1# include iostream 234using namespace std ; // use namespace std globally (here ok,// avoid this in the general case)567891011// A function that greets everyonevoid greet (){// do not need namespace-selector std:: any morecout " Hello , World . " endl ;}12131415161718// main functionint main ( int argc , char ** argv ){greet () ;return 0;}Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201516 / 85

Fundamental C FunctionsCall-by-Reference und Call-by-ValueIn Call-by-Value the address of the object is passed as function parameter and noobject copy is constructed:1234567// call-by-valuevoid swap wrong ( int a , int b ){int tmp a ;a b;// does not work, a and b are local copiesb tmp ;// in the scope of the function}89101112131415// call-by-referencevoid swap right ( int & a , int & b ){int tmp a ; // a, b are reference parametersa b;// That means changes to them areb tmp ;// persistant after end of function call}Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201517 / 85

Fundamental C FunctionsCall-by-Reference und Call-by-Value1234// main functionint main ( int argc , char ** argv ){int a 5 , b 6;5// Output 5, 6swap wrong (a , b )std :: cout a " , " b std :: endl ;6789// Output 6, 5swap right (a , b )std :: cout a " , " b std :: endl ;10111213return 0;1415}Shall changes of a function be persistent always reference variablen have to beused (see in swap right).Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201517 / 85

Pointer and ReferencesPointer and ReferencesOne of the more complicated themes in C/C are pointers and references.Pointer and the address operator & int x 12The variable x is defined by adress, size (necessary storage demand), nameand contents. To evaluate the value of the address (not the variable x!) theAdressoperator & is realized:std :: cout & x std :: endl // Output: 0xA0000000 Address values can be stored in pointer variables. Pointer variables have thesyntax Typ* name, type ist the type of the object, on which the pointer points:int * z & x ; // z is a pointer variableStefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201518 / 85

Pointer and ReferencesPointer and ReferencesThe dereference operator * Using the pointer variable zint * z & x ; // z is a pointer variablethe value of the variable x can also be changed. Herefor exists the(dereference operator *):* z 4711; // z is dereferenced, x has now the value 4711 Caution:- With the dereference operator the pointer z is not changed. (z points still ontothe memory address of x).- The symbol * denotes according to the context a dereference operator or apointer variable.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201518 / 85

Pointer and ReferencesPointer and ReferencesThe relationhip between pointer variable, adress- and dereference operator isclarified in the following figure:pointer variable intPtrint* intPtr &iaddress operator &&*intPtr 6dereference operator *Stefan Lang (IWR, Heidelberg)C for Scientific Computing1i6*i15. Oktober 201518 / 85

Pointer and ReferencesPointer and ReferencesReferencesBesides pointer variables there are references. References are internal pointers. References can be considered as another name“ for a variable:”123int x 5;int & y x ; // another name for xy 4;// means x 4!Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201518 / 85

Pointer and ReferencesPointer and ReferencesExample for pointer and references:12int i , j , *p , * q ;int & s i , & r j ; // references have to be initialized345r 2;r &j;// OK, j ( r) has now value 2// BAD, &j has worng type ’int *’ instead of ’int’p 2;p &j;// BAD, 2 has wrong type ’int’ instead of ’int *’// OK, p contains now the address of j67891011if ( p q ) // TRUE, if p, q point to the same address// the contents of the address does not matter.12131415if ( r s ) // TRUE, if the contents of j (reference of r) and i// (reference of s) is equal. The adress of the// variable does not matter!Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201519 / 85

Pointer and ReferencesPointer and References(Multi-dimensional) arrays are nothing else than pointer onto the first array entry:1int a [5];// Array of 5 int variables2345a [0] 3;std :: cout * a ; // output: 3 ( a[0])std :: cout & a ; // output: adress of a[0]67int a [3][20];Stefan Lang (IWR, Heidelberg)// 3 x 20 arrayC for Scientific Computing15. Oktober 201520 / 85

Pointer and ReferencesPointers and ReferencesPointer enable arbitrary complicated constructs:1int ** p ;// p contains a pointer onto variables pointing// onto type ’int’int * p [10];// p is an array, that contains 10 int * variables,// though the brackets [] bind stronger than *.// this means int * is the type of the array elements!23456789int (* p ) [10]; // Now instead p is a pointer onto an array// with 10 int-components1011int * f ()1213Stefan Lang (IWR, Heidelberg)// f is a parameterless function, that// returns a pointer onto an int.// Rounded brackets bind stronger, as above!C for Scientific Computing15. Oktober 201521 / 85

Memory Management in C Memory Segments in C programsIn C there are esentially thress memory segments where objects can be stored.These are:Memory segments in C 1The global memory segment. It stores all global variables and staticcomponents of classes and compiled directly into the executable file.2The stack contains all instances of currently executed methods and functionsand their related local variables.3The heap provides memory, that can be allocated for dynamically allocatedobjects.The management of dynamic memory is performed in C by the operatoren newand delete.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201522 / 85

Memory Management in C Memory Allocation with newMemory space can allocated from the heap with new:int * intPtr ;intPtr new int ; // intPtr points onto the new int memoryWithe the code line intPtr new int; memory space is allocated for namelessobject of type int and pointer to it is returned.The construct new int reserves space in the heap for an int value, provides a pointer onto the allocated memory space.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201523 / 85

Memory Management in C Freeing of Memory with deleteAllocated memory space should be freed when an object is not necessary anymore.This happens with the instruction delete:int * intPtr ;intPtr new int ;// intPtr points onto the new int memorydelete intPtr ;// memory is freedStefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201524 / 85

Memory Management in C Life Cycle of ObjectsDie life time of objects depends on the structure of the program: Static and global variables exist during the complete run time. Local variables exist as long as the function, they belong to, exist. They arecreated and destroyes with each new instance. Dynamic objects in the heap exist independently of the program structure,their life time is controlled by new and delete.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201525 / 85

Memory Management in C Life Cycle of ObjectsThe following code clarifies the different life times of dynamic and static variables:int foo () {int * p new int ;* p 5;return p ;}void main ( void ) {int * q foo () ;.delete q ;q NULL ;.}Stefan Lang (IWR, Heidelberg)////////Generate an nameless variable in the heapThe nameless variable is initialized with 5.A pointer onto a nameless variableis returned. Bad!////////q is generated is initialized with a pointeronto the nameless variable.The nameless variable in the heap is destroyedOK, q ist now secured (point to nothing)// Program end: variable q is deletedC for Scientific Computing15. Oktober 201525 / 85

Abstract Data Types and Their Realisation in C ClassesClasses and Data TypesA C class defines a data type. A data type is a status set with operations, thattransform states into each other. Example complex numbers:1# include iostream 2345678class ComplexNumber { // a class defintionpublic :void print (){std :: cout u " i * " v std :: endl ;}9101112private :double u , v ;};// ’;’ is very important!1314151617int main ( int argc , char ** argv ){ComplexNumber a , b , c ;a . print () ;// print unitialized (!) number18//c a b; // where defined?1920return 0;2122}Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201526 / 85

Abstract Data Types and Their Realisation in C ClassesClasses and Data Types C enables the encapsulation of a data type, this means separation ofimplementation and interface. public: Interface specification, private: Data and implementation. From outside only methods and data in the public part can be accessed. Implementation of methods can happen outside of the class.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201527 / 85

Abstract Data Types and Their Realisation in C Constructors and DestructorsConstructors The instruction ComplexNumber a; make the compiler generate an instance ofthe class. For initialisation the constructor is called. There can exist several constructors (polymorphism!). In certain cases the compiler generates default constructors.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201528 / 85

Abstract Data Types and Their Realisation in C Constructors and DestructorsConstructorsThe class ComplexNumber with two constructors:12345class Co mplexNum bers{public :// some constructorsComplexNumber () { u 0; v 0; }// default678ComplexNumber ( double re , double im ) // initialize with{ u re ; v im ; }// given numbers910void print () { . }11121314private :double u , v ;};Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201529 / 85

Abstract Data Types and Their Realisation in C Constructors and DestructorsConstructoren123456// usage of the complex number classint main ( int argc , char ** argv ){ComplexNumber a (3.0 ,4.0) ;ComplexNumber b (1.0 ,2.0) ;ComplexNumber c ;7a . print () ;c a b;89// output: 3 i * 4// where defined ?10return 0;1112};Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201530 / 85

Abstract Data Types and Their Realisation in C Constructors and DestructorsDestructors Dynamic generated objects can be destructed, if they are not necessary anymore. Deletion of objects is handled by the destructor. Destructors are especially to be (self)implemented, if the class containspointer (e.g. arrays!). Furthermore when dynamic memory is used inside a class. Keywords for dynamic memory management: new, delete.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201531 / 85

Abstract Data Types and Their Realisation in C Constructors and DestructorsOverloading of OperatorsOperations for abstract data types (classes) The instruction a b is not defined for ComplexNumber and must be defined. For classes different operations e.g. , ,*,/,-,--, ,! ,!, ,[],.can be self-implemented. Classes, that implement the operator () are called Functors.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201532 / 85

Templates and Generic ProgrammingTemplatesTemplates – Code Patterns Templates enable the parameterisation of classes and functors. Templates decouple functions or algorithms from data types. Allowed parameters: Standard types like int, double, ., Own types (classes), Templates. Templates enable static polymorphism (see later). Templates generalize code Generic Programming“.”Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201533 / 85

Templates and Generic ProgrammingExample: Templated Function1# include iostream 2345678// example for a function templatetemplate class T T getMax ( const T & a , const T & b ){return (a b ) ? a : b ;}910111213int main (){inti 5, j 6, k;double l 10.4 , m 10.25 , n ;14k getMax int ( i , j ) ; n getMax double ( l , m ) ;std :: cout k " , " n std :: endl ;// output: 6, 10.415161718return 0;1920}Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201534 / 85

Templates and Generic ProgrammingExample: Templated Array Class1234567// a class that takes a template parametertemplate typename T class Array{public :int add ( const T & next , int n ) ;// add ’next’ at data[n]T & at ( int n ) ;T & operator []( int n ) { return at ( n ) ; } // overloaded operator891011private :T data [10];};12131415161718192021// add a new data membertemplate class T int Array T :: add ( const T & next , int n ){if (n 0 && n 10){data [ n ] next ; return 0;}else return 1;}Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201535 / 85

Templates and Generic ProgrammingExample: Templated Array Class2324252627// get a certain data membertemplate class T T & Array T :: at ( int n ){if (n 0 && n 10) return data [ n ];}2829303132333435// main program# include iostream int main (){Array int c ; c . add (3 ,0) ; c . add (4 ,5) ; c . add (0 ,1) ;std :: cout c . at (5) std :: endl ;// output: 436Array char d ; d . add ( ’x ’ ,9) ;std :: cout d . at (9) std :: endl ;// output: x37383940return 0;4142}Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201536 / 85

Templates and Generic ProgrammingFurther on Templates Templates are the foundation of generic programming in C ! Templates can be self-specialized (for special cases). Further template parameter are possible. Parameters may have default values.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201537 / 85

The STLSTL – The Standard Template LibraryIn C ther are many preexisting template container, that can be used forimplementation purposes. They are collected in a library, named STL.The STL is a collection of template classes and algorithms, provides many container classes (class, that mananges a set of objects), has therefore standardized user interfaces for the containers, is contained in the C standard library.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201538 / 85

The STLContainer Types of the STLThe STL provides different kinds of containers: Sequential containerExamples: Vectors, lists Container adapterRestricted Interface for arbitrary containersExample: Stacks, queues Associative containerKey-Value ContainerExample: Maps, MultimapsStefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201539 / 85

The STLDis/Advantages of the STLAdvantages and disadvantages of the STL Dynamic memory management Avoidance of array overruns High quality of containers Optimizability by staticpolymorphismStefan Lang (IWR, Heidelberg)–Very complicated, unstructurederror messages–High demands for compiler anddeveloper–Not all compilers are STL-ready(despite the STL is contained in theC standard)C for Scientific Computing15. Oktober 201540 / 85

The STLExample of a Container Class: VectorsExample for the Application of STL containers:vector12# include iostream # include vector 34567int main () {// example usage of an STL vectorint result 0;std :: vector int x (100) ;8for ( int j 0; j 100; j ) x [ j ] j ;910x . push back (100) ;1112for ( int j 0; j x . size () ; j )result x [ j ];131415// output: 5050std :: cout result std :: endl ;161718return 0;1920}Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201541 / 85

The STLThe Iterator InterfaceThe Iterator InterfaceIterators provide access onto the elements of a container. They iterate over the elements of a container, provide pointer onto container elements, are provided by every container class, have r“- and w“ variants,”” help to avoid array overflows. are used in many STL algorithms like sorting, searching and others.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201542 / 85

The STLThe Iterator InterfaceExample: Iterators over a Map123# include iostream # include map # include cstring 45678int main (){// example usage of an STL-mapstd :: map std :: string , int y ;9y [ " one " ] 1; y [ " two " ] 2;y [ " three " ] 3; y [ " four " ] 4;101112std :: map std :: string , int :: iterator it ;//std::map¡std::string, double¿::iterator it; // nice error message :-)for ( it y . begin () ; it ! y . end () ; it )std :: cout it - first " : " it - second std ::endl ;// output: one: 1// two: 2 . usw.13141516171819return 0;2021}Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201543 / 85

The STLThe Iterator InterfaceAn Disadvantage of the STL: The error messaageIf in this example the wrong type of an iterator is instantiated, the compilerreturns the followoing error message:12345map . cc : In function ’ int main () ’:map . cc :15: error : no match for ’ operator ’ in ’ it y . std :: map Key ,Tp , Compare , Alloc :: begin [ with Key std :: basic string char, std :: char traits char , std :: allocator char , Tp int ,Compare std :: less std :: basic string char , std :: char traits char , std :: allocator char , Alloc std :: allocator std ::pair const std :: basic string char , std :: char traits char , std ::allocator char , int ]() ’/ usr / include / c /4.4/ bits / stl tree . h :154: note : candidates are : std ::Rb tree iterator std :: pair const std :: basic string char , std ::char traits char , std :: allocator char , double \& std ::Rb tree iterator std :: pair const std :: basic string char , std ::char traits char , std :: allocator char , double :: operator (const std :: Rb tree iterator std :: pair const std :: basic string char , std :: char traits char , std :: allocator char , double \&)map . cc :15: error : no match for ’ operator ! ’ in ’ it ! y . std :: map Key ,Tp , Compare , Alloc :: end [ with Key std :: basic string char ,std :: char traits char , std :: allocator char , Tp int ,Compare std :: less std :: basic string char , std :: char traits char , std :: allocator char , Alloc std :: allocator std ::pair const std :: basic string char , std :: char traits char , std ::allocator char , int ]() ’[.]Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201544 / 85

STL AlgorithmsAlgorithmsAlgorithms provided by the STLThe STL contains many helpful algorithms, that manipulate elements of data containers, use iterators for element access.Examples: Sorting Searching Copying Reversing the ordering in the container .Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201545 / 85

STL AlgorithmsAlgorithmsExample: Sorting-Algorithms for Vectors Different sorting orders for vectors are usable Distinction i.e. by: Used comparison operators Area of sorting Stability Complexity of Standard-Sorters for Vectors: O(n · log n) ideal O(n2 ) most unfavourable case Self-implemented comparision functions possible Caution: (double linked) lits are optimized for insertion and deletion ofelements special sorting algorithmsStefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201546 / 85

STL AlgorithmsAlgorithmsExample: Usage of a sorting algorithm for vectors12// a vector for integersvector int x ;3456x . push back (23) ; x . push back ( -112) ;x . push back (0) ; x . push back (9999) ;x . push back (4) ; x . push back (4) ;789// sort the integer vectorsort ( v . begin () , v . end () ) ;10111213// output: -112 0 4 4 23 9999for ( int i 0; i x . size () ; i )cout x [ i ] " \ t " ;Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201547 / 85

Inheritance in C Inheritance in C Inheritance Data type passes its abstractions to other data types. Is-an“ relation: Triangle is a geometric object, this means is to derive from”class GeomObject. Not to interchange with aContains-a“ relation: A triangle contains three points (but a triangle is no”point no inheritance).Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201548 / 85

Inheritance in C Inheritance in C 12345678// example of inheritance in C class Matrix{public :.private :double data [3][3]; // (3 x 3)-Matrix};910111213141516171819// the derived class: symmetrical matrix is a matrixclass SymMatrix : public Matrix{public :double getEntry ( int i , int j ) { return data [ i ][ j ]; }// error: data private in base class.// constructor calls a constructor of base classSymMatrix () : Matrix () { . }};Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201549 / 85

Inheritance in C Different Types of Inheritance in C In inheritance you have to take care of which members the derived class canaccess different types of inheritance: private inheritance:all elements of the base class get private members of the derived class. public inheritance:publicmembers of the base class get public members of the derived class,gets private.privateStefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201550 / 85

Inheritance in C Different Types of Inheritance in C Private member of the base class stay always private (otherwise theencapsulation make no sense). Problem: private members are encapsulated too strong, public members notin anyway. Ausweg: protected members can access onto derived classes.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201550 / 85

Virtual Functions and Abstract Base ClassesVirtual FunctionsVirtual FunctionsVirtual Functions enable the hiding of methods of the base class by the derivedclass:123class GeomObject{public :// base class for geo objects// ’area’ is a function member4virtual double area () { return 0.0; }.567};891011class Triangle : public GeomObject{// a derived classpublic :// has a specific member ’area’ as well12131415double area ().private :{ return 0.5 * a * h ; }16double h , a ;1718};Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201551 / 85

Virtual Functions and Abstract Base ClassesVirtual FunctionsVirtual FunctionsWhen Basis- and derived class members contain the same name – Which methodis then called?192021int main () {GeomObject * geo ;Triangle t ;22geo & t ;std :: cout geo - area () std :: endl ; // ?232425return 0;2627};Solution: If specified otherwise the methods of the basis object (!). By the keyword virtual the call is passed to the derived class. Keyphrase Late Binding, i.e. mapping method name implementationduring run time.Stefan Lang (IWR, Heidelberg)C for Scientific Computing15. Oktober 201552 / 85

Virtual Functions and Abstract Base ClassesVirtual FunctionsDynamic PolymorphismThe techniqueu of late type-bindung with virtual functions has its own name:Dynamic Polymorphism Exact type determination during runtime. Realisation by:- Virtual functions (Function Lookup Table),

10 Templates and Generic Programming 11 The Standard Template Library (STL) Stefan Lang (IWR, Heidelberg) C for Scienti c Computing 15. Oktober 2015 2 / 85. C f ur Wissenschaftliches Rechnen II Example of a Container Class: Vectors The Iterator Int

Related Documents:

Heidelberg College 310 East Market Street Tiffin, Ohio 44883-2462 1.800.Heidelberg www.heidelberg.edu Non-Profit Org. U.S. Postage PAID Heidelberg College Heidelberg CATALOG 2004 - 2005 2004-2005 Heidelberg College Catalog. Introduction 1 Academic Year Calendar ' Semester I 2004-2005 Sun. Aug. 29 First-year students and transfers arrive Mon .

Bruksanvisning för bilstereo . Bruksanvisning for bilstereo . Instrukcja obsługi samochodowego odtwarzacza stereo . Operating Instructions for Car Stereo . 610-104 . SV . Bruksanvisning i original

10 tips och tricks för att lyckas med ert sap-projekt 20 SAPSANYTT 2/2015 De flesta projektledare känner säkert till Cobb’s paradox. Martin Cobb verkade som CIO för sekretariatet för Treasury Board of Canada 1995 då han ställde frågan

service i Norge och Finland drivs inom ramen för ett enskilt företag (NRK. 1 och Yleisradio), fin ns det i Sverige tre: Ett för tv (Sveriges Television , SVT ), ett för radio (Sveriges Radio , SR ) och ett för utbildnings program (Sveriges Utbildningsradio, UR, vilket till följd av sin begränsade storlek inte återfinns bland de 25 största

Hotell För hotell anges de tre klasserna A/B, C och D. Det betyder att den "normala" standarden C är acceptabel men att motiven för en högre standard är starka. Ljudklass C motsvarar de tidigare normkraven för hotell, ljudklass A/B motsvarar kraven för moderna hotell med hög standard och ljudklass D kan användas vid

LÄS NOGGRANT FÖLJANDE VILLKOR FÖR APPLE DEVELOPER PROGRAM LICENCE . Apple Developer Program License Agreement Syfte Du vill använda Apple-mjukvara (enligt definitionen nedan) för att utveckla en eller flera Applikationer (enligt definitionen nedan) för Apple-märkta produkter. . Applikationer som utvecklas för iOS-produkter, Apple .

Cloud Computing J.B.I.E.T Page 5 Computing Paradigm Distinctions . The high-technology community has argued for many years about the precise definitions of centralized computing, parallel computing, distributed computing, and cloud computing. In general, distributed computing is the opposite of centralized computing.

distributed. Some authors consider cloud computing to be a form of utility computing or service computing. Ubiquitous computing refers to computing with pervasive devices at any place and time using wired or wireless communication. Internet computing is even broader and covers all computing paradigms over the Internet.