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

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Please be an angel an say you must use delete[].
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.

Comments

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;
};

2 Comments

Plus one, you've fixed the undefined behaviour encountered when using delete.
Thnask Kramer .. i do not have specific target..just a query.. ..was just playing with ,,i use vectors a lot..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.