CS 202 Fall 2013  >  Notes for Tuesday, September 10, 2013

CS 202 Fall 2013
Notes for Tuesday, September 10, 2013

CS 201 Recap (cont’d)

Some more important terminology.

See usevector.cpp, usestruct.cpp, and usepointer.cpp for examples of code using std::vector, a struct, and a pointer, respectively.

Classes I Day 1 [13.1–13.5]

Procedural vs. Object-Oriented

We move from procedural programming to object-oriented programming (OOP), which centers around objects (“smart data”). We encapsulate data and code together.

Other terms:

Defining a Class

Defining a class.

[C++]

class MyClass {  // MyClass is name of class; note the capital
public:
    void foo();  // Public member function foo, defined here
    {
        ...
    }
    void foofoo() const;
                 // const when function does not modify an object
                 // foofoo is defined later
    ...
private:         // Make member variables private!
    int m_bar;   // Private member variable m_bar of type int
    ...
};  // End of class definition; don't forget the semicolon


// Definition of member function foofoo
void MyClass::foofoo() const  // "MyClass::" before function NAME
{
    int x = m_bar * 3;  // Inside a member function,
                        //  access member variable by its name
    ...
}

Terms:

Creating & Using an Object

A class name is a type.

[C++]

MyClass x;  // x is an object of type MyClass

Call member functions on an existing object using the dot (“.”) operator.

[C++]

x.foo();

Put const before the type to declare an object that cannot be modified (only const member functions can be called).

[C++]

const MyClass cx;  // cx is an object that cannot be modified

cx.foo();          // WILL NOT COMPILE! foo is not const
cx.foofoo();       // No problem

Objects can be accessed by pointer.

[C++]

MyClass * y = &x;
y->foo();

Accessors & Mutators

[C++]

class Num {
    public:
        int getN() const  // Accessor ("get function")
        {
            return m_n;
        }

        void setN(int n)  // Mutator ("set function")
        {
            m_n = n;
        }

    private:
        int m_n;
};

Header & Source Files

We often put a class definition in a header file, named based on the class name (class Abc in header abc.h). Some member functions—usually the long ones—might be defined in a separate source file (abc.cpp).

The source includes the header. Any other file that uses the class also includes the header.

Example Class

See clock.h and clock.cpp for an example class (Clock). See clock_main.cpp for a simple C++ program that uses this class.


CS 202 Fall 2013: Notes for Tuesday, September 10, 2013 / Updated: 10 Sep 2013 / Glenn G. Chappell