Can I Declare A Class Object Inside A Class Function? C++ [closed]

I am trying to make a class that, among other things, will hold a 2D array. The size of this array is not known upon the initialization of the class object, so I need a function of this class to declare the array. Is there a way to do this and have the array be visible to the whole class and not be destroyed at the end of the function?

I have thought about using a multi-dimensional vector instead of arrays, but because vectors initialize with no elements, I’d need to manually declare each cell of the 2D grid. Each dimension could have 50+ elements, so it would get very inefficient very quickly.

I haven’t tried coding anything yet, I’m just wondering if it is possible or if I need to find another solution to my problem.

  • 4

    I don’t understand why std::vector don’t fit your needs.

    – 

  • You can declare an array pointer as a member of the class, and then have the function allocate the array and point the member to it. You will have to free the array when the class is destroyed. This is exactly the kind of situation that std::vector is intended to manage for you. You can simply resize the vector to the desired size, and you dont have to “manually declare each cell” unless each cell has a non-default constructor.

    – 




  • 2

    Don’t use array-of-arrays, use 2D array emulation on a 1D vector. You can pre-initialize this at size w * h and then add simple accessor functions to get or set locations using row/column coordinates, or what have you.

    – 




  • What does “visible to the whole class” mean? An object property will be “visible” to any instances, but the class itself doesn’t have any visibility to those by itself.

    – 

  • @RemyLebeau Thank you, I didn’t know multi-dimensional vectors were a thing. This should fix my issue once I learn my way around it.

    – 

Leave a Comment