Sign in to follow this  

Set dimensions of stack-based array in constructor?

This topic is 2842 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 2842 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this