Hi,
I have completely learned the languages "C" and "Java".
In Java there were only Classes but NO Structures. And now
when I am learning "C++" language, I am a little bit confused:
Why, when there exist the Classes in C++, should I use Structures?
Or I will ask in another way: it's good to use ONLY Classes and the
Structures DON'T use ANYWAY?
You can use both. In C++ structures are synominous with classes with one major difference.
In C++, classes default to private members. Meaning that everything in the class definition prior to your first public or protected declaration will be private.
Structures, however default to public.
My personal prefference is that I use structures when I need a data type that has no methods and classes when I need a data type that does.
e.g.
1 2 3 4 5 6 7 8 9 10 11 12 13
struct ingredient {
int qty; // these are public
string name;
};
class recipe {
string name; // these are private
vector<ingredient> ingredients;
public:
void add_ingredient (ingredient item); // these are public
ingredient get_ingredient (int index);
};
So you see, I make ingredient a struct cause I plan to access it's members directly, where-as i make recipe a class so as to use it's member functions. But this is just my prefference. Others might only use classes, or may use structs in different situations.
so to re-iterate, in C++ Class and Struct are interchangable. Structs default to public. Classes default to private.
I think he was replying to the wrong thread. Not sure, but his answer makes sense when reading the other thread.
Edit: nvm.. just realized he is the author of the other thread.
And yes, Mayflour, in C there are structs that don't have constructors (or methods if i recall correctly) and in Java there are classes but no structs.. but in C++ we have structs and classes and they are both the same thing, with the exception I pointed out above.
So in C++ you can have structs with constructors and methods. I just usually perfer to not use them. If i need methods, i'll use a class instead. but that is just my perferance.