Inside my class I need to use a structure. This structure will be unique for each class instance. So, the point is: should I use a variable or a pointer ?
Everything inside a class will be unique for every class instance.
I would declare the structure as a normal variable. Unless C++ has some funny exceptions I haven't had the chance to experience using a normal variable structure should work.
I'm pretty new myself. I have never had to use a structure inside a class so I don't know how to declare a new structure.
I will look around and try to find out but someone more experienced than myself will probably have to answer your last question.
EDIT: I'm not sure if this is what your looking for but here is a little example of using a structure inside a class.
#include <iostream>
usingnamespace std;
struct a_struct
{
int b;
};
class a_class
{
public:
a_struct something;
};
//To use it I would go like this
int main()
{
a_class abc;
abc.something.b = 10;
cout << abc.something.b << endl;
system("pause");
return 0;
}
Suppose I have a structure called MyData. The following code:
1 2 3 4 5
class Test {
MyData data;
public:
Test() { data = (MyData *) malloc(sizeof(MyData)); }
}
is right or wrong ? Now I think it's wrong because data is not a pointer, so it doesn't need to be malloced because it already has the amount of memory allocated to it (the size of MyData).
This, to be right should be:
1 2 3 4 5
class Test {
MyData *data;
public:
Test() { data = (MyData *) malloc(sizeof(MyData)); }
}
Your class can have an object as in MyData or a pointer as in MyData*.
If you are using a pointer, your should initialise and deinitialise with the constructor/descructor. You'll also need to define a copy consturctor and assignment operator as the defaults will just work on the pointers, not the objects pointed to.
The style you chose will depend on what you're doing.