Quote:Original post by Meta Adam
Yea, but i dont understand why it couldnt just be:
*** Source Showing data members as public ***
Well, it _can_ be. That's what makes the concept difficult. I was a longtime C programmer when I started to learn C++. The first thing that just baffled me was why you wanted to add all this complexity.
Why did these classes need methods? I have written functions and they work fine.
What's with this access protection stuff? I have declared variables and they work fine.
Making the data that a class holds private is a matter of methodology, not syntax. In other words, the code you posted works fine. However, what programmers discovered over the years of building massive applications with "top-down" languages like C was that it was really hard to manage and debug the code base.
The idea of C++ and being Object Oriented in general is that you can break your program's functionality into classes. The classes control their internals (the data) and it exposes functions that others can use to operate on them.
The string example given above is a classic. If you wrote a class that held a string for you, you would do so because managing character buffers is a pain, and prone to bugs. So you write this class, but if you simply left out the data in "public" for anyone to mess with, then you can't ever be certain the data in the string class still has any integrity. After all, any other class or function or method could come along and change the length of the string without changing the string data to match.
Instead you write public methods that make sure all operations performed are valid. They do some sanity checking, change the internal data, and will give it back to you with public accessors like get.
In a small class, the point can not be driven home. Your example makes the whole process of having private data with public accessors seem like extra and unnecessary work. That's why I balked so much when I read my first C++ book. The examples weren't compelling enough.
I am not belittling your example. Rather, I am reliving the feelings I had when I first read the chapter on data encapsulation in my first C++ book and said "What is this useful for again? It seems like more work."
That's the best answer I can give. The code you post works. However, it does not encapsulate the data. So any function that wants to change the dog's height, weight, or age can do so without anything to stop it. And if that's okay, then public is fine.