22.2 Implicit arguments


Suppose that SomeClass is a class whose prototype includes a member _val and two functions SomeFunction and SomeOtherFunction .

 class SomeClass  {      int _val;      int ValSquared(){return _val * _val;}      int SomeFunction(int input);      int SomeOtherFunction(int first, int second);  }; 

Now if K is an object of type SomeClass , then the value of, let us say, K.SomeFunction(17) will depend on (a) the argument 17, (b) the function definition of SomeFunction , and (c) the contents of the object K. K is an 'implicit argument' to this function call.

When you write out the code for SomeFunction , you play on the fact that you have an implicit argument to the function, even though you don't explicitly show it. Thus the code for SomeFunction might look like the following.

 int SomeClass::SomeFunction(int input)  {      return SomeOtherFunction(_val, ValSquared());  } 

This means that K.SomeFunction(17) would be evaluated as K.SomeOtherFunction(K._val, K.ValSquared()) , with K.ValSquared() being evaluated as K._val * K._val.

The initially bewildering C++ this is used inside a function as a way to refer to a pointer to the implicit calling object. The object itself is *this , that is, the object that this is pointing to. Remember that if p is a pointer, then *p 'dereferences' the pointer to stand for the actual object the pointer points to.

If we wanted to, we could have put this->_val or *this._val in place of _val inside the SomeClass::SomeFunction definition. But we don't want to, as this would be defeating the whole beauty of C++'s concise syntax.

In general, when you are looking at some unfamiliar code and you see a function call inside a class method definition, you can usually expect that any unfamiliar function you see being called 'naked' is in fact a member of the class. When we speak of a function being called 'naked,' we mean that it's being called without any explicit calling object in front of it, no caller .or pcaller-> in other words. If you don't find the function listed as a method of the class, it may be that it's a method of the class's parent class.

Now and then we want to explicitly avoid using a class's own version of a member function, preferring to use a global function with the same name . In this case, we put the symbol :: in front of the function name. The name of this symbol, by the way, is the 'scope resolution operator.' We sometimes use it in MFC programming, as most of our MFC class methods have the same names as some global method. In order to make the code easier to understand, when we use any global function at all we will habitually put the :: in front of its name just to remind ourselves that it isn't a member method of any class.



Software Engineering and Computer Games
Software Engineering and Computer Games
ISBN: B00406LVDU
EAN: N/A
Year: 2002
Pages: 272

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net