06 class basics cont

Upload: nguyen-phu-tai

Post on 10-Apr-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 06 Class Basics Cont

    1/55

    SESSION 6 CLASS BASICS

    CONTDDEEP COPIESCUSTOM IOSTREAMOPERATORSCONVERSION OPERATORS

  • 8/8/2019 06 Class Basics Cont

    2/55

    Event Loops - ( WS5 )

    WinMain WinMain(){(){ while(!done){ while(!done){

    if(R) // user pressed Rif(R) // user pressed Rif(S) // user pressed Sif(S) // user pressed Sif(L)if(L) [other keys] [other keys] [other mouse clicks] [other mouse clicks]if(Clicked close){if(Clicked close){

    done = true;done = true;}}

    }}

  • 8/8/2019 06 Class Basics Cont

    3/55

    C ommand line main() function

    intint main(){ main(){

    step1();step1();step2();step2();step3();step3();coutcout

  • 8/8/2019 06 Class Basics Cont

    4/55

    D etecting Keyboard Events ( WS5 )

    b ool sp; // S Pressed?

    if (keys['S'] && !sp ) {sp = TRUE; // pressing the S key [game code goes here]

    }if (!keys['S']){

    sp = FALSE; // not pressing the S key}

  • 8/8/2019 06 Class Basics Cont

    5/55

  • 8/8/2019 06 Class Basics Cont

    6/55

    D etecting Keyboard Events ( WS5 )

    b ool sp; // S Pressed?

    if (keys['S'] && !sp ) {sp = TRUE; // pressing the S key [game code goes here]

    }if (!keys['S']){

    sp = FALSE; // not pressing the S key}

  • 8/8/2019 06 Class Basics Cont

    7/55

    =(shallow copy)

    Shallow copies copy the ADDRESS of pointersbut they dont copy the object they point TO.

  • 8/8/2019 06 Class Basics Cont

    8/55

    (deep copy)

    =

    =Deep copies make copies of each data object

    instead of just copying pointers to data objects.

  • 8/8/2019 06 Class Basics Cont

    9/55

    If you want to do deep copies , you need to writea copy constructor .

    Order:: Order( Order& source) {

    // new ISBN o bj ectthis->is b n = ISBN(source.is b n);ordered = source.ordered;this->delivered = source.delivered;

    // You dont have to say this}

  • 8/8/2019 06 Class Basics Cont

    10/55

    If you want to do deep copies , you need to write a

    copy constructor and an assignment operator.

    Order:: Order( Order& source) {

    // new ISBN o bj ectthis->is b n = ISBN(source.is b n);ordered = source.ordered;this->delivered = source.delivered;

    // You dont have to say this}

  • 8/8/2019 06 Class Basics Cont

    11/55

    If you want to do deep copies , you need to write acopy constructor and an assignment operator.

    Order::operator= ( Order& rhs) {// new ISBN o bj ectthis->is b n = ISBN(rhs.is b n);this->ordered = rhs.ordered;

    this->delivered = rhs.delivered;}

  • 8/8/2019 06 Class Basics Cont

    12/55

  • 8/8/2019 06 Class Basics Cont

    13/55

    Resources

    Resources are stored outside the memoryallocated to an object.

    Instance variables that refer to resources(resource instance variables ) include pointersto

    dynamic arrays in freestore memory, andfile structures

  • 8/8/2019 06 Class Basics Cont

    14/55

    Resource instance variables example

    a pointer !a pointer !

  • 8/8/2019 06 Class Basics Cont

    15/55

    Copying

    If we were to make a shallow copy of a Studentobject, the original and the copy would point to thesame resource: g rade pointer

    If any changes the grades in the copy, the originalreferred to the changed grades and no longer to theoriginal grades.

    This behavior is not what we normally expectThis behavior is not what we normally expectfrom a copy.from a copy.

  • 8/8/2019 06 Class Basics Cont

    16/55

    Copying

    For each resource variable, we obtain a pointer to anew resource and copy the original into thatresource.To enable deep copying, we overwrite the compiler

    defaults for two member functions:the copy constructor andthe assignment operator

    If we do not define a copy constructor, the compilerIf we do not define a copy constructor, the compilerinserts one that makes a shallow copy.inserts one that makes a shallow copy. If we do notIf we do notdefine an assignment operator, the compiler insertsdefine an assignment operator, the compiler inserts

    one that performs a shallow assignment.one that performs a shallow assignment.

  • 8/8/2019 06 Class Basics Cont

    17/55

    Copy Constructor

    The copy constructor copies information froman existing object to a newly created object.

    The compiler calls this constructor wheneveran object is

    initialized,passed by value to a function parameter, orreturned by value from a function

  • 8/8/2019 06 Class Basics Cont

    18/55

    Copy Constructor

    A copy constructor declaration:Identifier ( const Identifier& );

    Identifier is the class name.

    In the definition of thecopy constructor, we

    perform a shallow copy of the non-resource instancevariables,allocate fresh freestore memory for the resourceinstance variable(s), andcopy data pointed to by the original object to thefreshly allocated memory pointed to by the newobject.

  • 8/8/2019 06 Class Basics Cont

    19/55

    Assignment OperatorAn assignment operator copies data from an existing objectinto an existing object.Identifier& operator=(const Identifier&);(Identifier: is the name of the class of the right operand)

    In the definition, we: check for self-assignment deallocate previously allocated freestore memory allocate new freestore memory

    copy resource source data to freshly allocated memory copy non-resource instance variables to destination

    variables

  • 8/8/2019 06 Class Basics Cont

    20/55

    N o Copies Allowed

    If you want to make it impossible forother people to write code that makes

    copies of your object, write a copyconstructor and an assignment

    operator and make them private.

  • 8/8/2019 06 Class Basics Cont

    21/55

    Custom iostream Operators

    intint main () { main () {

    ISBNISBN foofoo = ISBN(9330440556);= ISBN(9330440556);

    // How does// How does coutcout know what to do withknow what to do with// our ISBN o bj ect// our ISBN o bj ect foofoo? ?

    coutcout

  • 8/8/2019 06 Class Basics Cont

    22/55

    Custom iostream Operators

    An object can interact with input and outputstreams in the same way that primitive data

    types interact.The istream and ostream classes of theiostream library support object-oriented inputand output.

  • 8/8/2019 06 Class Basics Cont

    23/55

    Custom iostream Operators

    W e extend the functionality of the extraction(>>) and the insertion (

  • 8/8/2019 06 Class Basics Cont

    24/55

    O verloading the

  • 8/8/2019 06 Class Basics Cont

    25/55

    O verloading the

  • 8/8/2019 06 Class Basics Cont

    26/55

    O verloading the

  • 8/8/2019 06 Class Basics Cont

    27/55

    Cascading

    C ascading is the concatenation of severalvariables in a single statement interspersed

    with the appropriate operator.The insertion and extraction operators areoverloaded in the istream and ostreamclasses so as to enable cascading.

  • 8/8/2019 06 Class Basics Cont

    28/55

    Cascading

    Card a, b , c, d, e;

    // how does the + operator// do this:a = b + c + d + e;

  • 8/8/2019 06 Class Basics Cont

    29/55

    W e need 2 operators:

    // This one is for the first pair:O perator+(Card L, Card R);

    // This one is for the second,

    third, etc.O perator+(int , Card R);

  • 8/8/2019 06 Class Basics Cont

    30/55

    O verloading the + operator

    intint operator+(operator+( intint lhslhs ,Card ,Card & &rhsrhs ) {) {return lhs +return lhs + valToInt valToInt(rhs.val);(rhs.val);

    }}

  • 8/8/2019 06 Class Basics Cont

    31/55

    intint main () { main () {Card a ('A', 's');Card a ('A', 's');

    Card b ('K', 'd');Card b ('K', 'd');Card c ('3', 'h');Card c ('3', 'h');Card d ('9', 's');Card d ('9', 's');intint foofoo; ;

    foofoo = a + b + c + d; //= a + b + c + d; // foo foo = 33= 33}}

    intint operator+(operator+( intint lhslhs ,Card ,Card & &rhsrhs ) {) {return lhs +return lhs + valToInt valToInt(rhs.val);(rhs.val);

    }}

  • 8/8/2019 06 Class Basics Cont

    32/55

    Returning A Reference

    Returning a reference from a function has twointrinsic benefits:

    efficiencycreates an lvalue

    Returning a reference copies a singleaddress. ( Returning the value at that address

    may involve copying many instance variables,possibly even deep copying, which is much moretime consuming.)

  • 8/8/2019 06 Class Basics Cont

    33/55

    O verloading the

  • 8/8/2019 06 Class Basics Cont

    34/55

    Student no b ita(13443,BDCDF);Student doraemon(33333,AABAD);

    cout

  • 8/8/2019 06 Class Basics Cont

    35/55

    lvalue Creation

    The term lvalue originates in the description of anassignment expression.An assignment expression consists of a left operand, theassignment operator and a right operand. The leftoperand must occupy some memory location where thevalue of the right operand may be stored. The leftoperand cannot be a constant or a temporary expression.Examples of lvalues include:

    variables

    objectsarray elementsfunctions that return references

  • 8/8/2019 06 Class Basics Cont

    36/55

    D angling References

    Returning a reference to a local variable or aparameter received by value (these go out of

    scope when the function returns control to itscaller) is called a dangling reference.

  • 8/8/2019 06 Class Basics Cont

    37/55

    Variable Scope : a function that does

    nothingvoid void doNothingdoNothing () { () {

    intint a, b , c;a, b , c;a = 5; b = 6, c = 10;a = 5; b = 6, c = 10;intint d = a * b * c;d = a * b * c;// when the function closes a, b ,// when the function closes a, b ,

    c, and d getc, and d get ~deleted ~deleted ..}}

  • 8/8/2019 06 Class Basics Cont

    38/55

    Variable Scope: D angling References

    Card *Card * addCardsaddCards(Card a, Card b , Card)(Card a, Card b , Card){{

    Card c;Card c;c = a + b ;c = a + b ;return &c; // this doesnt workreturn &c; // this doesnt work

    // b ecause c gets deleted // b ecause c gets deleted

    // after the function closes// after the function closes}}

  • 8/8/2019 06 Class Basics Cont

    39/55

    Variable Scope: no dangling reference

    void void addCardsaddCards(Card a,(Card a,Card b ,Card b , Card * cCard * c ) {) {

    *c = a + b ;*c = a + b ;return c;return c; // this works// this works// it works b ecause c comes from // it works b ecause c comes from

    // outside the function,// outside the function,// so it doesnt get deleted // so it doesnt get deleted // when the function closes.// when the function closes.

    }}

  • 8/8/2019 06 Class Basics Cont

    40/55

    String Input overflow

    charchar foofoo [10];[10];intint b ar = 5; b ar = 5;

    cincin >> >> foofoo; // user types 13 chars; // user types 13 chars

    coutcout

  • 8/8/2019 06 Class Basics Cont

    41/55

    String Input overflow

    The SolutionT he string class addresses this indefinite-sizeproblem. An object of the string class accepts asmany characters as the user enters and allocatesas much memory as is needed to store the set of characters.T he string class requires #include for theprototypes.

  • 8/8/2019 06 Class Basics Cont

    42/55

    String Input overflow

    istream& getline(istream&, string&, char);

    The string class has two member functions for

    translating strings into null-terminated C -stylestrings:length() - the number of characters in the stringc_str() - the address of the null-terminated C -styleversion of the string.

  • 8/8/2019 06 Class Basics Cont

    43/55

    String C lass Example

    # include # include

    intint main( ) { main( ) {stringstring str str; ;getlinegetline( (cincin, , strstr); );

    }}

  • 8/8/2019 06 Class Basics Cont

    44/55

    Conversion Operators

    Sometimes we need to convert an object of oneclass to an object of another data type.

    Student::operatorStudent::operator int int() const{() const{return no;return no;

    }}

  • 8/8/2019 06 Class Basics Cont

    45/55

    Student::operatorStudent::operator int int() const{() const{return no;return no;

    }}

    intint main() { main() {

    intint n;n;StudentStudent hanshans(1234, ABABF);(1234, ABABF);

    n =n = hanshans; //convert Student to; //convert Student to int int

    coutcout

  • 8/8/2019 06 Class Basics Cont

    46/55

    D erived D ata Type Conversions

  • 8/8/2019 06 Class Basics Cont

    47/55

    D esign Considerations

    C onversion operators should be usedsparingly and their implementations kepttrivial.

    Too many conversion operators make yourcode difficult to read.

  • 8/8/2019 06 Class Basics Cont

    48/55

    Single-Argument Constructors

    Conversion operators define implicit conversionsfrom the data type of the current object to

    another data type.

    To define a conversion from a data type to thedata type of the current object, we use single-

    argument constructors.

  • 8/8/2019 06 Class Basics Cont

    49/55

    class Student {class Student {

    pu b lic: pu b lic:Student();Student();Student(Student(int int); );

    set(set(int int no, char grades);no, char grades);};};

    Student::Student(Student::Student(int int no) {no) {set(no, "");set(no, "");

    } // single argument constructor} // single argument constructor

  • 8/8/2019 06 Class Basics Cont

    50/55

    Student::Student(Student::Student(int int no) {no) {set(no, "");set(no, "");

    } // single argument constructor} // single argument constructor

    // convert// convert intint toto StudentStudentStudent harryStudent harry == 1234;1234;

    coutcout

  • 8/8/2019 06 Class Basics Cont

    51/55

    H ow does the compiler know what to dowhen it sees this:

    Student harryStudent harry == 1234;1234;

    ?

  • 8/8/2019 06 Class Basics Cont

    52/55

    Conversion Sequence

    In searching for a conversion the compiler stepsthrough definite stages. The compiler looks for

    an exact match (for example, int to int , Student toStudent ),a promoted match (for example, char to int , float todouble ),a standard conversion match (for example, int todouble, int to float ),a derived data type conversion match (for example,int to Student ). ( T his is the one it uses for theexample shown above.)

    Student harry = 1234; // ??Student harry = 1234; // ??

  • 8/8/2019 06 Class Basics Cont

    53/55

    Explicit Constructors

    To suppress implicit conversions by a single-argument constructor, we qualify the constructor asexplicitexplicit ClassIdentifier(dataType);

    For an explicit single-argument constructor, we

    need to writeharry = Student(1234);instead of

    harry = 1234;

  • 8/8/2019 06 Class Basics Cont

    54/55

    explicitexplicit Student::Student(Student::Student(int int no) {no) {set(no, "");set(no, "");

    }}

    // doesnt work// doesnt work

    Student harry = 1234;Student harry = 1234;

    // works// worksStudent harry = Student(1234);Student harry = Student(1234);

    W hy would we want to use explicit?W hy would we want to use explicit?

  • 8/8/2019 06 Class Basics Cont

    55/55

    ??