Quote:
Originally posted by name_in_use450
I am by no means an expert or even close to one; but I have been doing regular C for a while. I am fairly new to C++ though (and object-oriented in general) and am very confused about the following:
public, private, protected
class
the '::' as opposed to just ":" or "."
What is the difference and/or explanations of these.
thanks.
|
A class, very simply put, is a struct : it contains variables (which are called members in this contexts) and functions, called methods. However, it's how you access them that really makes a change.
As for public et al, I like to use to following analogy. Think of your house as a class.
Code:
//this code will NOT compile ;)
class House {
public:
mailbox myMailbox;
protected:
tv myTV;
private:
safe mySafe;
};
Think about it. Anybody, friend, foe, or even an unknown person can use your mailbox, put stuff in it, or take stuff from it (well that wouldn't be very honest, but hey.) Public members/methods can be accessed by anything, from any context.
Private members/methods are like things you put inside your safe. You wouldn't let anybody just barge inside your house and look inside it, heh ? Well private methods just serve that : anything you DON'T want users of that class to use should be marked private. Only other methods of the class can access private stuff.
Protected is the middle point : only some parts of your program can access it. What parts, you ask ?
- The class itself
- Functions/classes marked as
friend
- Objects that inherit from that class
Your TV is an excellent analogy. You wouldn't let anybody and everybody in to watch TV but if a friend came by and asked to watch football, you probably would let him use it.
Inheritance and friend functions are another topic entirely. In C++, members are private by default. Interestingly, you can use public, private and protected inside structs in C++, except they are public by default.
As for the '::', I was confused by it too. But it's simple, really. Its purpose is to explicit where the function is defined. Look at the following code:
Code:
class myInteger {
private:
int myInt;
public:
int changeInt(int x);
};
int myInteger::changeInt(int x) {
myInt = x;
}
The last lines mean "define myInteger's changeInt method". Otherwise, your compiler would think it's a simple function, unrelated to your class.
HTH.