Classes in c++

73
CSC212 Dt St t CSC212 Dt St t Data Structure - Section AB Data Structure - Section AB Section AB Section AB Lecture 2 Lecture 2 ADT and C++ Classes (I) ADT and C++ Classes (I) ADT and C++ Classes (I) ADT and C++ Classes (I) Instructor: Instructor: Hao Tang Hao Tang Department of Computer Science Department of Computer Science 1 City College of New York City College of New York

description

Classes in c++ Classes in c++ Classes in c++

Transcript of Classes in c++

  • CSC212 D t St tCSC212 D t St tData Structure - Section ABData Structure - Section ABSection ABSection AB

    Lecture 2Lecture 2ADT and C++ Classes (I)ADT and C++ Classes (I)ADT and C++ Classes (I)ADT and C++ Classes (I)

    Instructor: Instructor: Hao TangHao TangDepartment of Computer Science Department of Computer Science

    11

    p pp pCity College of New YorkCity College of New York

  • OutlineOutlineOutlineOutline

    A Review of C++ Classes (Lecture 2)A Review of C++ Classes (Lecture 2) OOP, ADTs and ClassesOOP, ADTs and Classes,, Class Definition, Implementation and UseClass Definition, Implementation and Use Constructors and Value SemanticsConstructors and Value SemanticsMore on Classes (Lecture 3)More on Classes (Lecture 3) Namespace and DocumentationNamespace and Documentation Namespace and DocumentationNamespace and Documentation Classes and ParametersClasses and Parameters Operator OverloadingOperator Overloading

    22

    Operator OverloadingOperator Overloading

  • Object Oriented ProgrammingObject Oriented ProgrammingObject Oriented ProgrammingObject Oriented Programming

    Chapter 2 introduces Object Oriented Programming.Chapter 2 introduces Object Oriented Programming.

    OOP is the typical approach to programming which OOP is the typical approach to programming which supports the creation of new data types and operations supports the creation of new data types and operations to manipulate those types.to manipulate those types.

    This lecture gives a review of C++ Classes and This lecture gives a review of C++ Classes and introduces ADTs.introduces ADTs.

    33

  • C++ Classes and ADTsC++ Classes and ADTsC++ Classes and ADTsC++ Classes and ADTs

    ClassClassMechanism to create objects and member Mechanism to create objects and member

    functionsfunctionsSupport information hidingSupport information hiding

    Abstract Abstract Data Data Types (ADTs)Types (ADTs) mathematical data typemathematical data typeClass as an ADT that programmers can use Class as an ADT that programmers can use

    without knowing how the member functions are without knowing how the member functions are implementedimplemented -- i e with information hidingi e with information hiding

    44

    implemented implemented -- i.e. with information hidingi.e. with information hiding

  • A point ADTA point ADTA point ADTA point ADT

    A data type to store A data type to store and manipulate a and manipulate a 2 2

    yy

    single point on a planesingle point on a plane ManipulationsManipulations xx

    1 1

    0 0

    p1p1

    InitializeInitialize RetrievalRetrieval

    ShiftShift 22 1 0 1 21 0 1 2

    --11

    -- 22 Shift Shift --2 2 --1 0 1 21 0 1 2

    55

  • A point ADTA point ADTA point ADTA point ADT

    A data type to store A data type to store and manipulate a and manipulate a 2 2

    yy

    single point on a planesingle point on a plane ManipulationsManipulations xx

    1 1

    0 0

    p1p1

    InitializeInitialize Retrieval coordinatesRetrieval coordinates

    ShiftShift 22 1 0 1 21 0 1 2

    --11

    -- 22

    ((--1, 0.8)1, 0.8)

    Shift Shift --2 2 --1 0 1 21 0 1 2

    66

  • A point ADTA point ADTA point ADTA point ADT

    A data type to store A data type to store and manipulate a and manipulate a 2 2

    yy

    single point on a planesingle point on a plane ManipulationsManipulations xx

    1 1

    0 0 0.80.8p1p1

    InitializeInitialize Retrieval coordinatesRetrieval coordinates

    ShiftShift 22 1 0 1 21 0 1 2

    --11

    -- 22 Shift Shift --2 2 --1 0 1 21 0 1 2

    --1.01.0

    77

  • A point ADTA point ADTA point ADTA point ADT

    A data type to store A data type to store and manipulate a and manipulate a 2 2

    yy

    single point on a planesingle point on a plane ManipulationsManipulations xx

    1 1

    0 0

    p1p1

    InitializeInitialize Retrieval coordinatesRetrieval coordinates

    Shift bShift b 22 1 0 1 21 0 1 2

    --11

    -- 22(1 3(1 3 1 4)1 4)

    p2p2

    Shift byShift by --2 2 --1 0 1 21 0 1 2(0.3, (0.3, --0.6)0.6)

    (1.3, (1.3, --1.4)1.4)

    88

  • OutlineOutlineOutlineOutline

    A Review of C++ Classes (Lecture 2)A Review of C++ Classes (Lecture 2) OOP, ADTs and ClassesOOP, ADTs and Classes,, Class Class DefinitionDefinition, Implementation and Use, Implementation and Use Constructors and Value SemanticsConstructors and Value SemanticsMore on Classes (Lecture 3)More on Classes (Lecture 3) Namespace and DocumentationNamespace and Documentation Namespace and DocumentationNamespace and Documentation Classes and ParametersClasses and Parameters Operator OverloadingOperator Overloading

    99

    Operator OverloadingOperator Overloading

  • point Definitionpoint Definition xx2 2 1 1 0 0

    yy

    pp

    point Definitionpoint Definition--2 2 --1 0 1 21 0 1 2

    --11--22

    We can implement the We can implement the pointpoint object using a object using a

    class point {

    data type called a data type called a classclass.. . . .

    };

    D t f t thD t f t th

    1010

    Dont forget the Dont forget the semicolon at the endsemicolon at the end

  • point Definitionpoint Definition xx2 2 1 1 0 0

    yy

    pp

    point Definitionpoint Definition--2 2 --1 0 1 21 0 1 2

    --11--22

    The class will have The class will have two components called two components called

    class point {

    x and y. These x and y. These components are the x components are the x and coordinates ofand coordinates of

    . . .double x;double y;and y coordinates of and y coordinates of

    this point.this point. Using a class permitsUsing a class permits

    double y;

    }; Using a class permits Using a class permits

    two new features . . .two new features . . .

    1111

  • point Definitionpoint Definition xx2 2 1 1 0 0

    yy

    pp

    point Definitionpoint Definition--2 2 --1 0 1 21 0 1 2

    --11--22

    The two components The two components will be will be private private

    class point {

    member variablesmember variables. . This ensures that This ensures that nobod can directlnobod can directl

    . . .private:

    double x;nobody can directly nobody can directly access this access this information. Theinformation. The

    double x;double y;

    };information. The information. The only access is through only access is through functions that we functions that we

    1212

    provide for the class.provide for the class.

  • point Definitionpoint Definition xx2 2 1 1 0 0

    yy

    pp

    point Definitionpoint Definition--2 2 --1 0 1 21 0 1 2

    --11--22

    In a class, the In a class, the functions which functions which

    class point {

    manipulate the class manipulate the class are also listed.are also listed.

    public:. . .

    private:private:double x;double y;

    };};Prototypes for the Prototypes for the pointpointfunctions go here,functions go here,ft th dft th d blibli

    1313

    after the word after the word public:public:

  • point Definitionpoint Definition xx2 2 1 1 0 0

    yy

    pp

    point Definitionpoint Definition--2 2 --1 0 1 21 0 1 2

    --11--22

    In a class, the In a class, the functions which functions which

    class point{

    manipulate the class manipulate the class are also listed.are also listed.

    public:. . .

    private:private:double x;double y;

    };};Prototypes for the Prototypes for the pointpointmember functions member functions go go hh

    1414

    herehere

  • point Definitionpoint Definition xx2 2 1 1 0 0

    yy

    pp

    point Definitionpoint Definition--2 2 --1 0 1 21 0 1 2

    --11--22

    class point

    Our Our pointpoint has at least four member functions:has at least four member functions:p

    {public:

    void initialize(double init x double init y);void initialize(double init_x, double init_y);void shift(double dx, double dy);double get_x() const;double get_y( ) const;

    private:double x;

    1515

    ;double y;

    };

  • point Definitionpoint Definition xx2 2 1 1 0 0

    yy

    pp

    point Definitionpoint Definition--2 2 --1 0 1 21 0 1 2

    --11--22

    class point

    The keyword The keyword constconst appears after two prototypes:appears after two prototypes:

    class point {public:

    id i iti li (d bl i it d bl i it )void initialize(double init_x, double init_y);void shift(double dx, double dy);double get_x( ) const;double get_y( ) const;

    private:double x;

    1616

    double x;double y;

    };

  • Files for the point ADTFiles for the point ADT xx2 2 1 1 0 0

    yy

    pp

    Files for the point ADTFiles for the point ADT--2 2 --1 0 1 21 0 1 2

    --11--22

    The The pointpoint class definition, which class definition, which we have just seen, is placed with we have just seen, is placed with documentation in a file calleddocumentation in a file called Documentation:(P diti ddocumentation in a file called documentation in a file called point.hpoint.h, outlined here., outlined here.

    The implementations of the The implementations of the f b f i ill bf b f i ill b

    (Preconditions and Postconditions)

    four member functions will be four member functions will be placed in a separate file called placed in a separate file called point.cxxpoint.cxx, which we will examine , which we will examine

    Class definition:point class d fi iti hi h

    pp ,,in a few minutes.in a few minutes. definition which we have already seen

    1717

  • OutlineOutlineOutlineOutline

    A Review of C++ Classes (Lecture 2)A Review of C++ Classes (Lecture 2) OOP, ADTs and ClassesOOP, ADTs and Classes,, Class Class DefinitionDefinition, Implementation and , Implementation and UseUse Constructors and Value SemanticsConstructors and Value SemanticsMore on Classes (Lecture 3)More on Classes (Lecture 3) Namespace and DocumentationNamespace and Documentation Namespace and DocumentationNamespace and Documentation Classes and ParametersClasses and Parameters Operator OverloadingOperator Overloading

    1818

    Operator OverloadingOperator Overloading

  • Using the point ADTUsing the point ADT xx2 2 1 1 0 0

    yy

    pp

    Using the point ADTUsing the point ADT--2 2 --1 0 1 21 0 1 2

    --11--22

    A program that A program that wants to use the wants to use the pointpoint ADT mustADT must

    #include #include #include point h"pointpoint ADT must ADT must

    includeinclude the the point.h header point.h header

    #include point.h"

    ...ppfile (along with file (along with its other header its other header inclusions)inclusions)inclusions).inclusions).

    File File pointmain1.cxxpointmain1.cxx

    1919

    pp

  • Using the point ADTUsing the point ADT xx2 2 1 1 0 0

    yy

    pp

    Using the point ADTUsing the point ADT--2 2 --1 0 1 21 0 1 2

    --11--22

    Just for Just for illustration, the illustration, the

    #include #include #include point h"example program example program

    will declare two will declare two pointpoint ariablesariables

    #include point.h"

    int main( ){pointpoint variables variables

    named p1 and p2.named p1 and p2.{

    point p1;point p2;

    2020

  • Using the point ADTUsing the point ADT xx2 2 1 1 0 0

    yy

    pp

    Using the point ADTUsing the point ADT--2 2 --1 0 1 21 0 1 2

    --11--22

    Just for Just for illustration, the illustration, the

    #include #include #include point h"example program example program

    will declare two will declare two pointpoint objectsobjects

    #include point.h"

    int main( ) {pointpoint objectsobjects

    named p1 and p2.named p1 and p2.{

    point p1;point p2;

    2121

  • Using the point ADTUsing the point ADT xx2 2 1 1 0 0

    yy

    pp

    Using the point ADTUsing the point ADT--2 2 --1 0 1 21 0 1 2

    --11--22

    The program The program starts by starts by

    #include #include #include point h"calling the calling the

    initialize initialize member f nctionmember f nction

    #include point.h"

    int main( ) {member function member function

    for p1.for p1.{

    point p1;point p2;p1 initialize( 1 0 0 8);p1.initialize(-1.0, 0.8);

    2222

  • Using the point ADTUsing the point ADT xx2 2 1 1 0 0

    yy

    pp

    Using the point ADTUsing the point ADT--2 2 --1 0 1 21 0 1 2

    --11--22

    The program The program starts by starts by

    #include #include #include point h"activatingactivating the the

    initialize initialize member f nctionmember f nction

    #include point.h"

    int main( ) {member function member function

    for p1.for p1.{

    point p1;point p2;

    p1.initialize(-1.0, 0.8);

    2323

  • Using the point ADTUsing the point ADT xx2 2 1 1 0 0

    yy

    pp

    Using the point ADTUsing the point ADT--2 2 --1 0 1 21 0 1 2

    --11--22

    The member The member function function

    int main( )activation activation consists of four consists of four parts startingparts starting

    int main( ){

    point p1;point p2;parts, starting parts, starting

    with the object with the object name.name.

    point p2;

    p1.initialize(-1.0, 0.8);name.name.

    2424

  • Using the point ADTUsing the point ADT xx2 2 1 1 0 0

    yy

    pp

    Using the point ADTUsing the point ADT--2 2 --1 0 1 21 0 1 2

    --11--22

    The instance The instance (object) name is (object) name is

    int main( )followed by a followed by a period.period.

    int main( ) {

    point p1;point p2;point p2;

    p1.initialize(-1.0, 0.8);

    2525

  • Using the point ADTUsing the point ADT xx2 2 1 1 0 0

    yy

    pp

    Using the point ADTUsing the point ADT--2 2 --1 0 1 21 0 1 2

    --11--22

    After the period After the period is the name of is the name of

    int main( ) {the member the member function that you function that you are acti atingare acti ating

    int main( ) {point p1;point p2;

    are activating.are activating. p1.initialize(-1.0, 0.8);

    2626

  • Using the point ADTUsing the point ADT xx2 2 1 1 0 0

    yy

    pp

    Using the point ADTUsing the point ADT--2 2 --1 0 1 21 0 1 2

    --11--22

    Finally, the Finally, the arguments for arguments for the memberthe member int main( ) {the member the member function. In this function. In this example the first example the first

    int main( ) {point p1;point p2;pp

    argument (x argument (x coordinate) and coordinate) and the secondthe second

    p1.initialize(-1.0, 0.8);

    the second the second argument (y argument (y coordinate)coordinate)

    2727

  • A QuizA Quiz xx2 2 1 1 0 0

    yy

    pp

    A QuizA Quiz--2 2 --1 0 1 21 0 1 2

    --11--22

    How would you How would you activate p1's get_x activate p1's get_x member function ?member function ? int main( )member function ?member function ?

    What would be theWhat would be the

    int main( ) {

    point p1;point p2;What would be the What would be the

    output of p1's output of p1's get_x member get_x member function at thisfunction at this

    point p2;

    p1.initialize(-1.0, 0.8);function at this function at this point in the point in the program ?program ?

    2828

  • A QuizA Quiz xx2 2 1 1 0 0

    yy

    pp

    A QuizA Quiz--2 2 --1 0 1 21 0 1 2

    --11--22

    Notice that the Notice that the get_x get_x member function has member function has no argumentsno arguments int main( ) {no arguments.no arguments.

    At this pointAt this point

    int main( ) {point p1;point p2;

    At this point, At this point, activating activating p1.get_x p1.get_x will return a double will return a double

    p1.initialize(-1.0, 0.8);cout

  • A QuizA Quiz xx2 2 1 1 0 0

    yy

    pp

    A QuizA Quiz--2 2 --1 0 1 21 0 1 2

    --11--22

    Trace through this Trace through this program, and tell program, and tell me the completeme the complete

    int main( ) {

    point p1; me the complete me the complete output.output.

    point p1;point p2;

    p1.initialize(-1.0, 0.8); p ( )cout

  • A QuizA Quiz xx2 2 1 1 0 0

    yy

    pp

    A QuizA Quiz--2 2 --1 0 1 21 0 1 2

    --11--22

    --1.0 0.81.0 0.8--1.0 0.81.0 0.8

    int main( ) {

    point p1;0.3 0.3 --0.60.6

    point p1;point p2;

    p1.initialize(-1.0, 0.8); p ( )cout

  • What you know about ObjectsWhat you know about ObjectsWhat you know about ObjectsWhat you know about Objects

    Class = Data + Member Functions.Class = Data + Member Functions.You know how to You know how to definedefine a new class type, and place a new class type, and place yp , pyp , p

    the definition in a header file.the definition in a header file.You know how to You know how to useuse the header file in a program the header file in a program

    which declares instances of the class type.which declares instances of the class type.You know how to You know how to activateactivate member functions.member functions. But you still need to learn how to But you still need to learn how to writewrite the bodies of the bodies of

    a classs member functions.a classs member functions.

    3232

  • OutlineOutlineOutlineOutline

    A Review of C++ Classes (Lecture 2)A Review of C++ Classes (Lecture 2) OOP, ADTs and ClassesOOP, ADTs and Classes,, Class Class DefinitionDefinition, , ImplementationImplementation and and UseUse Constructors and Value SemanticsConstructors and Value SemanticsMore on Classes (Lecture 3)More on Classes (Lecture 3) Namespace and DocumentationNamespace and Documentation Namespace and DocumentationNamespace and Documentation Classes and ParametersClasses and Parameters Operator OverloadingOperator Overloading

    3333

    Operator OverloadingOperator Overloading

  • point Implementationpoint Implementation xx2 2 1 1 0 0

    yy

    pp

    point Implementationpoint Implementation--2 2 --1 0 1 21 0 1 2

    --11--22

    Remember that the member functions bodies Remember that the member functions bodies generally appear in a separate generally appear in a separate point.cxxpoint.cxx file.file.class pointclass point {public:

    void initialize(double init_x, double init_y);void shift(double dx, double dy);double get x( ) const;double get_x( ) const;double get_y( ) const;

    private:double x;

    3434

    double x;double y;

    };

  • point Implementationpoint Implementation xx2 2 1 1 0 0

    yy

    pp

    point Implementationpoint Implementation--2 2 --1 0 1 21 0 1 2

    --11--22

    We will look at the body of We will look at the body of intializeintialize, which must assign , which must assign its two arguments to the two private member variables.its two arguments to the two private member variables.class pointclass point {public:

    void initialize(double init_x, double init_y);void shift(double dx, double dy);double get x( ) const;double get_x( ) const;double get_y( ) const;

    private:double x;

    3535

    double x;double y;

    };

  • point Implementationpoint Implementation xx2 2 1 1 0 0

    yy

    pp

    point Implementationpoint Implementation--2 2 --1 0 1 21 0 1 2

    --11--22

    For the most part, the functions body is no different For the most part, the functions body is no different than any other function body.than any other function body.

    void point::initialize(double init_x, double init_y){{

    x = init_x;y = init_y;

    }

    3636

    But there are two special features about a But there are two special features about a member functions body . . .member functions body . . .

  • point Implementationpoint Implementation xx2 2 1 1 0 0

    yy

    pp

    point Implementationpoint Implementation--2 2 --1 0 1 21 0 1 2

    --11--22

    In the heading, the function's name is preceded by In the heading, the function's name is preceded by the class name and :: the class name and :: -- otherwise C++ won't realize otherwise C++ won't realize this is a classs member function.this is a classs member function.

    void point::initialize(double init_x, double init_y){

    i itx = init_x;y = init_y;

    }

    3737

  • point Implementationpoint Implementation xx2 2 1 1 0 0

    yy

    pp

    point Implementationpoint Implementation--2 2 --1 0 1 21 0 1 2

    --11--22

    Within the body of the function, the classs member Within the body of the function, the classs member variables and other member functions may all be variables and other member functions may all be yyaccessed.accessed.

    void point::initialize(double init_x, double init_y){

    i itx = init_x;y = init_y;

    }

    3838

  • point Implementationpoint Implementation xx2 2 1 1 0 0

    yy

    pp

    point Implementationpoint Implementation--2 2 --1 0 1 21 0 1 2

    --11--22

    Within the body of the function, the classs member Within the body of the function, the classs member variables and other member functions may all be variables and other member functions may all be yyaccessed.accessed.

    But, whose member i bl

    void point::initialize(double init_x, double init_y){

    i it

    variables are these? Are they

    p1 xx = init_x;y = init_y;

    }

    p1.xp1.yp2.x ?

    3939

    pp2.y

    ?

  • point Implementationpoint Implementation xx2 2 1 1 0 0

    yy

    pp

    point Implementationpoint Implementation--2 2 --1 0 1 21 0 1 2

    --11--22

    Within the body of the function, the classs member Within the body of the function, the classs member variables and other member functions may all be variables and other member functions may all be yyaccessed.accessed.

    If we activate

    void point::initialize(double init_x, double init_y){

    i it

    p1.initialize:p1.xp1 yx = init_x;

    y = init_y;}

    p1.y

    4040

  • point Implementationpoint Implementation xx2 2 1 1 0 0

    yy

    pp

    point Implementationpoint Implementation--2 2 --1 0 1 21 0 1 2

    --11--22

    Within the body of the function, the classs member Within the body of the function, the classs member variables and other member functions may all be variables and other member functions may all be yyaccessed.accessed.

    If we activate

    void point::initialize(double init_x, double init_y){

    i it

    p2.initialize:p2.xp2 yx = init_x;

    y = init_y;}

    p2.y

    4141

  • point Implementationpoint Implementation xx2 2 1 1 0 0

    yy

    pp

    point Implementationpoint Implementation

    H i h i l i f hH i h i l i f h tt bb--2 2 --1 0 1 21 0 1 2

    --11--22

    Here is the implementation of the Here is the implementation of the get_xget_x member member function, which return the x coordinate:function, which return the x coordinate:

    double point::get_x() const{{

    return x;

    }

    4242

  • point Implementationpoint Implementation xx2 2 1 1 0 0

    yy

    pp

    point Implementationpoint Implementation

    H i h i l i f hH i h i l i f h tt bb--2 2 --1 0 1 21 0 1 2

    --11--22

    Here is the implementation of the Here is the implementation of the get_xget_x member member function, which return the x coordinate:function, which return the x coordinate:

    double point::get_x() const {{

    return x;

    Notice how this member function implementationNotice how this member function implementation

    }

    4343

    Notice how this member function implementation Notice how this member function implementation uses the member variable x of the point object.uses the member variable x of the point object.

  • point Implementationpoint Implementation xx2 2 1 1 0 0

    yy

    pp

    point Implementationpoint Implementation

    M b f i i h bM b f i i h b--2 2 --1 0 1 21 0 1 2

    --11--22

    Member functions may activate other member Member functions may activate other member functionsfunctions

    void point::origin() {

    x = 0.0;y = 0.0;

    }

    N ti thi b f ti i l t ti tillN ti thi b f ti i l t ti till

    }

    4444

    Notice this member function implementation still Notice this member function implementation still directly assign the member variables x and y.directly assign the member variables x and y.

  • point Implementationpoint Implementation xx2 2 1 1 0 0

    yy

    pp

    point Implementationpoint Implementation

    M b f i i h bM b f i i h b--2 2 --1 0 1 21 0 1 2

    --11--22

    Member functions may activate other member Member functions may activate other member functionsfunctions

    void point::origin() {

    i iti li (0 0 0 0)initialize(0.0, 0.0);}

    Notice how this member function implementationNotice how this member function implementation

    4545

    Notice how this member function implementation Notice how this member function implementation uses the member function initialize.uses the member function initialize.

  • A Common PatternA Common PatternA Common PatternA Common Pattern

    l i t

    Often, one or more member functions will Often, one or more member functions will place data in the member variables...place data in the member variables...

    class point {public:

    void initialize(double init_x, double init_y);id hift(d bl d d bl d )void shift(double dx, double dy);

    double get_x( ) const;double get_y( ) const;

    private:d bldouble x;double y;

    };Initialize & shift get_x & get_y

    4646

    ...so that other member functions may use that ...so that other member functions may use that data.data.

  • Summary of classesSummary of classesSummary of classes Summary of classes

    ClassesClasses have member variables and member have member variables and member functions. An functions. An objectobject is a variable where the data is a variable where the data type is a classtype is a classtype is a class.type is a class.

    You should know how to You should know how to declaredeclare a new class type, a new class type, how tohow to implementimplement its member functions, how toits member functions, how to useusehow to how to implementimplement its member functions, how to its member functions, how to useusethe class type.the class type.

    Frequently, the member functions of an class type Frequently, the member functions of an class type place information in the member variables, or use place information in the member variables, or use information that's already in the member variables.information that's already in the member variables.

    Ne t e ill see more feat res of OOP and classesNe t e ill see more feat res of OOP and classes

    4747

    Next we will see more features of OOP and classes.Next we will see more features of OOP and classes.

  • AssignmentsAssignmentsAssignments Assignments

    Reading: Reading: Chapter 2.3Chapter 2.3--2.52.5

    Programming assignment 1 Programming assignment 1 -- Due Due June 12June 12 Need all of chapter 2 to finish, but you can start doing it Need all of chapter 2 to finish, but you can start doing it

    nownownownow Requirements and guidelines have been posted on the Requirements and guidelines have been posted on the

    course web sitecourse web siteC I ll i G id liC I ll i G id li C++ Installation Guide onlineC++ Installation Guide online Linux Users: See the assignment #1 guidelinesLinux Users: See the assignment #1 guidelines Mac/Win Users: Check the courseMac/Win Users: Check the course pagepage

    4848

    Mac/Win Users: Check the course Mac/Win Users: Check the course pagepage

  • BreakBreak

    4949

  • OutlineOutlineOutlineOutline

    A Review of C++ Classes (Lecture 2)A Review of C++ Classes (Lecture 2) OOP, ADTs and ClassesOOP, ADTs and Classes,, Class Definition, Implementation and UseClass Definition, Implementation and Use Constructors and Value SemanticsConstructors and Value SemanticsMore on Classes (Lecture 3)More on Classes (Lecture 3) Namespace and DocumentationNamespace and Documentation Namespace and DocumentationNamespace and Documentation Classes and ParametersClasses and Parameters Operator OverloadingOperator Overloading

    5050

    Operator OverloadingOperator Overloading

  • Constructors: point InitializationConstructors: point Initialization xx2 2 1 1 0 0

    yy

    pp

    Constructors: point InitializationConstructors: point Initialization--2 2 --1 0 1 21 0 1 2

    --11--22

    The program The program starts by starts by

    #include #include #include point h"activatingactivating the the

    initialize initialize member f nctionmember f nction

    #include point.h"

    int main( ) {member function member function

    for p1.for p1.{

    point p1:point p2;

    p1.initialize(-1.0, 0.8);

    First improvement: automatic initializationFirst improvement: automatic initialization

    5151

    First improvement: automatic initialization First improvement: automatic initialization without activating the initialize functionwithout activating the initialize function

  • Constructors: point InitializationConstructors: point Initialization xx2 2 1 1 0 0

    yy

    pp

    Constructors: point InitializationConstructors: point Initialization--2 2 --1 0 1 21 0 1 2

    --11--22

    class point

    We can provide a normal member function We can provide a normal member function initializeinitializep

    {public:

    void initialize(double init x double init y);void initialize(double init_x, double init_y);void shift(double dx, double dy);double get_x() const;double get_y( ) const;

    private:double x;

    5252

    ;double y;

    };

  • Constructors: point InitializationConstructors: point Initialization xx2 2 1 1 0 0

    yy

    pp

    Constructors: point InitializationConstructors: point Initialization--2 2 --1 0 1 21 0 1 2

    --11--22

    class point

    Or use a constructor that is automatically calledOr use a constructor that is automatically calledp

    {public:

    point(double init x double init y);point(double init_x, double init_y);void shift(double dx, double dy);double get_x() const;double get_y( ) const;

    private:double x; --function name same as class namefunction name same as class name

    5353

    ;double y;

    }; -- no return type, even no void !no return type, even no void !

  • Constructors: ImplementationConstructors: Implementation xx2 2 1 1 0 0

    yy

    pp

    Constructors: ImplementationConstructors: Implementation--2 2 --1 0 1 21 0 1 2

    --11--22

    For the most part, the constructor is no different For the most part, the constructor is no different than any other member functions.than any other member functions.

    void point::initialize(double init_x, double init_y){{

    x = init_x;y = init_y;

    }

    5454

    We only need to replace We only need to replace initializeinitialize with with pointpoint

  • Constructors: ImplementationConstructors: Implementation xx2 2 1 1 0 0

    yy

    pp

    Constructors: ImplementationConstructors: Implementation--2 2 --1 0 1 21 0 1 2

    --11--22

    For the most part, the constructor is no different For the most part, the constructor is no different than any other member functions.than any other member functions.

    point::point(double init_x, double init_y){{

    x = init_x;y = init_y;

    }

    5555

    But there are three special features about constructor . . But there are three special features about constructor . . ..

  • ConstructorsConstructorsConstructorsConstructors

    Constructor is a member function whichConstructor is a member function which the name must be the same as the class namethe name must be the same as the class name automatically called whenever a variable of the automatically called whenever a variable of the

    class is declaredclass is declared arguments must be given after the variable arguments must be given after the variable

    name (when declared in user file)name (when declared in user file)A a to impro e the initiali e f nctionA a to impro e the initiali e f nctionA way to improve the initialize functionA way to improve the initialize function by providing an initialization function that is by providing an initialization function that is

    guaranteed to be calledguaranteed to be called

    5656

    guaranteed to be calledguaranteed to be called

  • Constructors: point InitializationConstructors: point Initialization xx2 2 1 1 0 0

    yy

    pp

    Constructors: point InitializationConstructors: point Initialization--2 2 --1 0 1 21 0 1 2

    --11--22

    Automatically Automatically called when called when

    #include #include #include point h"declared.declared.

    Parameters after Parameters after h bjh bj

    #include point.h"

    int main( ) {the object namesthe object names { point p1:

    point p2;

    p1.initialize(-1.0, 0.8);

    First improvement: automatic initializationFirst improvement: automatic initialization

    5757

    First improvement: automatic initialization First improvement: automatic initialization without explicitly activating an initialize without explicitly activating an initialize functionfunction

  • Constructors: point InitializationConstructors: point Initialization xx2 2 1 1 0 0

    yy

    pp

    Constructors: point InitializationConstructors: point Initialization--2 2 --1 0 1 21 0 1 2

    --11--22

    Automatically Automatically called when called when

    #include #include #include point h"declared.declared.

    Parameters after Parameters after h bjh bj

    #include point.h"

    int main( ) {the object namesthe object names { point p1(-1.0, 0.8):

    point p2(0.3, 0.6);

    First improvement: automatic initializationFirst improvement: automatic initialization

    5858

    First improvement: automatic initialization First improvement: automatic initialization without explicitly activating an initialize without explicitly activating an initialize functionfunction

  • Default ConstructorsDefault Constructors xx2 2 1 1 0 0

    yy

    pp

    Default ConstructorsDefault Constructors--2 2 --1 0 1 21 0 1 2

    --11--22

    Automatically Automatically called when called when

    #include #include #include point h"declared.declared.

    Parameters after Parameters after h bjh bj

    #include point.h"

    int main( ) {the object namesthe object names { point p1(-1.0, 0.8):

    point p2(0.3, 0.6);

    Sometime we want to define an object withSometime we want to define an object with

    5959

    Sometime we want to define an object with Sometime we want to define an object with no parametersno parameters

  • Default ConstructorsDefault Constructors xx2 2 1 1 0 0

    yy

    pp

    Default ConstructorsDefault Constructors--2 2 --1 0 1 21 0 1 2

    --11--22

    Automatically Automatically called when called when

    #include #include #include point h"declared.declared.

    NO parameters NO parameters f h bjf h bj

    #include point.h"

    int main( ) {after the object after the object

    name p2name p2

    {point p1(-1.0, 0.8);point p2;

    not even a pair of parenthesesnot even a pair of parentheses

    6060

    not even a pair of parenthesesnot even a pair of parentheses

  • Default ConstructorsDefault Constructors xx2 2 1 1 0 0

    yy

    pp

    Default ConstructorsDefault Constructors--2 2 --1 0 1 21 0 1 2

    --11--22

    class point

    We could provide a second constructor with no parametersWe could provide a second constructor with no parametersp

    {public:

    point();

    Implementation Implementation

    point::point()point();point(double init_x, double init_y);

    {x = 0.0;y = 0.0;private:

    double x;double y;

    y 0.0;}

    6161

    y;};

  • Constructors: Function OverloadingConstructors: Function OverloadingConstructors: Function OverloadingConstructors: Function Overloading

    You may declare as many constructors as You may declare as many constructors as you like you like one for each different way of one for each different way of initializing an objectinitializing an object

    Each constructor must have a distinct Each constructor must have a distinct parameter list so that the compiler can tell parameter list so that the compiler can tell them partthem part

    Question: How many default constructor is Question: How many default constructor is allowed?allowed?

    6262

  • Constructors: automatic default constructorConstructors: automatic default constructorConstructors: automatic default constructorConstructors: automatic default constructor

    What happens if you write a class without any What happens if you write a class without any constructors?constructors?

    The compiler automatically creates a simple The compiler automatically creates a simple default constructordefault constructor which only calls the default constructors for the which only calls the default constructors for the

    member variables that are objects of some other classesmember variables that are objects of some other classes

    Programming Tip :Always provide your ownProgramming Tip :Always provide your own Programming Tip :Always provide your own Programming Tip :Always provide your own constructors, and better with a default constructorconstructors, and better with a default constructor

    6363

  • Value Semantics of a ClassValue Semantics of a ClassValue Semantics of a ClassValue Semantics of a Class

    Value semantics determines how values are Value semantics determines how values are copied from one object to anothercopied from one object to another

    Consists of two operations in C++Consists of two operations in C++ The assignment operatorThe assignment operator The copy constructorThe copy constructor

    Document the value semanticsDocument the value semantics When you implement an ADT, the document should When you implement an ADT, the document should

    include a comment indicating that the value semantics include a comment indicating that the value semantics is safe to use.is safe to use.

    6464

    is safe to use.is safe to use.

  • Value Semantics: assignment operatorValue Semantics: assignment operatorValue Semantics: assignment operatorValue Semantics: assignment operator

    Automatic assignment operatorAutomatic assignment operator For a new class, C++ normally carries out assignment For a new class, C++ normally carries out assignment

    by simply copying each variable from the object on theby simply copying each variable from the object on theby simply copying each variable from the object on the by simply copying each variable from the object on the right to that on the leftright to that on the left

    our new class point can use automatic assignment our new class point can use automatic assignment operator operator point p1(-1.0, 0.8), p2;

    p2 = p1;

    When automatic assignment failsWhen automatic assignment fails we will see examples in Lecture 4 (pointers andwe will see examples in Lecture 4 (pointers and

    cout

  • Value Semantics: copy constructorValue Semantics: copy constructorValue Semantics: copy constructorValue Semantics: copy constructor

    A copy constructorA copy constructor is a constructor with exactly one parameteris a constructor with exactly one parameter is a constructor with exactly one parameter is a constructor with exactly one parameter

    whose data type is the same as the constructors whose data type is the same as the constructors classclass

    is to initialize a new object as an exact copy of is to initialize a new object as an exact copy of an existing objectan existing object

    An example An example point p1(-1.0, 0.8);point p2 (p1);

    6666

    cout

  • Value Semantics: copy constructorValue Semantics: copy constructorValue Semantics: copy constructorValue Semantics: copy constructor

    A copy constructorA copy constructor is a constructor with exactly one parameteris a constructor with exactly one parameter is a constructor with exactly one parameter is a constructor with exactly one parameter

    whose data type is the same as the constructors whose data type is the same as the constructors classclass

    is to initialize a new object as an exact copy of is to initialize a new object as an exact copy of an existing objectan existing object

    An alternative syntaxAn alternative syntaxpoint p1(-1.0, 0.8);

    6767

    point p2 = p1;

    cout

  • Value Semantics: discussionValue Semantics: discussionValue Semantics: discussionValue Semantics: discussion

    point p2 = p1;point p2 = p1; versus versus p2 = p1;p2 = p1; The assignment The assignment p2 = p1;p2 = p1; merely copies p1 to the merely copies p1 to the

    already existing object p2 using thealready existing object p2 using the assignmentassignmentalready existing object p2 using the already existing object p2 using the assignment assignment operatoroperator. .

    The syntax The syntax point p2 = p1;point p2 = p1; looks like an assignment looks like an assignment statement, but actually a declaration that both declare a statement, but actually a declaration that both declare a new object, and calls the new object, and calls the copy constructorcopy constructor to initialize to initialize p2 as a copy of p1.p2 as a copy of p1.

    p2 will be the same iff the assignment operator p2 will be the same iff the assignment operator and the copy constructor do the same thingsand the copy constructor do the same things

    6868

    and the copy constructor do the same thingsand the copy constructor do the same things

  • Copy Constructor: ImplementationCopy Constructor: ImplementationCopy Constructor: ImplementationCopy Constructor: Implementation

    You may write a copy constructor much like any You may write a copy constructor much like any other constructorother constructor Lecture 4 and laterLecture 4 and later

    Take advantage of a C++ featureTake advantage of a C++ feature automatic copy constructorautomatic copy constructor similar to assignment, the automatic copy constructor similar to assignment, the automatic copy constructor

    initializes a new object by merely copy all the memberinitializes a new object by merely copy all the memberinitializes a new object by merely copy all the member initializes a new object by merely copy all the member variables from the existing object.variables from the existing object.

    Automatic versions may fail!Automatic versions may fail!

    6969

  • Constructors etc a summaryConstructors etc a summaryConstructors, etc. a summaryConstructors, etc. a summary

    Constructor is a member functionConstructor is a member function define your own constructors (including a default)define your own constructors (including a default)

    i d f li d f l automatic default constructorautomatic default constructor inline member functions ( Ch 2.2)inline member functions ( Ch 2.2)

    Place a function definition inside the class definitionPlace a function definition inside the class definition Place a function definition inside the class definitionPlace a function definition inside the class definition for time efficiencyfor time efficiency

    value semantics of a classvalue semantics of a class assignment operators and copy constructorassignment operators and copy constructor automatic assignment op and copy constructorautomatic assignment op and copy constructor

    7070

  • OutlineOutlineOutlineOutline

    A Review of C++ Classes (Lecture 2)A Review of C++ Classes (Lecture 2) OOP, ADTs and ClassesOOP, ADTs and Classes,, Class Definition, Implementation and UseClass Definition, Implementation and Use Constructors and Value SemanticsConstructors and Value SemanticsMore on Classes (Lecture 3)More on Classes (Lecture 3) Namespace and DocumentationNamespace and Documentation Namespace and DocumentationNamespace and Documentation Classes and ParametersClasses and Parameters Operator OverloadingOperator Overloading

    7171

    Operator OverloadingOperator Overloading

  • AssignmentsAssignmentsAssignments Assignments

    Reading: Reading: Chapter 2.3Chapter 2.3--2.52.5 Chapter 2.3Chapter 2.3 2.52.5

    Programming assignment 1 Programming assignment 1 -- Due Due June 12June 12 Need all of chapter 2 to finish but you canNeed all of chapter 2 to finish but you can Need all of chapter 2 to finish, but you can Need all of chapter 2 to finish, but you can

    start doing it nowstart doing it now Requirements and guidelines have been postedRequirements and guidelines have been posted Requirements and guidelines have been posted Requirements and guidelines have been posted

    on the course web siteon the course web site

    7272

  • Th fi t t ( 3Th fi t t ( 3 47) f thi l t d t d f47) f thi l t d t d fThe first part (p.3The first part (p.3--47) of this lecture was adapted from:47) of this lecture was adapted from:

    Presentation copyright 1997, Addison Wesley LongmanPresentation copyright 1997, Addison Wesley LongmanFor use with For use with Data Structures and Other Objects Using C++Data Structures and Other Objects Using C++by Michael Main and Walter Savitch.by Michael Main and Walter Savitch.

    Some artwork in the presentation is used with permission from Presentation Task ForceSome artwork in the presentation is used with permission from Presentation Task Force(copyright New Vision Technologies Inc.) and Corel Gallery Clipart Catalog (copyright(copyright New Vision Technologies Inc.) and Corel Gallery Clipart Catalog (copyrightCorel Corporation, 3G Graphics Inc., Archive Arts, Cartesia Software, Image ClubCorel Corporation, 3G Graphics Inc., Archive Arts, Cartesia Software, Image ClubGraphics Inc., One Mile Up Inc., TechPool Studios, Totem Graphics Inc.).Graphics Inc., One Mile Up Inc., TechPool Studios, Totem Graphics Inc.).

    Students and instructors who use Students and instructors who use Data Structures and Other ObjectsData Structures and Other Objects Using C++ Using C++ arearewelcome to use this presentation however they see fit, so long as this copyright notice welcome to use this presentation however they see fit, so long as this copyright notice remains intact.remains intact.

    THE ENDTHE END

    7373

    THE ENDTHE END