+ 1
How can I make an array attribute without predefined size? (God's language++)
I need an object with an array as an attribute, the array size would be defined during the creation of the object (In the class constructor). I've no idea how to do that, would I need to use pointers? Using C++.
3 ответов
+ 3
You can use pointers
or
you can use vector, that is much simpler and is more preffered in C++.
For example:
//with pointer:
class A{
int *pData;
public:
A(unsigned size):pData(new int[size]){}
~A(){ delete[] pData; }
};
//--------------------------------------------------
//more preffered way
//with vector (vector header must be included)
class A{
std::vector<int> data;
public:
A(unsigned size):data(size){}
};
+ 2
just be certain to include the delete destructor in your class when dynamically allocating via pointer. otherwise you will introduce memory leaks.
0
andriy kan Yes, this is what I searched for, pointer solution seems more interesting for the case.
Jayakrishna That was not the problem.