Expert C Programming

(Jeff_L) #1

Compared with C, it seems you have to shout at the C++ compiler to invoke it. Compile,
and run the a.out file. Congratulations—it may not do much, but you have successfully
written a C++ class.


The implementation of a member function, when placed outside its class, has some special syntactic
sugar on the front.


The syntactic sugar :: says "Hey! I'm important! I refer to something in a class."


So instead of looking like the regular C function declaration,


return-type functionname(parameters) {...};


member functions (also known as "methods") will have the form


return-type Classname :: functionname(parameters)


{... };


The :: is called "the scope resolution operator." The identifier that precedes it is a class to look in. If
there's no preceding identifier, it means global scope. If the implementation of peel() is put inside
the class, it might look like this:


class Fruit { public: void peel(){ printf("in peel"); }


slice();


juice();


private: int weight, calories_per_oz;


};


And, if you separate it out, it will look like this


class Fruit { public: void peel();


slice();


juice();


private: int weight, calories_per_oz;


};


void Fruit::peel(){ printf("in peel"); }


The two approaches are semantically equivalent, but the second is more usual and provides benefits
for organizing the source more cleanly using include files. The first approach is commonly used for
very short functions, and it makes the code automatically expand in line instead of causing a function
call.


Programming Challenge

Free download pdf