0

In C++, why does the following struct definition reports "field has incomplete type" error:

struct Element {
    Element* prevPtr = nullptr, nextPtr = nullptr;
};

while the second definition works fine:

struct Element {
    Element* prevPtr = nullptr;
    Element* nextPtr = nullptr;
};

It seems the second pointer cannot be defined together with the first pointer (separated by a comma). Why is that?

chaohuang
  • 3,965
  • 4
  • 27
  • 35
  • 1
    `Element* prevPtr = nullptr, nextPtr = nullptr;` defines a pointer followed by an instance. The `*` belongs to the variable not the type. `Element *prevPtr = nullptr, *nextPtr = nullptr;` – Retired Ninja Jun 19 '23 at 23:22
  • 2
    `using Element_ptr = Element*; Element_ptr prevPtr = nullptr, nextPtr = nullptr;`. However, the general guidance from many seasoned developers is to avoid defining more than one variable in a statement. – Eljay Jun 19 '23 at 23:25

0 Answers0