advanced programming slides preliminary

Upload: raul-toledano

Post on 10-Mar-2016

226 views

Category:

Documents


0 download

DESCRIPTION

advanced programming

TRANSCRIPT

  • 118.07.2012 Janne Mntykoski 1

    Advanced programming

    Janne [email protected]

    Room B501

    18.07.2012 Janne Mntykoski 2

    Course focus

    C++ programming Advanced C programming Focus is on programming a microcontroller

    (mbed, LPC1768)

  • 2Main contents C++- Class - objects- Derived class base class inheritance- Polymorfism easier function naming C and C++- Strings- Pointers- Structure

    20.07.2012 Janne Mntykoski 3

    06.01.2008 Janne Mntykoski 4

    WWW-sites and books

    Wikipedia: C++ ja Olio-ohjelmointi Mureakuha: cpp.mureakuha.com Rintala ja Jokinen: Olioiden ohjelmointi C++:lla,

    Talentum Vaatii C-kielen osaamisen pohjalle Pivi Hietanen: C++ ja olio-ohjelmointi - Kattava

    C++ teos Overland: C++ Without Fear 2/E

    Osa kalvojen esimerkeist suoraan Wikipediasta tai Mureakuhasta

  • 318.07.2012 Janne Mntykoski 5

    Free programming environments

    Code:blocks supports both C and C++ -languageswww.codeblocks.org

    Dev-C++ supports both C and C++ -languageswww.bloodshed.net

    18.07.2012 Janne Mntykoski 6

    Embedded programming environment

    Online C++ compiler for mbed module, ARM Cortex-M3 LPC1768 microcontroller, Cortex-M0 module also available

    A lot of libraries for devices for mbedwww.mbed.org

  • 418.07.2012 Janne Mntykoski 7

    Why C++?

    C++ - language is very popular It supports modern coding technics like

    object oriented programming SystemC hardware description language

    is based on C++ The powerful mbed module supports C++,

    ARM Cortex-M3

    18.07.2012 Janne Mntykoski 8

    Introduction to C++ Development sterted in 1979 Main designer Bjarne Stroustrup Expands the C language with modern

    coding technics like object oriented programming

    Object oriented programming is very useful in big coding projects

    First ANSI standard in 1998, ANSI C++, ISO

  • 5C++ programming

    18.07.2012 Janne Mntykoski 9

    C++ source files, extension .cpp C++ header files, extension .h or .hpp

    Precompiler, #-directives

    Compiler, creates .obj files

    Linker, combines .obj files and adds startup code

    Executable program, extension .exe or .bin

    19.07.2012 Janne Mntykoski 10

    C and C++ comparisonC style#include main() {

    printf ("Hello World!\n");}C++#include int main() {

    std::cout

  • 6#include using namespace std;void main(void){

    char c;cout

  • 719.07.2012 Janne Mntykoski 13

    Class Circle.hpp file#include using namespace std;const double pi = 3.141; class Ball{private :

    // Place for variables and functionspublic:

    float ray_v;float GiveSurfaceArea(){ return pi*ray*ray; };float GiveCF(){ return 2.0*pi*ray; };

    };int main(){

    Ball ball1;

    ball1.ray_v = 3;cout

  • 818.07.2012 Janne Mntykoski 15

    Benefits from object oriented programming

    The code has been divided into clear sub-programs with objects:

    - Easier to design- Easier to understand- Easier to reuse- Easier to modify

    C code C++ code

    Ways to manage the code

    Use state machines to organise the code Use objects to combine variables and

    functions into understandable sub-programs

    When to use objects?: Definitely when the code size starts to increase

    18.07.2012 Janne Mntykoski 16

  • 918.07.2012 Janne Mntykoski 17

    Object oriented programming Three new things:

    - encapsulation -> objects and classes (type of object)- inheritance -> class reuse- polymorfism -> function name overloading

    By encapsulation we are hiding part of the complexity of the code -> object interface is simpler than the object

    Inheritance means less coding and more code reuse Polymorphism simplifies naming functions and their use

    18.07.2012 Janne Mntykoski 18

    Class Ball.hpp fileconst double pi = 3.141; class Ball{protected :

    float ray_v;// Place for Protected functions

    public:// Place for Public variables, not recommendedBall();Ball(float ray);~Ball() {};void SetRay(float raysade);float GiveRay();float GiveSurfaceArea();float GiveVolume();

    };

    Constant PIBegin class declaration

    Inheritable, Invisible to the outside

    External interface

    Class creatorsClass destructor

    Declaration ofClass functions

    ray_vGiveSurface

    Area

    GiveVolume

    SetRay

    GiveRay

    New Ray value

    The Ray value

    Surface AreaVolume

    Public inteface

    Protected variable

    End class declaration

    Class is the type of the object

  • 10

    #include #include Ball.hpp"Ball::Ball();

    Ball::SetRay(1.0);};Ball::Ball(float ray){

    Ball::SetRay(ray);}void Ball::SetRay(float ray){

    ray_m = ray;}float Ball::GiveRay(){

    return ray_v;}float Ball::GiveSurfaceArea(){

    return 4*pi*ray*ray;}float Ball::GiveVolume(){

    return 4.0/3.0*pi*ray*ray*ray;}

    18.07.2012 Janne Mntykoski 19

    Class Ball.cpp file

    DefinitionsofClass functions

    Class constructor, no parameters,default ray=1.0

    Class constructor with parameter

    ray_vSetRayNew Ray value

    ray_v GiveRay The Ray value

    ray_v GiveSurfaceArea

    Surface Area

    ray_v GiveVolume Volume

    Notice

    #include #include Ball.hpp"

    using namespace std;

    int main(){

    Ball ball1(2);Ball ball2;

    cout

  • 11

    18.07.2012 Janne Mntykoski 21

    Class constructors and destructor

    Constructor is called when object is created

    Constructor Object creation Initialization

    Ball(); Ball ball2; Default value(s)

    Ball(float ray); Ball ball1(2); Parameter value(s)

    Destructor Action

    ~Ball() {}; Free any reserved dynamicmemory

    Destructor is called when object is deleted or in the end of the program

    Complex objects

    Class constants: the same for class objects

    Class wide variable: the same for class objects

    Object copying possible Object pointers

    06.01.2008 Janne Mntykoski 22

  • 12

    Program pause

    Program will wait for ENTER to be pressed

    19.07.2012 Janne Mntykoski 23

    C style (DOS command) C++

    system(PAUSE); cin.get();#include

    Int main(void) {printf ("Hello!\n");system(PAUSE);return 0;

    }

    #include using namespace std;int main() {

    cout

  • 13

    20.07.2012 Janne Mntykoski 25

    StringsC C++

    #include #include

    int main(void) {char str1[30] = Hi!, str2[30];

    strcpy(str2, str1);if (strcmp(str1, str2) == 0)

    printf(They are equal\n);

    printf(Length: %d, strlen(str2););

    return 0;}

    #include #include using namespace std;int main () {

    string str1 = Hi!, str2;

    str2 = str1;if (str1 == str2)

    cout or equal to"

  • 14

    Inheritance example, ColoredBall

    Inheritance is an easy way to reuse code ColoredBall is called derived class19.07.2012 Janne Mntykoski 27

    ray

    GiveSurfaceArea

    GiveVolume

    SetRay

    GiveRay

    New Ray value

    The Ray value

    Surface Area

    Volume

    variables

    Functions

    Object interface

    SetColor GiveColorcolorNew Color value

    The Color value

    Inherited,Base class Ball

    19.07.2012 Janne Mntykoski 28

    Derived class ColoredBall.hpp file#include Ball.hpp"

    class ColoredBall : public Ball{private :

    int color_v;// Private functions

    public:ColoredBall();ColoredBall(float ray, int color);~ ColoredBall() {};void SetColor(int color);int GiveColor(void);

    };

    ray_vGiveSurface

    Area

    GiveVolume

    SetRay

    GiveRay

    New Ray valueThe Ray value

    Surface Area

    Volume

    Public inteface

    Private variable

    color_v

    SetColor

    GiveColor

    New Color valueThe Color value

    Base class Ball

    Inherit class Ball

    Not inheritable, Invisible to the outside

    External interfaceClass creators

    Class destructorDeclaration ofClass functions

    class Ball

  • 15

    19.07.2012 Janne Mntykoski 29

    Derived class ColoredBall.cpp file#include #include ColoredBall.hpp"

    ColoredBall () {ColoredBall::SetColor(1);

    };

    ColoredBall::ColoredBall (float ray, int color){

    Ball::SetRay(ray);ColoredBall::SetColor(color);

    }

    void ColoredBall::SetColor(int color){

    color_v = color;}

    int ColoredBall::GiveColor(void){

    return color_v;}

    Definitions of Class functions

    Class constructor, no parameters,default Color=1.0

    Class constructor with parameters

    color_vSetColorNew Color value

    color_v GiveColor The Color value

    Notice

    Class ColoredBall

    #include #include ColoredBall.hpp"using namespace std;int main(){

    ColoredBall ball1(3.0,2);ColoredBall ball2;

    cout

  • 16

    19.07.2012 Janne Mntykoski 31

    Function overloading is polymorfismC C++

    int abs(int); int abs(int);

    long labs(long); long abs(long);

    double fabs(double); double abs(double);

    There has to difference in parameter types Return type difference is not enough Polymorfism (=many forms) -> same

    function name, many different functions Operator overloading is also possible

    19.07.2012 Janne Mntykoski 32

    Polymorfism example, function abs#include using namespace std;

    Int abs( int n);double abs( double n );

    int main( ){

    cout

  • 17

    19.07.2012 Janne Mntykoski 33

    C and C++ comparisonC style

    #include int main(void){

    int i, j=1;printf(Give integer: );scanf(%d, &i);printf(i is %d, j is %d\n, i. j);

    }

    C++#include using namespace std;int main(){

    int i;cout

  • 18

    #include using namespace std;void funktio(int &intM, float &intM);int main(){

    int intN = 5;float floatN = 6.12;

    cout

  • 19

    Advanced C programming

    20.07.2012 Janne Mntykoski 37

    String pointers#include

    void main(void){

    char stringC[11] = String";char *string_pointer;

    string_pointer = stringC + 6;printf(stringC = %s, stringC + 6 = %s\n", stringC, string_pointer);printf(Member?(alkio) 6 of stringC = %c\n", *string_pointer);

    stringC[3] = '\0printf(stringC = %s\n", stringC);

    stringC = stringC + 1;

    system(PAUSE);}

    20.07.2012 Janne Mntykoski 38

    Pointer to a memory location which contains character(s)

    Add 6*(size of character= 1 byte)

    '\0'-characters is the end of stringTherefore here is Str printed

    INCORRECT! stringC is constant

    Array name=stringC=address of the member 0 of array

  • 20

    Pointers#include int main(){

    int i = 5;int *ptr;float array[2] = {3.14, 0.07};float *ptr2;

    ptr = &i;printf(Value of i: %d, Value in address ptr: %d.\n", i, *ptr);printf(Address of i: %p, value of pointer ptr %p.\n", &i, ptr);

    ptr2= array;printf(Address of member 0 of array: %p, ptr2: %p.\n", array, ptr2);printf(Value of member 0 of array: %f. ptr2[0]: %f.\n", *array, ptr2[0]);

    ptr2 = ptr2 + 1; printf(Address of member 1 of array: %p, ptr2: %p.\n", array+1, ptr2);printf(Value of member 1 of array: %f. ptr2[0]: %f.\n", array[1], ptr2[0]);

    }

    20.07.2012 Janne Mntykoski 39

    Pointer to a memory location which contains an integer

    Pointer to a memory location which contains a float

    & is address operatori=*ptr, * is contents operator&i=ptr

    The same addressi=*ptr, * is contents operator

    *array=array[0]

    Add size of float= 4 bytes

    array[1]=ptr2[0]

    13.01.2006 Janne Mntykoski 40

    Pointer calculations#include int main(){

    int i = 5;int *ptr;int array[3] = {3, 2, 1};int *ptr2;

    *ptr++(*ptr)++

    x = *ptr;ptr++;

    }

    kasvattaa osoittimen arvoa kahdellakasvattaa osoittimen osoittaman muistipaikan sislt yhdell

    sallitut operaatiot ovat +, ++, - ja

    OR! x = *ptr++;

  • 21

    #include

    struct personStruct {char name[30];int age;

    };

    int main(void){

    struct personStruct person;int j;

    printf(Give name: ");fgets(person.name, 30, stdin);printf(Give age: ");scanf("%d", &(person.age));

    for (j=0; j < 30; j++)if (person.name[j] == '\n')

    person.name[j] = '\0';}

    Structure

    20.07.2012 Janne Mntykoski 41

    Read into field name in structure person

    Remove newline \n from the end of string

    Read into field age in structure person

    Structure type personType containsfields name and age

    #include

    typedef struct personStruct {char name[30];int age;

    } personType;

    int main(void){

    personType persons[2] = {{"Untamo",1},{"Juusto", 0}};personType *personsPtr;

    personsPtr = persons;

    printf(Member 0: name: %s, age: %d\n", persons[0].name, persons[0].age);printf(Member 0: name: %s, age: %d\n", personsPtr->name, personsPtr->age);

    personsPtr++;printf(Member 1: name: %s, age: %d\n", personsPtr[0].name, personsPtr[0].age);printf(Member 1: name: %s, age: %d\n", personsPtr->name, personsPtr->age);

    }

    Array of structures

    20.07.2012 Janne Mntykoski 42

    InitializeStructure pointer

    Move to the next structure

    Could be omitted, default=size of initialization

    Type definition

  • 22

    #include #include void main(){

    char *words[3][2]= {{"sana","word"},{"peli","game"},{"talo","house"}};char word[30];int i;

    printf(Give word: ");fgets(word, 30, stdin);for (i=0; i < 30; i++)

    if (word[i] == '\n')word[i] = '\0';

    for (i=0; i

  • 23

    ?Output file

    20.07.2012 Janne Mntykoski 45

    C C++#include ???

    int main(){

    FILE *outputfile;outputfile=fopen(output.txt,w); //a?if (outputfile == NULL) {

    printf(File open failed!);return 2;

    }

    char stringC[80];

    printf(Give string: ");fgets(stringC, 30, stdin);fputs(stringC, outputfile);fputs(Hi, outputfile);fclose(outputfile);

    }

    #include #include using namespace std;

    int main(void){

    ofstream outputfile(output.txt");if (!outputfile) {

    cout

  • 24

    13.01.2006 Janne Mntykoski 47

    Bit fields In struct ja union you can define the number of

    bits used Field has to be of type int or unsigned struct bit_card {

    unsigned nro:4; /* 4 bits */unsigned country:2; /* 2 bits */unsigned color:1; /* 1 bit */

    };

    #include

    typedef enum {START, SUCCESS} state_t;Int main(){

    int c;state_t current_state = START, next_state = START;

    while(1) {switch(current_state){

    case START :next_state = SUCCESS;break;

    case SUCCESS :printf(Program terminated.\n"); getch(); return;

    }current_state=next_state;

    }}

    Enumerated type

    20.07.2012 Janne Mntykoski 48

    State variables

    START=0, SUCCESS=1

    State machine

    STATE_START

    STATE_SUCCESS

  • 25

    13.01.2006 Janne Mntykoski 49

    Dynamic memory allocation

    Memory is allocated and freed during run-time

    Function malloc() reserves memory Function free() releases the reserved

    memory They are in stdlib.h library

    Other additions to C++

    06.01.2008 Janne Mntykoski 50

  • 26

    06.01.2008 Janne Mntykoski 51

    Other additions to C++

    Classes: (Simula67) Operator overloading

    Others: Type bool. Has two values: false and true. Dynamic type conversions of the variables Inline functions Dynamic memory allocation (new, delete)

    19.07.2012 Janne Mntykoski 52

    Advanced I/OC++ code#include main(){// muutetaan formaattiacout

  • 27

    ?Output format

    19.07.2012 Janne Mntykoski 53

    C C++ Output

    printf(%f\n,123.234567);printf(%s\n, "hello);

    cout