Sams Teach Yourself C in 21 Days

(singke) #1
you can access all of these members because they are public by default. This means that
we can access any of these three structure members in the following way:
obj_name.firstname
obj_name.lastname
obj_name.formatted_name()
withobj_namebeing the name of the variable (object) that was declared using the name
structure. Because these are public, you can call any of these three members from any-
where in your program.

Creating Private Data
Structures are publicby default, and classes are privateby default. Private members of
a class cannot be accessed from anywhere in your programs. They are private. This
means they can only be accessed by member functions within the class.
If you declared a class such as the following:
class name {
string firstname;
string lastname;
string formatted_name();
}
by default all of the members are private. You cannot access firstnameorlastname
except from member functions within the nameclass. This means that only the member
functionformatted_name()has access to these two variables. The following code would
result in an error:
class name {
string firstname;
string lastname;
string formatted_name();
};
int main(int argc, char* argv[])
{
name myName

myName.firstname = “Bradley” //Error, data is private
...
...
return 0;
}
The error in this code is due to the fact that myNamecontains only private data members.
Only other members within the object would be able to use the three members.

676 Bonus Day 3

38 448201x-Bonus3 8/13/02 11:19 AM Page 676

Free download pdf