Expert C Programming

(Jeff_L) #1

Software Dogma


The Key Idea: A Class


A class is just a user-defined type with all the operations on it.


A class is often implemented as a struct of data, grouped together with pointers-to-functions
that operate on that data. The compiler imposes strong typing—ensuring that these
functions are only invoked for objects of the class, and that no other functions are invoked
for the objects.


The C++ class accomplishes all this. It can be compared to a struct, and indeed can be conveniently
implemented as a struct. The general form is:


class classname {


availability: declarations


...


availability: declarations


};


Availability


The availability is a keyword that says who can access the declarations that follow. The availability
will be one of the following:


public: (^) The declarations that come after are visible outside the class and can be set, called, and
manipulated as desired. It's preferred to not make data public. This is because leaving
data private keeps the metaphor complete: only the object itself can change things;
outside functions have to use member functions, which ensures the data is only updated
in a disciplined way.
protected: (^) The declarations that come after are visible to functions inside this class, and to
functions in classes derived from this class.
private: (^) The declarations that come after can only be used by the member functions of this
class. Private declarations are visible outside the class (the name is known), but they
are not accessible.
There are two other keywords, friend and virtual, that affect availability. These keywords apply
to individual declarations, rather than whole groups of them as the ones above. Unlike the other three
availability controls, friend and virtual are not followed by a colon.
friend (^) This says that the function is not a member of the class, but can access private and
protected data just as though it were. A friend can be another function or another class.
virtual (^) We have not yet covered the concepts that motivate this, so we'll postpone explaining it till

Free download pdf