Really simple question

Started by
2 comments, last by Fender148 23 years, 9 months ago
Ive been learning C++, but along the way Ive come across this typedef struct store_typ { int oreos //more stuff, whatever } store, *store_ptr How does this relate to making a structure or class for what Ive probably seen, using class keyword. Is this basically declaring a structure in C, how do the two words relate, store and store_ptr relate to store_typ? Thanks
Advertisement
First off, you need to know that in C, if you declared a struct, you had to type the keyword struct when declaring a variable of that type. For example:
struct store_typ{
int a;
};

struct store_typ s;

By using typedef, you are essentially setting up a shortcut to typing ''struct store_typ''. Instead, you can use just ''store'' (if you do things as typed in your example). Similarly, ''store_ptr'' can be used in place of
struct store_typ* sp;
Instead of the above, you can type
store_ptr sp;

Essentially, you are just saving yourself some typing. Other than that, it really isn''t doing anything. You aren''t creating a variable of that type, you are just giving the type a new, more convenient to type name. I hope that makes sense and I hope I was clear enough to help you out.
A class and data structure are basically the same thing. The only real difference is that a class comes with constructors destructors (local functions that are called whenever a class of that type are created or destroyed).

when you see
typedef struct store_typ{int oreos;} store, *store_ptr; 


It defines a new type, similar to ''int'' or ''char'' defined as ''store'', and also, if you want to make it a pointer, ''store_ptr''... so that you could make the following declaration:
store safeway;// safeway automatically has the integer member variable called oreossafeway.oreos = 4;store_ptr* albertsons;albertsons->oreos = 3; 


There you go. The only difference is that in C++ you can go:
struct store{int oreos;};store costco;costco.oreos = 1; 

... and basically get the same effect (without the pointer).

In C++, however, you can also use classes, which do basically the same thing.
class store{public:int oreos;};store payless;payless.oreos = 7; 

... and get the same effect. The only difference is that all class member data default to private (couldn''t be changed or accessed), while structs are public. Also, classes will call a default constructor and destructor.

Hope that helps!

- Goblin
"In order to understand the full depth of mankind, you must first seperate the word into its component parts: 'mank' and 'ind'."
- The Goblin (madgob@aol.com)
thanks guys

This topic is closed to new replies.

Advertisement