Maybe a stupid question

Maybe this is a stupid beginners's question:

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 ?


Thank you.
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.

Ok, thank you. But - I'm comming from C - I need to malloc it, right ?
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

using namespace 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;
}
Last edited on
I think I figured out with your help.

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)); }
}


I'm right about this ?
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Test1
{
	MyData	data;

public:
	Test1()
	{
	}
};

class Test2
{
	MyData*	pdata;

public:
	Test2()
		:	pdata(new MyData)
	{
	}
	~Test2()
	{
		delete pdata;
	}
	Test2(const Test2 &n)
		:	pdata(new MyData)
	{
		*pdata = *n.pdata;
	}
	Test2& operator=(const Test2 &n)
	{
		if (this != &n)
		{
			*pdata = *n.pdata;
		}
		return *this;
	}
};
Ok, I got it. Thank you guys for your support.
Topic archived. No new replies allowed.