-2

The solution from the "duplicated from" question is to initialize the pointer after the class definition but I have found no success doing so. Trying to insert A B::AArray; or A B::AArray = new A[10]; gives me multiple errors including "conflicting declaration" and "cannot be initialized by a non-constant expression". I can't seem to find a way to define B::AArray anywhere in the code.

class A{
public:
    int Avar;
    A(int Avar = 0){this->Avar = Avar;}
};

class B{
private:
    static A *AArray;
public:
    static void setAArray();
};

int main(){
    return 0;
}

void B::setAArray(){
    A *data;
    data = new A[10];
    AArray = data; // <- delete this line and the program complies
}

This piece of code says I have an undefined reference to 'B::AArray' and won't compile. How do I resolve this if I want a static pointer to an array of class A objects in class B?

Note: my class does not use multiple files currently and everything is under one .cc file

Community
  • 1
  • 1
Potato Salad
  • 37
  • 1
  • 5
  • 2
    Did you try adding `A* B::AArray = nullptr;` after the definition of `class B` (just like the "'duplicate from' question" says) and later in `B::setAArray` to redirect the pointer? – Kiril Kirov Jan 23 '17 at 11:53

1 Answers1

0

Given the content of the previous duplicate, a more detailed working sample of the OP code follows.

The definition needs to outside the function;

class B{
private:
    static A *AArray;
public:
    static void setAArray();
};

A* B::AArray = nullptr; // define and initialise with a suitable default

int main(){
    return 0;
}

void B::setAArray(){
    A *data;
    data = new A[10];
    AArray = data; // initialization...
}

The AArray = data; is not a definition, it is an initialization.

Sample listing.

Niall
  • 30,036
  • 10
  • 99
  • 142