1

I am trying to dynamically allocate a array inside a class. Came across a very weird thing. Please have look on this two piece of code and do tell me the difference.

class A{

public:
    int n;

    int *a;

    a = new int [4];

    ~A(){delete []a;}

    A(){}
}

Compiling with GCC produces the following error:

a does not a name type

But when I use:

class A{

public:

    int n;

    int *a = new int [4];

    A(){}
    ~A(){ delete []a;}
}

It compiles

user3383404
  • 35
  • 2
  • 11

3 Answers3

4
a= new int [4];

Is not an initialization but an assignment and is not allowed.

int *a = new int [4];

Works as it is an in class initilization and is allowed in C++11 and beyond.

You are also mixing new[] and delete. Whenever you use new you should have a call to delete and when you use new[] you need to call delete[]

Now instead of dealing with pointers and new[] and delete[] you should use a std::vector instead.

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
2

This is an initialization:

int *a = new int [4];

This is an assignment which can't be done in a class declaration, but can be done, e.g., in a constructor:

a = new int [4];

Also, if you use new[], you also need to use delete[], not delete.

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
2

I'm not clear on what exactly you're shooting for, but this work should be done in the constructor and destructor of the class

class A
{
public:
    A() { a = new int[4]; }
    ~A() { delete[] a; }
private:
    int* a;
};

and better yet, you could avoid doing any dynamic allocation yourself if you use std::vector

class A
{
public:
    A() : a(4) {}
private:
    std::vector<int> a;
};
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218