0
class Graph {
private:
    int n;
    Head* array;
    Graph(int n)
    {
        this->n = n;
        array = new Head[n];
        for (int i = 0; i < n; i++)
        {
            array[i].head->vertex = i;
        }
    }

};

When the first Head* array is being declared, it is being done in the stack. Then again it is being allocated to the heap using the new keyword inside the constructor.

I want to understand if this is the same as if we wrote: Head* array = new Head[n]; And if so then is this a standard way of declaring member variables in a class? Is it also because when objects are created constructors are invoked first, so member variables are not set if they are not in the constructor?

  • It's not the same because you could not have written `Head* array = new Head[n];` as a member declaration… – Michael Kenzel Apr 02 '19 at 02:39
  • 1
    Reference to array is still on the stack, only what it points to is on the heap. – rated2016 Apr 02 '19 at 03:01
  • *is this a standard way of declaring member variables in a class?*: [Why should C++ programmers minimize use of 'new'?](https://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new) – user4581301 Apr 02 '19 at 03:29
  • I think I misread that. I'll leave the link anyway because it is important. The preferred way to initialize a member variable with a value not known at compile time is the [Member Initializer List](https://en.cppreference.com/w/cpp/language/initializer_list). – user4581301 Apr 02 '19 at 03:33

0 Answers0