Advertisement

Classes, and the "correct" way to access private variables

Started by June 09, 2002 05:07 PM
10 comments, last by Peon 22 years, 5 months ago
Heya all,

As a fairly experienced OO programmer I just thought I'd share some of my revelations.

Basically, accessor functions are good for two things.

1. If you plan on changing the way the internals work often.
2. There is more happening than might be immediately obvious, that is there is "extra" functionality.

Here's an example.

struct CSquare{    float height;    float width;    float area;};  


In the above example you have three fields, but you'll notice that one of them is based solely upon the other two. This would be an example of when accessor functions would be GOOD. It is a demonstration of rule #2 above...continuing the example:

CSquare square1;square1.height = 10;square1.width = 10;square1.area = 100;// if now at a later time I do the following,// without changing the area field, I've got a problemsquare1.width = 5;  


The better solution is to put the height and width into set/get functions, even though they seem redundent...it prevents stupid mistakes.

One last example...suppose I have the following class.
Class CPoint2D{    public:        float GetX();        float GetY();        SetX(float arg);        SetY(float arg);     private:        float x, y;};  


The above is an obvious example of when NOT to use set/get functions. The reason being is because there is no "extra" calculations going on by setting either x or y, and even more than that...the functionality of a 2D point will most likely NEVER change.

If you follow the 2 rules above, you should find that public vs. private becomes a bit more obvious.

Best Regards,
Jeromy "Maverick" Walsh
------------------------
"The question isn't how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" -Boondock Saints

[edited by - jwalsh on June 11, 2002 3:35:43 PM]
Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
Chronicles of Elyria (An In-development MMORPG)
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints
Excuse me if this is repetitious(i only read the question), but there is a basic solution: make the tank data public, not private.
I tried to code, but the compiler kept giving me an error: stupid coder alert.hpotter2

This topic is closed to new replies.

Advertisement