question about classes

Jul 5, 2014 at 10:20pm
Will functions always go in public and variables or members always be in private?

Last edited on Jul 5, 2014 at 10:22pm
Jul 5, 2014 at 10:30pm
Well, they go in whatever you define them as. You use the keyword "public" for public, and "private" for private.

private:
1
2
3
4
5
6
7
//Private Var / Funcs

class CLASS{
private:
      int var1;
      void SuperFunc();
}

public:
1
2
3
4
5
6
7
//Public Var / Funcs

class CLASS{
public:
    int var1;
    void SuperFunc();
}


And I do like to make functions public, just for ease of use. But, I make variables protected, sometimes private depending on it's importance. Usually companies dislike it when you make variables public. I am pretty sure it is a security thing.


In javascript and C# (just telling you fun-facts / random info) you can do define the variable / function with the keyword, like static or const
Ex:
1
2
private int var1;    //This variable is private.
public int var2;         //This variable is public 

Jul 5, 2014 at 10:35pm
So i want to get this straight. Public- you can use it in main. Private- you can use it in your class but not in main. Am i right to assume that?
Jul 5, 2014 at 10:37pm
@darkness
Yup, pretty much that.

Just that you can use public variables/functions anywhere in your program where an instance of that class exists.
Jul 5, 2014 at 10:41pm
Sorry, I didn't explain correctly. Public members can be used anywhere at anytime. Private members can only be used inside the class. Public can be used with any function, not just main, as long as you are programming correctly with objects. Think of it this way:

You are in elementary school, and the teacher has classroom supplies. You can use them anywhere in the room, but if you take it out of the room, you get an error (in trouble). But, her bookshelf has books you can sign out and take anywhere in the school.

Hope that can help
Jul 5, 2014 at 10:54pm
@AceDawg That makes a lot of sense. Thank you so much.
@gaius
What you mean by instance of that class? I have heard people saying instance of a class but i never really understood it. By instance, do they mean the name of the class?
Last edited on Jul 5, 2014 at 10:55pm
Jul 5, 2014 at 11:09pm
An instance of a class is usually just an object to the class.
Jul 5, 2014 at 11:14pm
OHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH dam thank you so much ace. You were a big help.
Jul 5, 2014 at 11:30pm
No problem
Jul 5, 2014 at 11:34pm
You can learn more about where things "should" go by googling around "encapsulation".
Topic archived. No new replies allowed.