Set dimensions of stack-based array in constructor?

Started by
4 comments, last by SiCrane 14 years, 2 months ago
Is it possible to do something like this:

class Foo
{
  private:
    Bar[] mArr;
}

Foo::Foo(int dim) : Bar[dim] { }
Obviously that syntax is invented but I think it conveys what I'm trying to do, as well as my confusion about the appropriate syntax =). If it's not possible, oh well, but it would be the nicest solution to my problem.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~I program in C++, on MSVC++ '05 Express, and on Windows. Most of my programs are also for windows.
Advertisement
Assuming that you're asking about C++, there's no direct way to do what you want.
Not directly, no... and let's just not discuss alloca(). You can do it with vector, of course.
Yes, C++ (should have mentioned). Darn... seems like that's something that'd come up a lot. Oh well. Thanks.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~I program in C++, on MSVC++ '05 Express, and on Windows. Most of my programs are also for windows.
No not possible. The size of the object would not be known at compile time. However, as Sneftel has pointed out you could (should) do it with std::vector which has a constructor that takes the initial size as an argument.

Doing it via templating would be another option.
It's something that you see somewhat commonly in C. Do a search for "flexible array members" or "struct hack". However, it doesn't play nicely with C++ features such as constructors, and I doubt it will ever be a C++ feature.

This topic is closed to new replies.

Advertisement