0380017

Embed Size (px)

Citation preview

  • 7/28/2019 0380017

    1/16

    661

    EXAMPLE

    C+ + By

    32

    Introduction toObject-OrientedProgramming

    The most widely used object-oriented programming language to-day is C++. C++ provides classeswhich are its objects. Classesreally distinguish C++ from C. In fact, before the name C++ wascoined, the C++ language was called C with classes.

    This chapter attempts to expose you to the world of object-oriented programming, often called OOP. You will probably notbecome a master of OOP in these few short pages, however, you areready to begin expanding your C++ knowledge.

    This chapter introduces the following concepts:

    o C++ classes

    o Member functions

    oConstructors

    o Destructors

    This chapter concludes your introduction to the C++ language.After mastering the techniques taught in this book, you will be readyto modify the mailing list program in Appendix F to suit your ownneeds.

  • 7/28/2019 0380017

    2/16

    Chapter 32oIntroduction to O bject-O riented Programming

    662

    What Is a Class?

    A class is a user-defined data type that resembles a structure. A

    class can have data members, but unlike the structures you haveseen thus far, classes can also have member functions. The datamembers can be of any type, whether defined by the language or byyou. The member functions can manipulate the data, create anddestroy class variables, and even redefine C++s operators to act onthe class objects.

    Classes have several types of members, but they all fall into twocategories: data members and member functions.

    Data MembersData members can be of any type. Here is a simple class:

    / / A spher e cl ass.

    cl ass Sphere

    {

    publ i c:

    f l oat r ; / / Radi us of spher e

    f l oat x, y, z; / / Coor di nat es of sphere

    };

    Notice how this class resembles structures you have alreadyseen, with the exception of the publ i c keyword. The Sphere class hasfour data members: r , x, y, and z. In this case, the publ i c keywordplays an important role; it identifies the class Spher e as a structure.As a matter of fact, in C++, apublic class is physically identical to astructure. For now, ignore the publ i c keyword; it is explained laterin this chapter.

    Member Functions

    A class can also have member functions (members of a class thatmanipulate data members). This is one of the primary features thatdistinguishes a class from a structure. Here is the Spher e class again,with member functions added:

  • 7/28/2019 0380017

    3/16

    663

    EXAMPLE

    C+ + By

    #i ncl ude

    const f l oat PI = 3. 14159;

    / / A spher e cl ass.

    cl ass Sphere

    {

    publ i c:

    f l oat r ; / / Radi us of spher e

    f l oat x, y, z; / / Coor di nat es of spher e

    Spher e( f l oat xcoor d, f l oat ycoor d, f l oat zcoor d, f l oat r adi us)

    { x = xcoord; y = ycoord; z = zcoor d; r = r adi us; }

    ~Sphere( ) { }

    f l oat vol ume( )

    {

    return ( r * r * r * 4 * PI / 3) ;

    }

    f l oat sur f ace_ar ea( )

    {

    return (r * r * 4 * PI ) ;

    }

    };

    This Sphere class has four member functions: Spher e( ) , ~Spher e( ) ,vol ume( ) , and sur f ace_area( ) . The class is losing its similarity to astructure. These member functions are very short. (The one with the

    strange name of~Spher e( ) has no code in it.) If the codes of themember functions were much longer, only the prototypes wouldappear in the class, and the code for the member functions wouldfollow later in the program.

    C++ programmers call class data objects because classes domore than simply hold data. Classes act on data; in effect, a class isan object that manipulates itself. All the data you have seen so far inthis book ispassive data (data that has been manipulated by code inthe program). Classes member functions actually manipulate classdata.

    In this example, the class member Spher e( ) is a special function.It is a constructor function, and its name must always be the same asits class. Its primary use is declaring a new instance of the class.

    Constructors createand initialize class

    data.

  • 7/28/2019 0380017

    4/16

    Chapter 32oIntroduction to O bject-O riented Programming

    664

    Examples

    1. The following program uses the Sphere( ) class to initialize a

    class variable (called a class instance) and print it./ / Fi l ename: C32CON. CPP

    / / Demonst r at es use of a cl ass const r uct or f unct i on.

    #i ncl ude

    const f l oat PI = 3. 14159; / / Appr oxi mat e val ue of pi .

    / / A spher e cl ass.

    cl ass Spher e

    {

    publ i c:

    f l oat r; / / Radi us of spher e

    f l oat x, y, z; / / Coor di nat es of sphere

    Spher e( f l oat xcoor d, f l oat ycoor d,

    f l oat zcoord, f l oat r adi us)

    { x = xcoord; y = ycoord; z = zcoor d; r = r adi us; }

    ~Sphere( ) { }

    f l oat vol ume( )

    {

    return ( r * r * r * 4 * PI / 3) ;

    }

    f l oat sur f ace_ar ea( )

    {

    return (r * r * 4 * PI ) ;

    }

    };

    voi d mai n()

    {

    Spher e s( 1. 0, 2. 0, 3. 0, 4. 0) ;

    cout

  • 7/28/2019 0380017

    5/16

    665

    EXAMPLE

    C+ + By

    Note: In OOP, the mai n( ) function (and all it calls) becomessmaller because member functions contain the code that ma-

    nipulates all class data.

    Indeed, this program looks different from those you haveseen so far. This example is your first true exposure to OOPprogramming. Here is the output of this program:

    X = 1, Y = 2, Z = 3, R = 4

    This program illustrates the Spher e( ) constructor function.The constructor function is the only member function calledby the program. Notice the ~Spher e( ) member function

    constructed s, and initialized its data members as well.

    The other special function is the destructor function,~Spher e( ) . Notice that it also has the same name as the class,but with a tilde (~) as a prefix. The destructor function nevertakes arguments, and never returns values. Also notice thatthis destructor doesnt do anything. Most destructors dovery little. If a destructor has no real purpose, you do nothave to specify it. When the class variable goes out of scope,the memory allocated for that class variable is returned tothe system (in other words, an automatic destruction oc-

    curs). Programmers use destructor functions to free memoryoccupied by class data in advanced C++ applications.

    Similarly, if a constructor doesnt serve any specific function,you arent required to declare one. C++ allocates memory fora class variable when you define the class variable, just as itdoes for all other variables. As you learn more about C++programming, especially when you begin using the ad-vanced concept ofdynamic memory allocation, constructorsand destructors become more useful.

    2. To illustrate that the~Spher e( )

    destructor does get called (itjust doesnt do anything), you can put a cout statement in theconstructor as seen in the next program:

    / / Fi l ename: C32DES. CPP

    / / Demonst r at es use of a cl ass dest r uct or f unct i on.

    Destructors erase

    class data.

  • 7/28/2019 0380017

    6/16

    Chapter 32oIntroduction to O bject-O riented Programming

    666

    #i ncl ude

    #i ncl ude

    const f l oat PI = 3. 14159; / / Appr oxi mat e val ue of pi .

    / / A spher e cl ass

    cl ass Spher e

    {

    publ i c:

    f l oat r ; / / Radi us of spher e

    f l oat x, y, z; / / Coor di nat es of spher e

    Spher e( f l oat xcoor d, f l oat ycoor d,

    f l oat zcoord, f l oat r adi us)

    { x = xcoord; y = ycoord; z = zcoor d; r = r adi us; }

    ~Spher e( )

    {cout

  • 7/28/2019 0380017

    7/16

    667

    EXAMPLE

    C+ + By

    Notice that mai n( ) did not explicitly call the destructorfunction, but ~Spher e( ) was called automatically when theclass instance went out of scope.

    3. The other member functions have been waiting to be used.The following program uses the vol ume( ) and sur f ace_area( )functions:

    / / Fi l ename: C32MEM. CPP

    / / Demonst r ates use of cl ass member f unct i ons.

    #i ncl ude

    #i ncl ude

    const f l oat PI = 3. 14159; / / Appr oxi mat e val ue of pi .

    / / A spher e cl ass.

    cl ass Spher e

    {

    publ i c:

    f l oat r; / / Radi us of spher e

    f l oat x, y, z; / / Coor di nat es of spher e

    Spher e( f l oat xcoor d, f l oat ycoor d,

    f l oat zcoor d, f l oat r adi us)

    { x = xcoord; y = ycoord; z = zcoor d; r = r adi us; }

    ~Spher e( )

    {

    cout

  • 7/28/2019 0380017

    8/16

    Chapter 32oIntroduction to O bject-O riented Programming

    668

    cout

  • 7/28/2019 0380017

    9/16

    669

    EXAMPLE

    C+ + By

    }

    };

    voi d mai n(){

    Spher e s( 1. 0, 2. 0, 3. 0, 4. 0) ;

    cout

  • 7/28/2019 0380017

    10/16

    Chapter 32oIntroduction to O bject-O riented Programming

    670

    The advantage of using in-line functions is that they executefastertheres no function-call overhead involved becauseno function is actually called. The disadvantage is that ifyour functions are used frequently, your programs become

    larger and larger as functions are expanded.

    Default Member Arguments

    You can also give member functions arguments by default.Assume by default that they coordinate of a sphere will be 2.0, thez coordinate will be 2.5, and the radius will be 1.0. Rewriting theprevious examples constructor function to do this results in thiscode:

    Spher e( f l oat xcoor d, f l oat ycoor d = 2. 0, f l oat zcoor d = 2. 5,

    f l oat r adi us = 1. 0)

    { x = xcoord; y = ycoord; z = zcoor d; r = r adi us; }

    You can create a sphere with the following instructions:

    Spher e s( 1. 0) ; / / Use al l def aul t

    Spher e t ( 1. 0, 1. 1) ; / / Over r i de y coor d

    Spher e u( 1. 0, 1. 1, 1. 2) ; / / Over r i de y and z

    Spher e v( 1. 0, 1. 1, 1. 2, 1. 3) ; / / Over r i de al l def aul t s

    voi d mai n( )

    {

    Spher e s( 1. 0, 2. 0, 3. 0, 4. 0) ;

    cout

  • 7/28/2019 0380017

    11/16

    671

    EXAMPLE

    C+ + By

    Examples

    1. Default arguments are used in the following code.

    / / Fi l ename: C32DEF. CPP

    / / Demonst r ates use of def aul t argument s i n

    / / cl ass member f unct i ons.

    #i ncl ude

    #i ncl ude

    const f l oat PI = 3. 14159; / / Appr oxi mat e val ue of pi .

    / / A spher e cl ass.

    cl ass Spher e

    {

    publ i c:f l oat r; / / Radi us of spher e

    f l oat x, y, z; / / Coor di nat es of spher e

    Spher e( f l oat xcoor d, f l oat ycoor d = 2. 0,

    f l oat zcoor d = 2. 5, f l oat r adi us = 1. 0)

    { x = xcoord; y = ycoord; z = zcoor d; r = r adi us; }

    ~Spher e( )

    {

    cout

  • 7/28/2019 0380017

    12/16

    Chapter 32oIntroduction to O bject-O riented Programming

    672

    cout

  • 7/28/2019 0380017

    13/16

    673

    EXAMPLE

    C+ + By

    2. You also can call more than one constructor; this is calledoverloading the constructor. When having more than oneconstructor, all with the same name of the class, you must

    give them each a different parameter list so the compiler candetermine which one you intend to use. A common use ofoverloaded constructors is to create an uninitialized objecton the receiving end of an assignment, as you see done here:

    / / C32OVCON. CPP

    / / Demonst r ates use of overl oaded const r uct ors.

    #i ncl ude

    #i ncl ude

    const f l oat PI = 3. 14159; / / Appr oxi mat e val ue of pi .

    / / A spher e cl ass.

    cl ass Spher e

    {

    publ i c:

    f l oat r; / / Radi us of spher e

    f l oat x, y, z; / / Coor di nat es of spher e

    Spher e( ) { / * doesn t do anyt hi ng. . . */ }

    Spher e( f l oat xcoor d, f l oat ycoor d,

    f l oat zcoor d, f l oat r adi us)

    { x = xcoord; y = ycoord; z = zcoor d; r = r adi us; }

    ~Spher e( )

    {

    cout

  • 7/28/2019 0380017

    14/16

    Chapter 32oIntroduction to O bject-O riented Programming

    674

    Spher e t ; / / No par amet er s ( an uni ni t i al i zed spher e) .

    cout

  • 7/28/2019 0380017

    15/16

    675

    EXAMPLE

    C+ + By

    publ i c:

    Spher e( f l oat xcoor d, f l oat ycoor d, f l oat zcoor d, f l oat r adi us)

    { x = xcoord; y = ycoord; z = zcoor d; r = r adi us; }

    ~Spher e( ){

    cout

  • 7/28/2019 0380017

    16/16

    Chapter 32oIntroduction to O bject-O riented Programming

    676

    Review Questions

    The answers to the review questions are in Appendix B.

    1. What are the two types of class members called?

    2. Is a constructor always necessary?

    3. Is a destructor always necessary?

    4. What is the default visibility of a class data member?

    5. How do you make a class member visible outside its class?

    Review ExerciseConstruct a class to hold personnel records. Use the following

    data members, and keep them private:

    char name[ 25] ;

    f l oat sal ary;

    char dat e_of _bi r t h[ 9] ;

    Create two constructors, one to initialize the record with itsnecessary values and another to create an uninitialized record.Create member functions to alter the individuals name, salary, anddate of birth.

    Summary

    You have now been introduced to classes, the data type thatdistinguishes C++ from its predecessor, C. This was only a cursoryglimpse of object-oriented programming. However, you saw thatOOP offers an advanced view of your data, combining the data withthe member functions that manipulate that data. If you desire to

    learn more about C++ and become a guru of sorts, try UsingMicrosoft C/C++ 7 (Que, 0-88022-809-1).