[Skip Navigation] [CSUSB] / [CNS] / [Comp Sci & Eng Dept] / [R J Botting] / [CSci201] / 16
[Text Version] [Syllabus] [Schedule] [Glossary] [Labs] [Projects] [Resources] [Grading] [Contact] [Search ]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] [11] [12] [13] [14] [15] <16> [17] [18] [19] [20]
Podcasts: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] [11] [12]
Labs: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10]
Thu Feb 28 15:26:44 PST 2008

Contents


    Chapter 7: pages 215-233 Classes

      Reading

        Introduction

        Classes are the last data type we will cover in CS201. They let you write software that directly reflects the real world. As a result the code is easier to read, more likely to work weel, and easier to fix when it doesn't work.

        They are also a handy way of expanding the language. The <string> library declares a class of string objects that you have been using for most of the quarter. The <vector> library declares a type of object that has many similar objects hidden inside it. The <iostream> library defines several very useful objects

        • cin
        • cout
        • cerr
        • ...
        You used cin and cout in the very first lab. And cerr is just like cout except it is for reporting error messages and diagnostics.

        Notice -- you can use objects in a well written class without knowing what the detailed code for the class is. Classes are highly reusable.

        Objects encapsulate little pieces of intelligence. Little parts of the solution to the problem.

        The Clock Class

        I have taken all the definitions for the Clock class and the test example on page 217, added a few features, and put the result in [ clock.cpp ] and tested them.

        Demo -- sketching the UML for clock.cpp

        7.1 Class Definitions

        You can have as many public and private sections as you like. However most classes have one public and one private section. Further all the data members (variables) are private and most (if not all) of the member functions are public.

        You should learn to distinguish two kinds of functions

        1. accessors that get data but don't change it.
        2. mutators that change variables but don't return results

        Each public/private section can declare as many variables and functions as you like.

        You can also include the bodies of functions in the class Do this when the body is small -- one line long. Lots of functions in classes are this small. Functions that are defined inside a class are said to be inline and their calls are executed very much faster than functions that are not inline.

        Notice the semicolon at the end of a class definition. It is vital. Don't ask why!

        Page 220 -- using the double colon operator

         	className::functionName(....){.....}

        7.2 Placement of Classes

        This shows you how to do multifile programs.

        They need special Makefiles if you do it this way.

        In CSCI201 I'll be happy if your projects are not multifile projects. You can defeclare and define a class in the same file that uses it if you wixh. You may wish to place a class in a separate "....cpp" file and use #include to use it in a program:

         	#include "ClassName.cpp"
        For large projects this strategy is not efficient. It is easier when learning C++ to do it straightforwardly. In CS202 you will have to do the more complicated technique.

        7.3 Constructors

        You are not allowed to give values to variables declared in a class. (Don't ask why, I don't know).

        Instead you write functions with the same name as the class. And the actions you put in the body of a constructor are done when you declare a new object.

        7.3.1 Declarations of constructors

         		className ( parameters );
        notice the semicolon above.

        7.3.2 Definitions of constructors

        Note: a short constructor is best put inline.
         		ClassName (parameters) { shortBody }
        Notice the abscence of a semicolon above!

        A long constructor is best defined later:

         		ClassName::ClassName (parameters) { LotsOfStuff }
        Notice the abscence of a semicolon above!

        Note: we have a short hand for initializing variables

         		className( parameters ) : variable(value), ...

        Also take care to distinguish (...) from {....}.

        7.3.3 Calling Constructors

        When you declare variable a constructor is called.

        Once a variable is constructed you must not reconstruct it.

        You can create objects on the fly by using a constructure in an expression!

        You can create whole arrays of objects at one time!

        7.3.4 -- 7.4 SKIP

        7.5 NEXT Time.

      . . . . . . . . . ( end of section Reading) <<Contents | End>>

      Example of a Simple Class in C++

      Handout: [ 16ex.cpp ] plus a UML diagram (the kind I will ask for in the final project).

      Exercise 1: Fill in the blanks...

      Exercise 2: Predict what it does...

      Glossary

      1. object::=an instance of a class that has it's own data values and it's classes's operations.
      2. class::=a collection of objects that all have the same kinds of data and operations.
      3. inline::=a function is inline if its body is inside the class.
      4. data_member::=A variable that is part of an object.
      5. member_function::=A function in a class that is called by applying it to an object.
      6. constructor::=A function in a class with the same name as the class that initializes a new object.
      7. accessor::jargon=a member function in a class that accesses the values of data without changing them, should be marked as a const.
      8. getter::jargon=an accessor that gets and returns a value of a data member.
      9. mutator::jargon=a function in a class that changes the values of its variables but returns no data, should be void and have no const.
      10. setter::jargon=a mutator that sets one variable equal to a given value.

      Syntax

        Declaring a simple class
         class Name
         {
         	public:
         		Functions that can be used outside the class
         	private:
         		hidden variables and operations
         };
        Here is a template [ class.cpp ] that you can download and copy/paste or read into a C++ program. It includes some handy features -- all you have to do is , copy/and paste what you need, edit the Names, delete what you don't need, and make the functions do what you want.

        Declaring an object

         		ClassName variableName ( parameters );

        Declaring a pointer to an existing object

         		ClassName * variableName = &existingObjectName;

        Declaring a pointer to a new object

         		ClassName * variableName = new ClassName( parameters );

        Making an object do something

         		variable.functionName( parameters )
        (May be a command or in an expression).
         		point->functionName( parameters )
        (May be a command or in an expression).

        You can chain a series of operations

         		variable.function1(parameters).function2(parameters). ...

      Questions

        What are the predefined floating points

        Float and double are two predefined floating point data types. They have number expressed with a mantissa and exponent format. They are good for measurements but not for counting.

        Will we be translating UML diagrams in to code

        Yes. Demo in class of the Counter class.

        Will we be translating code into UML diagrams

        Yes.

        Would constructors be considered a type of function

        Yes. They are strange because they don't a returned type or a void and always have the same name as the class.

        What are constructors

        They are functions that create new objects. They are called when you declare the object, or when you use the 'new' operation. First the computer reserves the spce it needs (by looking at the attributes) and then it executes the commands in the constructor.

        Why do we need classes

        To control the complexity of a big program. It is the old divide and conquer technique. Divide up a complex programs into many simple classes. Connect them by passing messages. As a result the program will be be more maintainable -- and have fewer bugs.

        What is a class

        A class is a template ofr a set of similar objects. They all have similar data and will accept the same operations.

        Should my classnames all start with capital letters

        Yes.

        Does every body start class names with a capital letter

        Every body except the people who wrote the standard does it right. The standard has classnames like: string, vector, etc..

        How does a class work

        A class is a template describing an object. It includes a description of the data/attributes of the objects and the operations/functions that can be applied to these objects.

        A class's name is used to construct new objects that belong to the class. Then it is up to the objects.

        Why set classes to private at the start

        Just to remind ourselves of the rule that things a private at the start of a class unless until we write "public:".

        Be happy -- in Java we have to write private or public before every declaration!

        How does an object work

        Objects store there attributes/data in primary memory. You use an object in a program be sending it a message:
         		object_name . message (data)
        This works just like a function call.... but while the function executes the function has access to the attributes inside the object.

        Normally attributes a private and can not be accessed outside the object/class.

        Where would you find a library of available classes

        Start with the standard library. I have a summary [ ../samples/stl.html ] of the most useful -- mainly containers like vectors and deques. The Wikipedia entry [ C++_standard_library ] looks a useful place to learn. I also have a copy of the draft standard [ ../c++std/cd2/index.html ] (not easy to read but comprehensive). You can find other libraries on the web such as [ http://www.boost.org/ ] as an example.

        Can we make our own libraries

        Yes. Put them in a file with the right incantation and then #include it -- put the file name in double quotation marks. The incantations:
         #ifndef FILENAME
         #define FILENAME
        (at the top of the file)
         #endif
        (at the end of the file).

        What are inline functions

        If you include a member function's body inside its class declaration then it is said to be inline. Normal functions work because the computer jumps from the call to the start of the function and jumps back again when the function returns. An inline function is quite different. The compiler takes the call and replaces it with a copy of the function's body (with parameters substituted as needed).

        So inline functions are fast but take more space. Use them for small function bodies.

        Why would destructors be used in real-life program situations

        They are used for tidying up and recycling storage allocated by 'new' on the heap. Only used on large programs. Not needed in CSci201.

        What does the double colon operator do in a program

        It is used to refer to functions and data inside a function.
         		ClassName::functionName (....)
        refers to the function called functionName inside the class called className.

        Is there a reason why the book has word_word and wordWord identifiers

        Just history. The Smalltalk people started the wordWordWord convention. The Pascal people the word_word_word idea. C++ doesn't care. Most people use the wordWordWord format.

        Can we program in Dia like we can in C++\

        We cdon't have a compiler for UML. Dia doesn't even have a tool to output C++ code. Perhaps you should write it?

        What does cerr do

        cerr does every thing that cout does. But you can tak output sent to cout and redirect it into a file:
         		command > file
        But 'cerr' output doesn't go in the file, it is shown to the user.

        Use 'cerr' to output error messages and debugging print out.

        Where do I declare a variable so that it belongs to a function

        Put the declaration after the opening '{' of the function and before the closing '}'.

      Next -- Quiz 8 Lab 08 Project 07

      The Quiz will be on classes and objects -- prove that you know the parts of a class definition and work out what a program does that uses that class definition.

      The Lab will ask you to draw UML diagrams of the classes in Chapter 7.

      The project [ projects.html#P7 ] should fix (if needed) your Project 6 (create and use a function).

    Abreviations

  1. Gnu::="Gnu's Not Unix", a long running open source project that supplies a very popular C++ compiler.
  2. KDE::="Kommon Desktop Environment".
  3. OOP::="Object-Oriented Programming", Current paradigm for programming.
  4. SP::="Structured Programming", Previous paradigm for programming.
  5. TBA::="To Be Announced", something I should do.
  6. TBD::="To Be Done", something you have to do.
  7. UML::="Unified Modeling Language", [ 15.html ] (class notes on the UML and OOP).

End