user7008889
user7008889

Reputation:

How to initialize const size array in constructor without explicitly stating the size in class declaration?

I need to do something like

class foo {
  foo();
  int a[];
}

Further in cpp-file:

foo::foo() : a{1,2,3,4} {}

Peculiarities:

  1. C++98 standard

  2. array is not int, initializing list is much longer. Though its values are known at compile time, they can change from time to time

EDIT: Another option is also suitable, when new[] is used for memory allocation, but, again, it is undesirable to state the array size explicitly:

class foo {
  foo();
  int * a;
}

Further in cpp-file:

foo::foo() {
  a = new[]; // impossible
  // filling the array with values
}

Upvotes: 1

Views: 247

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477454

You cannot do that: The size of the array is part of the type of the array, and hence of the class. The constructor is also part of the class. The class needs to exist first before you can call constructors, so the constructor call cannot influence the class definition.

Upvotes: 1

Related Questions