[cs13001] Arguments in member functions

Mikhail Nesterenko mikhail at cs.kent.edu
Wed Dec 12 19:05:27 EST 2012


> 
> I was wondering, regarding this part of code:
> 
> class Bicycle
> {
> public:
>           char get_color();
>           int number_of_speeds();
>           void set(int the_speeds, char the_color);  // <<<<< This part
> private:
>           int speeds;
>           char color;
> };
> 
> I wanted to ask, why are the arguments in void not the exact same
> name as the attributes in the private part of the class?  How does
> the void function know which variables to plug in the parameter?
> What if there were 2 int variables instead of 1, which one would it
> choose?

Let us consider the implementation of this function:

    void  Bycycle::set(int the_speeds, char the_color){
    	    speeds = the_speeds;
	    color = the_color;
    }

The parameters of this method (member function) are used to initialize
or update the corresponding attributes of the object on which the
method is invoked. Hence, on the one hand, the parameter's identifier
has to differ from the corresponding attribute (otherwise there is a
name collision in the member function). On the other hand, it would be
nice if the name of the parameter reflects it purpose of initializing
the attribute.

In this program, the_ is added to differentiate the parameter
identifier from the attribute while the rest of the identifier is the
same. 

Note that matching the names of parameters and attributes is a
stylistic convention: it is not required by C++ syntax. The parameters
could be named as follows:

    void set(int a, char b);

But this program would be less readable.


Thanks, 
-- 
Mikhail


More information about the cs13001 mailing list