How to generate dynamic empty 2D array without default constructor in C++ -
i have class named test
, i'd create empty 2d array hold instances of class , add them later 1 one using constructor accepts parameters.
basically, i'd reserve memory fill in later objects. needs bee on heap
since have class generate 2d arrays of different sizes.
this first approach doesn't work since test
class doesn't have default constructor:
test** arr; arr = new test*[10]; (int = 0; < 10; i++) arr[i] = new test[10];
[edit]
here full test code. in all, i'm getting wrong values out, should numbers 0 99:
#include <iostream> using namespace std; class test { private: short number; public: test(short n) { this->number = n; } short getnumber() { return number; } }; int main() { test** arr; arr = new test*[10*10]; (int = 0; < 100; i++) arr[i] = new test(i); (int = 0; < 10; i++) { (int j = 0; j < 10; j++) cout << arr[i][j].getnumber() << " "; cout << endl; } }
maybe try using default constructor default parameters?
test(int = 0) {. . .}
Comments
Post a Comment