TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: MIKE WALKER
from: KURT KUZBA
date: 1998-04-08 11:35:00
subject: Private / Protected

MW>   Something that I am not quite clear on is the difference
MW>   between private and protected specifiers within a class.
MW>   Can someone explain the difference between these?
MW>   Also when would each be used?
   The public specifier allows the calling function access to
   the code and data members.
   The protected specifier allows the calling function to read
   the code and data members, but not to alter them.
   The private specifier does not allow the calling function to
   either read from or write to the code or data members.
class Foo {
public:
   int PubGetIt()       { return privbar;      }
   int PubSetIt(int a)  { return privbar = a;  }
   int pubbar;
protected:
   int ProtGetIt()      { return PrivGetIt();  }
   int ProtSetIt(int a) { return PrivSetIt(a); }
   int protbar;
private:
   int PrivGetIt()      { return privbar;      }
   int PrivSetIt(int a) { return privbar = a;  }
   int privbar;
};
//   Given the above class, Foo, then
int main()
{
   Foo Fb;
   int a;
   Fb.pubbar = 1;        // this will work
   a = Fb.pubbar;        // this will work
   Fb.protbar = 1;       // this will not work
   a = Fb.protbar;       // this will work
   Fb.privbar = 1;       // this will not work
   a = Fb.privbar;       // this will not work
   Fb.PubSetIt(1);       // this will work
   Fb.ProtSetIt(1);      // this will work
   Fb.PrivSetIt(1);      // this will not work
   a = Fb.PubGetIt();    // this will work
   a = Fb.ProtGetit();   // this will work
   a = Fb.PrivGetit();   // this will not work
   return 0;
}
   As you can see by this demonstration, private members are
   readily accessible to public and protected members of the
   same class. Protected members are available to calling
   functions, but cannot be altered. Private members are
   entirely safe from the calling function.
   Any functions which manipulate the data and require a
   specific range in which to operate should be private.
   Any data which should not be manipulated from outside the
   class, to protect against violating array boundaries or
   variable range boundaries, should be either protected or
   private. The private and protected specifiers allow you
   to encapsulate your data and keep it within safe parameters.
   There are other considerations, too, when heredity is to
   be involved.
> ] Once you know me better, you'll like me even less...........
---
---------------
* Origin: *YOPS ]I[* 8.4 GIG * RA/FD/FE * Milwaukee, WI (1:154/750)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.