Main Menu


Sponsored Links

  


  
  
Web Cartoon Maker: a Fun Way to Learn C++ Contents Previous Next

Converting Functions to Methods

In previous section we defined a class Point and wrote a function named Reflect . To call this function we had to pass a Point object as a parameter. To make Reflect into a member function we should eliminate this parameter and place it inside the class definition.

As a result, inside the function we no longer have a parameter named P . Instead, we have a current object, which is the object this function is invoked on. And we can access all its instance variables by their names without using a dot symbol.

class Point

{

public :


double dX, dY;


void Reflect ()

{

double dTemp = dX;

dX = dY;

dY = dTemp;

}

};

In order to invoke the new version of print, we have to invoke it on a Point object:

Max.SetPos ( MyPoint.dX, MyPoint.dY );

MyPoint.Reflect ();

Max.GoesTo ( MyPoint.dX, MyPoint.dY, 5 );

Similarly we can convert GetReflectedCopy to a method:

class Point

{


Point GetReflectedCopy ()

{

Point Result;

Result.dX = dY;

Result.dY = dX;

return Result;

}


};

Remember, that GetReflectedCopy as a function used to have parameter From ? And for safety we added a keyword const to indicate that we are not going to modify this parameter? It is also possible to indicate that we are not going to modify an object and its instance variables a member function or method was invoked on. The same keyword const can be placed after a member function declaration:

class Point

{


Point GetReflectedCopy () const

{

Point Result;

Result.dX = dY;

Result.dY = dX;

return Result;

}


};

Again, keyword const does not change the behavior of a method. It just makes this method safer. If you try to change an instance variable ( dX or dY ) by an accident, the compiler will complain and you will be able to avoid problems later.


Contents Previous Next
  
News

New Tales Animator Video by Alan Sturgess

Alan Sturgess shared an excellent video he made using Tales Animator! You can still download Tales Animator here. Unfortunately it is only available for Wi

...

Simple Online Character Designer

There is a prototype of simple online character designer available HERE. It is only a prototype, it does not contain many pieces yet but it can already generat

...

Book is updated

Now our book "Web Cartoon Maker: A Fun Way to Learn C++" is fully in synch with WCM 1.5! It is available for download and online reading HERE.

...

Web Cartoon Maker 1.5 is here!

Web Cartoon Maker 1.5 is finally here! You can download it HERE! Here is what was updated in version 1.5: Web Cartoon Maker Desktop Edition is now fully standal

...

read more news...


Poll