-
class access
HI guys.
need some help on data abstraction and why its so important the following prog contains a class with a private data member I know only the member function can access this data but if this prog was all in ordinary functions or even just one main function and I choose not to access the array I wouldn't, Is it mainly used for one programmer hiding something from another working on the same program and if this is the case the chances of others knowing my identifier names would be rare.
I aks these questions because I'm just learning and therefor program on my own.
#include<iostream.h>
#include<conio.h>
class programmer{
char programmers_only[50];
public:
programmer(); // default constructor(no arguments)
void non_programmers() // inline function
{
cout<<"No access to programmers information";
}
};
programmer::programmer() // default constructor definition
{ // Not considered inline by the compiler
strcpy(programmers_only,"private info: pointer hold addresses of objects");
}
int main()
{
programmer anthony; // call default constructor definition of object anthony
// doesn't have initializing values
anthony.non_programmers();
cout<<anthony.programmers_only; // Error no access to private data
getch();
return 0;
}
// The only time a constructor is called is when the programmer declares an instance
// of the class which will automatically call the constructor, The only time a destructor
// is called is when an instance of a class is no longer needed, when the program ends
// or when its memory is deallocated.
thanks for the help.
-
private data members are a way to protect yourself from yourself. Similar to the const keyword, which makes (mostly) sure that nothing else changes your data, private data members can't be accessed by anything you don't want to access them by accident and that will save you a lot of time debugging wierd problems later.
Another reason data hiding is so important is when others begin to use your classes. If you decide to update the class then how the other people use it doesn't matter because they will never have used it other than how you intended. You define an explicit interface that is public and then a private implementation that the interface calls.
Code:
class Foo
{
int data;
void accessData();
public:
void interface(){ accessData(); }
};
The interface has access to the class, but the user of the interface has access only to the interface and can't use the class improperly without rewriting it.
If you're writing a toy class that will only be used once by you then public members are okay. Otherwise make your members private and define an interface for usage.
-Prelude