intro_c_cpp lesson 9 fall_10

Upload: udo3

Post on 07-Apr-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    1/22

    Introd to C/C++(Section 2) Week 9 1

    Introduction to C/C++

    Yedidiah Solowiejczyk

    Week 9

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    2/22

    Introd to C/C++(Section 2) Week 9 2

    Sy nopsisReview of Classes in C++

    Declaring classesInitializing class member variablesPublic vs. private member functionsConstructors & DestructorsInheritancePol ymorphism

    Virtual Member Functions Overriding Member Functions

    Standard Libraries math.h, stdlib.h, etc

    More on Exotic Pointers. Link Lists Binar y Trees Binar y Search

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    3/22

    Introd to C/C++(Section 2) Week 9 3

    A Brief Histor y of C++

    C++ Programming 1980 Stroustrop at Bell Labs extended the C

    programming language to include the concept of class combining data with the respective functions that

    manipulate the data Object-Oriented Programming (OOP)

    Encapsulation Strong data typing

    Inheritance Reusability

    Polymorphism Run-time functionality

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    4/22

    Introd to C/C++(Section 2) Week 9 4

    Object Oriented Programming

    Encapsulation The abilit y to define new data t ypes and set of

    operations ( functions) governing the new t ype

    Inheritance class derivation The abilit y to create new t ypes that inherit properties

    from exiting t ypes

    Pol ymorphism The abilit y of objects that belong to related classes to

    respond differentl y to the same operationVirtual functions

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    5/22

    Introd to C/C++(Section 2) Week 9 5

    C programming vs. Object Oriented Programming

    C programming Structured Language

    Decomposition of task into procedures(functions)

    Data is handled separatefrom procedures Prone to errors becauseof separation betweendata and functions

    C++ OOP Language

    Builds strong link between the datastructures and the

    methods that manipulatethe data Think of objects & their

    behavior Mammals Persons

    Mobile phones Satellite vehicles Geometric Shapes

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    6/22

    Introd to C/C++(Section 2) Week 9 6

    Classes in C++Structure

    collection of variables of differenttypes

    contained within a name (tag)

    Class collection of ( member ) variables of

    different t ypes combined with a set of related

    (member) functions

    contained within a name (tag)

    Classes encapsulate the data and functions

    into one collection the object .

    Encapsulation makes programming and

    maintenance easier Ever ything is one place C++ imposes a built in discipline

    Example

    class cat // template of an object{private: // protected area

    unsigned int A ge; // data membersunsigned int Weight;

    public:// member function

    void Meow( );

    };// member function declarationvoid Meow( void);int main( ){

    cat X; //instantiate ( object ) XX.Meow; //invoke methodX.A ge = 5; //forbidden private

    }void Cat::Meow( ) // class definition{ cout

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    7/22

    Introd to C/C++(Section 2) Week 9 7

    Class SkeletonPrivate member data members protect data in class from being

    erroneousl y modified from theoutside the class Privatize data members

    Public member functions Socialize (make public)

    member functions allow access to private parts via

    built-in functions ( publicaccessor ) Ever y public member function

    has access to the private datamembers

    Member function definition use scoping operator :: int cat::get A ge( )

    {::::::::

    }

    Exampleclass cat // class declaration or protot ype{

    // private: - b y defaultint A ge;int Weight;

    public: // public member functionsvoid set A ge(int x){ A ge = x;} //inlinevoid setWeight(int y){Weight = y;}int get A ge(){return A ge;}int getWeight();void Meow();

    };int main (){

    cat X;int temp;X.set A ge(6);X.setWeight(20);temp = X.get A ge( );temp = X.getWeight( );

    }// access thru scoping operator ::int cat::getWeight() {return Weight;}void cat::setWeight(int W){weight = W;}

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    8/22

    Introd to C/C++(Section 2) Week 9 8

    ConstructorsConstructors

    Constructor - is unique member functionthat is used for initializing the datamembers of a class

    Constructors can take parameter s but itis not mandatory

    Constructors cannot return a value even void

    Constructor has the same name as class Default constructors if you do notdeclare a constructor the compiler willprovide one automaticallyConstructors declarations cat::cat(int age, int weight); cat::cat(int age); cat::cat( ) default constructor

    If you provide a constructor then default constructor will not be provided automatically by compiler you should create your own

    Exampleclass Cat // protot ype (declaration){private:

    int A ge, Weight, Id;public:// constructors

    Cat(int age, int weight, int id);Cat( );// default constructor

    // member functionsint get A ge(){return A ge};

    int getWeight() (){return Weight}; //inline fnctvoid Meow();

    };int main(){

    Cat X(5,20,35); //constructorsCat Y;

    }Cat::Cat(int age, int weight, int id) //definitions

    { A ge = age;Weight = weight;Id = id;

    }Cat::Cat( ) // default constructor{A ge = 0; Weight = 0; Id = 0;}

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    9/22

    Introd to C/C++(Section 2) Week 9 9

    Destructors Destructor - is a unique member function cleans up after object goes

    out scope de-allocates memory Destructors have always the name of the class

    Destructors are always preceded with~

    Destructor never take argumentsDestructors never return a value

    Destructor declarationcat::~cat(){ } // takes no actionThere is onl y one destructorIf you do not provide adestructor, the compiler will

    provide one

    class Cat // protot ype (declaration){private:

    int A ge, Weight, Id;public:

    Cat(int age, int weight, int id); // constructorsCat( );// default constructor~Cat( ); //destructorint get A ge(); //other member functionsint getWeight();

    void Meow();};int main(){

    Cat X(5,20,35);Cat Y;

    }Cat::Cat(int age, int weight, int id) //definitions

    {A ge = age;Weight = weight;Id = id;

    } // default constructorCat::Cat( ) {A ge = 0; Weight = 0; Id = 0;}Cat::~Cat( ){ cout

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    10/22

    Introd to C/C++(Section 2) Week 9 10

    Friend FunctionsF riend member function doesexactl y what other memberfunctions except that it hasaccess to private members of oneor more classes

    class tax; // announcement

    class customer { int cost_item;

    public:customer(){balance = 0;}

    friend void PRINT(customer x, tax y);

    }

    class tax { int rate;

    public:tax( ){rate = 0;}

    friend void PRINT(customer x, tax y);

    };void PRINT(customer x, tax y){

    cout

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    11/22

    Introd to C/C++(Section 2) Week 9 11

    Inheritance A class that adds new functionality to

    an existing class is said to be derived from the original ( base ) class

    A class inherits from its base classmany of its attributes

    Single inheritance derived from asingle class

    class A ;class B: public A

    Multiple inheritance derived fromtwo or more classes

    class A ;

    class B;class C: public A , public B; //Inheritance is-a relationship

    Single Inheritance

    Shape Attributes

    int X;Int Y;

    Square Rectangle

    CirclePoint Center(5);

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    12/22

    Introd to C/C++(Section 2) Week 9 12

    InheritanceClass inheritance allowsmembers of one class to be usedas if the y were members of asecond class

    A derived class can inherit from

    its base class in three wa ys: public private protectedExamples class Student:public Person;

    class Y:private X; class A :protected B ;

    A class can contain three t ypes of members: public

    Visible outside the class

    private Accessible only thru public

    member functions

    protectedA ccessible onl y thru publicmember functionsProtected data & functions are

    fully visible to derived classes

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    13/22

    Introd to C/C++(Section 2) Week 9 13

    InheritanceInheritance

    Publicmemb

    Privatememb

    Protectedmemb

    public Public Private Protected

    private Private Private Private

    protected Protected Private Protected

    m e mb ers

    INHER

    ITs

    ACCE

    Ss

    A pu b lic m e mb er is accessi b leto a pu b licly derived class

    A private m e mb er is notaccessi b le to derived classes

    A protected m e mb er function arefully visi b le to derived classes b ut

    otherwise private

    Inheritance Li m itationsThe following

    operations are notinherited

    ConstructorsDestructorsOverloaded operators

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    14/22

    Introd to C/C++(Section 2) Week 9 14

    Inheritance If a base class and a derived class

    have identical named publicfunctions with the same signature , invoking the function in the derivedclass overrides the base function

    Exampleclass Shape {public :void setColor(int new_color);void move(int x, int y);void Print( ){cout

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    15/22

    Introd to C/C++(Section 2) Week 9 15

    Virtual Functions#define PI 3.14159class Shape {public:void setColor(int new_color);void move(int x, int y);virtual float area( ){return -1;}virtual float perim( ){return -1;}//constructors//destructorsprivate:int x, y; //center of shape};class Circle:public Shape { //derivedprivate:int r;public:virtual float area( ){ return (PI*r*r);}};

    class Rectangle:public Shape{//derivedprivate:int u, v;public:virtual float area( ){ return (u*v);}virtual float perim( ){retrun (2*u + 2*v;}};int main(){

    Shape *p; // pointer to shapeCircle c;Rectangle r;int flag = 1;

    if( flag ==1 )p = &c; //point to circle

    elsep = &r; //point to rectangle

    p->area( ); //get area ????

    }

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    16/22

    Introd to C/C++(Section 2) Week 9 16

    Standard Libraries

    C STANDARD LIBRARYContains function prototypes, type and m acro definitions

    #include - character handling #include - error handling

    #include - string handlingint strlen(char *s1), int strc m p(char *s1, *char *s2), etc #include - big and small numbers

    INT_MAX 32767, INT_MIN -32767

    #include - catch all

    Random # generator #include - date and time #include - sin, cos, tan, etc

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    17/22

    Introd to C/C++(Section 2) Week 9 17

    Random Number Generators#include

    #include //contains the function prototype for rand( )

    int main( ){

    int i , seed; printf("Enter random number seed prime

    #\n");scanf("%d" , &seed);

    srand(seed); // init random numbergeneratoor

    for(i = 0; i < 5; i++) printf("%12d" , rand( ));

    printf("\n ------- Normalized Random Numbers ----\n");for(i = 0; i < 5; i++)

    printf("%12d" , rand( )/32767 );

    printf("\n");

    }

    [solowiejczyk@sweng191 Jed]$ !mamake Randomcc Random.c -o Random[solowiejczyk@sweng191 Jed]$ ./RandomEnter random number seed prime #11804289383 846930886 1681692777 1714636915 1957747793

    ------- Normalized Random Numbers ----12947 21969 50348 18204 36306

    [solowiejczyk@sweng191 Jed]$ ./RandomEnter random number seed prime #31205554746 483147985 844158168 953350440 612121425

    ------- Normalized Random Numbers ----9488 36934 56669 58682 15126

    [solowiejczyk@sweng191 Jed]$ ./RandomEnter random number seed prime #171227918265 3978157 263514239 1969574147 1833982879

    ------- Normalized Random Numbers ----14913 7070 31857 43387 59267

    [solowiejczyk@sweng191 Jed]$

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    18/22

    Introd to C/C++(Section 2) Week 9 18

    TemplatesTemplates are patterns from whichclasses can be created

    ExampleTemplate class A rra y{public:

    A rra y(int Size); // constructor~ A rra y( ){delete [ ] A rra y _ptr ;}

    int get Size(){return size;}private:

    int size;Type *A rra y _ptr;

    };A rra y:: A rra y(int Size){

    size = Size;A rra y _ptr = new Type [size]; //Heap

    }

    int main(){

    Array A[4]; //array 4 intsArray F[12];

    {Array C[32];

    }//destro y C after going out of scope}

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    19/22

    Linked Listlinked list - is a data structure that consists of a sequenceof data records such that in each record there is a field thatcontains a reference (i.e. , a l ink ) to the next record in thesequence.

    The principal benefit of a linked list over a conventional array is thatthe order of the linked items may be different from the order that thedata items are stored in memory or on disk. For that reason , linked listsallow insertion and removal of nodes at any point in the list , with aconstant number of operations.

    On the other hand , linked lists by themselves do not allow randomaccess to the data , or any form of efficient indexing. Thus , many basicoperations such as obtaining the last node of the list , or finding anode that contains a given datum , or locating the place where a newnode should be inserted may require scanning most of the listelements.

    Introd to C/C++(Section 2) Week 9 19

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    20/22

    Introd to C/C++(Section 2) Week 9 20

    Linked Listsstruct node {int value;struct node *next;};

    struct node X1, X2,X3, X4;strcut node *temp;X1.value = 5;X1.next = &X2;X2.value = 6;X2.next = &X3X3.value= 7;X3.next = NULL

    X1 X2 X3

    value valuevalue NULL

    X4

    value

    Link Lists are used when you need to maintain a disorganized listof items that can be dynamically allocated and de-allocatedExample: Modeling communications center receiving & dropping random calls

    temp.next = X1.nextX1.next = &X4;X4.next = temp.nextX4.value = 12;

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    21/22

    Introd to C/C++(Section 2) Week 9 21

    Binar y Tree Structures

    Binar y tree is a data structure in

    which each node has at mosttwo children

    struct node {char fruit[32];char descri b er[128];struct node *left;struct node *right;};

    Searches are quick~ log 2(N) fast rather than N

    lemon

    date pear

    grape orange quince berry

  • 8/6/2019 Intro_C_CPP Lesson 9 Fall_10

    22/22

    Binar y Search Problem: Given an sorted list of values (names) ,

    what is average # searches that are necessary tofind a random value (name)?Linear Search - probing each name in the list , willtake on the average N/2 comparisons

    Binary Search algorithm is implemented by jumping to middle of array and testing target namevs. array name (equal , smaller , larger)

    Algorithm requires log 2 (N) vs. O(N) e.g. log 2 (1024) ~ 10 attempts vs. O( 1024/2 )

    Introd to C/C++(Section 2) Week 9 22

    Benson |Doe | Frank ||Julian| **|Oscar |** | Zorba