Milan
Milan

Reputation: 13

Initializing an array of pointers to a defined structure with constructor

struct Mystruct
{
  int x;
  int y;
  Mystruct(int x, int y);
}
------------------------
class Myclass
{
  Mystruct** p;
  Myclass(int n);
}
------------------------
Myclass::Myclass(int n)
{
  this->p = new Mystruct*[n];
  for ( int i = 0; i < n; i++ )
    this->p[i] = new Mystruct[n];
}

This will not work. I know the problem lies somewhere with default constructor not being available, but I do not know how to move forward from here.

Upvotes: 1

Views: 43

Answers (1)

bruno
bruno

Reputation: 32594

you want

Myclass::Myclass(int n)
{
  this->p = new Mystruct*[n];
  for ( int i = 0; i < n; i++ )
    this->p[i] = new Mystruct[n];
}

because Mystruct** p;

You also need to save the dimension, and to add a destructor, very probably the constructor must be public.

As said in a remark to be able to allocate your array of Mystruct that one need a constructor without parameter

Upvotes: 2

Related Questions