Reputation: 683
I am working on a program and need to make an array of objects, specifically I have a 31x1 array where each position is an object, (each object is basically built out of 6 ints). Here is what I have but something is wrong and i could use some help thank you.
31x1 struct header"
const int days=31;
struct Arr{
int days;
int *M;
};
typedef Arr* Array;
31x1 matrix constructor:
void constr(){
int *M;
M = new Expe[31]; // Expe is the class
class header:
class Expe {
private:
//0-HouseKeeping, 1-Food, 2-Transport, 3-Clothing, 4-TelNet, 5-others
int *obj;
}
Class object constructor:
Expe::Expe() {
this->obj=new int[6];
}
help please... because i`m pretty lost.
Upvotes: 0
Views: 246
Reputation: 1452
You should not use new
unless you have to. You're dynamically allocating memory which you have to manually delete afterwards.
Instead, use statically allocated arrays:
struct Arr{
int days;
Expe M[31];
}
This way you don't need to construct M, it automatically is filled with 31 Expe objects. Same goes for the int array in Expe.
(Hint: structs and classes are almost identical. They only difference is that default visibility for structs is public. Apart from that, structs can have member functions and constructors just like classes do.)
If you have to use dynamic allocation you should follow this notation:
X* variableName = new X[size];
...
delete[] variableName; //Be sure to get rid of unused memory afterwards.
Pointers should only be of type int*
if you want to store an array of ints in it.
You can also use const int
s for array size declarations. So this is valid:
const int size = 5;
int X[size];
You can use this to get rid of the "magic numbers" in your code.
Typedefs like typedef Arr* Array;
are typically used in C, not in C++ so much. There is hardly any situation where you would need to typedef something like this.
If you post your entire code we might provide better help. It seems that you don't only have one or two errors in your code, but also some fundamental understanding.
Upvotes: 3