Differences between structs and classes

Please correct me if I'm wrong.

struct objects can be used to store multiple data in a group.

class objects are similar. They contain multiple data in a group, with different levels of acess. The tutorial here says:
private members of a class are accessible only from within other members of the same class or from their friends.
protected members are accessible from members of their same class and from their friends, but also from members of their derived classes.
Finally, public members are accessible from anywhere where the object is visible.

I'm not entirely clear on this. Could someone put it simpler, somehow?

The other thing is that class 's can contain functions. class::function can be used to edit functions inside classes.

Am I missing something? I want to make sure I get this before I go on.

Thanks!
There's no difference between the struct and class keyword, except that members are private by default when using class and public when using struct.

Dunno what you don't understand about the access specifiers, but to reiterate:
private: only the own class member functions have access.
protected: like private, but derived classes have access too.
public: everyone has access.
You've got it essentially correct. A private member means that it's not visible outside of the object. So:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
class MyClass {    // define class
private:
	int i;
public:
	int getI () {return i;}
};

MyClass myObject; // create an object of this class type

cout << myObject.i; // won't work; i is private to the object
cout << myObject.getI(); // will work; function is public.
}


This is the convention for C++: data is private, and (most) routines are public. This is intended as a gating mechanism for access to the data: one can only access data through the routines supplied by the class author.

Protected is a little different: any inherited classes have access to a protected object. If you're just starting out, you may want to ignore this for now.

Not sure about your statement:

class::function can be used to edit functions inside classes.


Functions can be used to *access* *data* inside objects. One generally doesn't edit functions on the fly.

Hope this helps.

Last edited on
Topic archived. No new replies allowed.