-
Here is a real world scenario that may best answer your question.
ABC
Code:
class Image
{
public:
virtual void *getPixels() = 0;
virtual void setPixels(void *pxls);
virtual size_t getWidth() const = 0;
virtual size_t getHeight() const = 0;
virtual void setWidth(size_t width) = 0;
virtual void getHeight(size_t height) = 0;
};
Now you have the construct for what any Image would look like. From here out, all your derived classes may do things entirely different. For example, you may have a JPEGImage class which stores a JFIF header and has to decode data in order to getPixels(). Or you may have a BitmapImage that is just a fat array of pixels that are ready to be dumped as-is.
Since you have a reliable interface that is consistent across the board, it does not matter how things are dealt with internally. Right? That is more what encapsulation is about rather than "hiding data" as some may say. Its not a matter of hiding so much as its a matter of I do not care how you store your pixels, I just need to see them so I can draw to the screen.
-
Master5001, that is an excellent example - we do not want to know how pixels are stored in the image, just a way to get the pixels out.
--
Mats
-
Why thank you Matt. I woke up with a little extra spring in my step this morning. Perhaps there is hope for me yet.
-
It is also useful for things like this:
Code:
class Circle{
private:
double radius;
public:
double getCircumference(){
return PI*radius*2
}
}
This can then later be changed to a variable that stores the circumference instead, without changing the API of the class.
-
I think one of the main reasons I've shyed away from templates is because the syntax is just so freaking ugly.
I simply cannot read that code.
-
To which code are you refering? Neither mine nor King Mir's were templates. Mine is an abstract base class and Mir's is an example of applying a principle.
[Edit]Ah nevermind. You were refering to Elysia's template. Templates are useful. Simply using typedefs will entirely eliminate most of what you find visually unappealing about them. I suggest you learn how to read them though. Elysia's coding style is satisfactory and the code doesn't do anything whacky and hard to understand.[/edit]
-
>I think one of the main reasons I've shyed away from
>templates is because the syntax is just so freaking ugly.
Templates don't scale well when it comes to complexity. Simple uses are simple, but advanced uses are painful.