I'm an amateur C++ programmer, but I have learned a few things about 
C++ programming.  As far as relating public and private variables and 
functions, I've learned you use public functions to access private 
data (variables) so the programmer may control how the data is 
accessed by the user, otherwise public variables are subject to be 
changed by the user and your program no longer behaves as you want.  
Best thing to do is to define and implement public functions that 
access those  fields that should be private that you want to change.  
You're leaving yourself open to malicious users if you have public 
data in your classes.  Remember use public function to access private 
data to preserve encapsulation of data within your C++ application.  
There are numerous C++ tutorial sites that explain data encapsulation 
more fully and some are listed in the links folder of this group.  
Good programming!

--- In [email protected], "John Gunnarsson" 
<[EMAIL PROTECTED]> wrote:
>
> Hi,
> 
> I'm looking for you input on whats the best practice for public 
fields
> in a class.
> In other high level languages (such as C#) it usually exist a 
property
> get/set mechanism. I have seen implementatons using get/set methods
> for reteriving and setting private values in a c++ class, which i 
find
> totally okay for primitives as int, strings etc.
> 
> One thing that I don't know how to handle is where a class have one 
or
> several class instances inside itself (as private fields) but should
> be accessable from public.
> 
> Ofcource you could have the get/set methods but then you have to get
> and set the complete internal state of the class, where it's very
> probably that you only would like to change one single field.
> 
> What is the best practice to solve this? Is it okay to have publci
> fields in a c++ class without get/set methods?
> 
> I could of cource implement a get function that returnes a pointer 
to
> the class, and via that pointer I could change the internal state on
> the second class. If my explanation is messy consider this code 
(semi
> pseduo)
> 
> class Address
> {
>    public:
>     string getCity();
>     string setCity(string const &city);
> 
>    int getId();
>    void setId(int const &id);
>   private:
>     string name;
>     int id;
> 
> };
> 
> 
> class Order
> {
>   public:
>      /*
>        what to do here? implement get/set functions for the fields 
below,
>        or it it okay to declare the payer and shipto members here?
>     */
> 
>   private:
>     Address payer;
>     Address shipto;
> };
> 
> //John
>


Reply via email to