Skip to main contentCal State San Bernardino / [CNS] / [Comp Sci Dept] / [R J Botting] >> [CSci202] >> 05
[Index] [Schedule] [Syllabi] [Text] [Labs] [Projects] [Resources] [Search] [Contact] [Grading]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20]
Tue Apr 17 15:41:55 PDT 2007

Contents


    CSci202 Computer Science II, Session 05, Objects in C++


      (Previous): UML and OO programming [ 04.html ]

      Preparation

      Study this page and Chapter 7 on C++ classes and write down the questions, doubts, and surprises that you have on a piece of paper. Include your printed name!

      Note on top page 226

      On our systems we do not use "demo.exe" but "demo".

      Assigned Work Due

      Note on top page 226

      On our systems we do not use "demo.exe" but "demo".

      An Improvement on algorithm on page 245

      The algorithm for .key shuffle can be improved. I developed, tested, and published a better algorithm than this one in 1974.

      There is no need to do 1000 random swaps -- you only need 52!

       Loop for n1 in 1 to 52
          n2=random in n1+1 .. 52
          swap card n1 with card n2
       End loop

      Bonus

      Hand in Project 2 to earn a Bonus. Resubmissions of Project 1 will not be accepted.

      Input

      1. Hints for drawing a UML diagram. Example: designing a simple Counter. Answer: [ Counter.jpg ] TBA
      2. Note: A class diagram does not specify what operations do.
        • Use good names. (good = clear && accurate && standardized)
        • Write a program that tests the functions as part of the specification.

        • Later: Use some of the other UML diagrams.
        • Add a comment boxes and use Object Constraint Language.
        • Use a CASE tool and fill in the specification tabs.
        • Iff safety is critical, use mathematics and symbolic logic to give a precise and checkable spec.

        An example of testing a C++ class with the assert function. [ testCounter.cpp ] (published).
      3. Coding a UML class diagram in C++. Hint: use an blank class header file [ blank.h ] [ testBlank.cpp ] as a starting point. Answer [ Counter.h ] TBA

      Quick Exercise and return of graded work: Q1 and P1

      The class drew and compare class diagrams for the class Clock in Chapter 7.

      Questions

        One will be answered, at least, from each person. Some in class, some on paper, and some will be recorded here before the next class.

        Examples of dividing programs into files

        I have some notes [ Complex Projects in resources ] on this topic. We will return to this topic in later classes and in lab04.

        What are the {..} for after a function in a class

        These a complete "inline" function definitions. They include the implementation of the function as part of its declaration inside the class. For example on page 219
             int read_min() { return m; }
        could be rewritten as
             int read_min();
        as long as we later, outside of class Clock wrote
             inline int Clock::read_min() { return m; }

        What are inline functions

        These are functions that are copied by the compiler and inserted in your code where ever they are called. They are executed instantly because the computer doesn't have to jump to the body and back again. However, they use up space.

        Inline functions should be small and simple -- one line max. It is normal to define [ Getters and Setters ] (below) as inline functions.

        Getters and Setters

        A Getter function is one that gets the value of a private variable. Nearly all OO programmers use a name like "getX" for variable x:
             int getM() const { return m; }
        The const tells the C++ compiler that we won't be changing any variables in the function.

        Similarly a Setter is a function that sets the value of a private variable ... use these only when needed and safe. If we needed a clock where the minutes could be set to a value we might write:

             void setM(int m0) { assert(0<=m and m<=60); m=m0; }

        Can you return a vector from a function

        Yes. The function definition of function f that return a vector of doubles would be like this
             vector<double> f(data);
        and its implementation for class C might be like this
             vector<double> C::f(data) {vector <double> result; ...... return result; }
        You could call it like this
             myVector= myC.f(myData);

        However -- returning large amount of data (a vector can have a million items) slows down programs and should be avoided if possible. This is a classic case for using pass by reference:

             void f(data, vector<double> & result);
        with implementation like this
             void C::f(data, vector<double> & result) { ...... return result; }
        You could call it like this
             myC.f(myData, myVector);

        Why not make everything public

        This is what we did in the 1960's. It leads to bugs when you misuse the parts of objects in incorrect ways.

        It is rather like owning a clockwork watch with no case. It breaks down because of stuff getting into it.

        As a rule: data should be private and most functions are public. Make a function private if there is a way for it to be misused.

        What is a constructor

        A function in a class that puts the initial data into a newly created object. The name (in C++ and Java) is the same as the name of the class.

        How do I call constructors

        Constructors are called automatically when you declare an object:
             Class object(data);
        or get a new object
             Class * pointer = new Class(data);

        If I have a function or constructor with a char * can I give it a char[10]

        Yes -- like this
             blah example(char * s)....
             char a[10] = "hello";
             .... example( a)...

        What happens to data that I deallocate

        The computer keeps a list of unused and deallocated RAM and recycles it when you need it.

        What are friend functions

        A friend has access to the private data and functions of a class.

        A friend function must not have an object when it is called.

        The commonest friend functions are those that input and output objects.

        More in the next [ 06.html ] class.

        When and Why use Inline fucntions

        Inline code is easier to write and runs faster..... but it leads to bigger compiled programs.

        Rule: short functions are best inline. Long ones should not be inline.

        Unlike many books and some instructors I encourage you to include small function bodies in your "header files" and class declarations. This is more a practitioner's approach than a purist's guide line. A small function/constructor/destructor is no more than one line long:

         		It get_it() const{return it;}
         		void set_it(It is) { it=is;}
        (The above are typical of the many boring short function we write for some classes).

        When to use initialization lists vs code in a constructor body

        First you may not assign to const and attributes/data members can not be initialized in their declaration. The items initialized in the list are done before the object fully exists and its constant fields/attributes are locked into their final form.

        As a rule: use initialization lists whenever the arguments to a constructor provides values for data members/fields/attributes.

        What is there a semicolon at the end of a class definition?

        It terminates a list of declared objects! C++ allows you the option of defining a class and declaring an object of that type in one blow:
         		class Pair{ public: int first, second;} x,y;
         		x.first=1; y.first=2; x.second=y.first; y.first=x.first++;

        Why didn't C++ add a sophisticated way to do ifndef....

        I don't know... Possibly the standard writers where lazy.

        Constructors

        A constructor prepares a new object for use. In C++ it must have the same name as the class of object it creates. Most classes need at least one called the "default constructor".

        Because all constructors in a class have the same name, the identifier is overloaded. They must have different kinds of argument.

        If one actually wants to stop others from constructing new objects, then you merely define constructors as private functions. This is sometimes useful.

        The Counter class has a simple example, above. There will be more in other classes.

        Why use classes when we can write functions without classes?

        The functions in a class are good when we want to do things to some data. Functions outside classes are good for truly mathematical functions that take some input data and produce some new data. For example, sqrt takes in a double and produces a double. When we want to add something to an existing object or to remove something from it then a function in a class is better.

        Classes make programs that are clearer and easier to modify: many small independent pieces.

        Do we have to have a destructor if we don't allocate memory?

        Even if a class doesn't allocate heap storage, one of the classes that are derived from it may do so. It is wise to always include a destructor.... more later.

        Private vs Public parts

        The private attributes and operations are inside an invisible case so that they can not be used by commands outside the class. Imagine them as the works of a watch. The public parts are like the knobs and buttons and dials on the outside of a watch or clock.

      Exercises

      Based on chapter 7 and the Input above. Examples: take UML and code in C++, take given C++ and draw UML, ...

      A CaloryCounter counts up only and has three values for the hundreds, tens, and units of calories. Draw a quick UML diagram, write a test program, and code in C++.

      Lab on using Dia to draw Diagrams and the UML

      [ lab03.html ]

    . . . . . . . . . ( end of section CSci202 Computer Science II, Session 05, Objects in C++) <<Contents | End>>
    (Next): More about C++ Classes (Chapter 8) [ 06.html ] plus Project 2 is due at the start of the next class. Study these pages! [ project2.html ] [ projects.html ]

    Abreviations

  1. TBA::="To Be Announced", something I have to do.
  2. TBD::="To Be Done", something you have to do.
  3. Dia::="A free Open Source Diagramming tool for Linux, Windoze, etc. ".

End