In my code, I want to create a dynamic array of objects. I don't know how many objects I want until the runtime, and the array's class has a dynamic variable array, so my objects can be of any size. Therefore, to make an array of them, I want to create an array of pointers as pointers are of a fixed size. Then, during runtime, when I know how many objects I will store, I want to malloc the memory needed to store the pointers. When I try mallocing, I get a linking error unless I define the array at the top of the .cpp file, even though it's already declared in the header .h file, and I am not sure why this is necessary.
My code: Maintest.cpp
#include <iostream>
#include "class.h"
#include "Maintest.h"
//Class** Maintest::testArray = NULL; //uncommenting this line fixes the linking error
void Maintest::createMany(){
testArray = (Class **) malloc(10 * sizeof(Class *));
}
int main(){
printf("hello");
}
Maintest.h
class Maintest {
private:
static Class** testArray;
public:
static void createMany();
};
class.cpp
#include <iostream>
#include "class.h"
Class::Class(int arg){
test = arg;
}
class.h
class Class {
private:
int test;
public:
Class::Class(int);
};