2

I have to declare an array of pointers to objects (of classes) in C++. I thought this was the only way, but apparently I was wrong, as it throws a syntax error when I try to compile it. Specifically, among the 7 errors I received, 2 of these errors are in the lines: where I create the array using "new", and in the line where I call the "setData()" function. Can you tell me where I went wrong? Thanks.

#include <iostream>

class Test
{
    public:
        int x;

        Test() { x=0; }
        void setData(int n) { x=n; }
};

void main()
{
    int n;
    Test **a;

    cin >> n;
    a=new *Test[n];

    for(int i=0; i<n; i++)
    {
        *(a+i)=new Test();
        *(a+i)->setData(i*3);
    }
}

2 Answers 2

3

Use a=new Test*[n];
Other than that, you have no delete´s in your program, trivial getter/setters
for public variables are strange, and *(a+i) could be a[i]

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

4 Comments

Thanks a lot, it worked. But, can you tell me what's the difference in placing the asterisk before and after the class-name? and Why can't I use *(a+i) (although I know a[i] is better), still?
About the a[i]: You can use the other thing too, but why? About the asterisk: The language is just made this way; you can´t reorder everything. For a new int[10], [10]new int or new [10]int would be wrong too...
okay... but *(a+i)->setData() does not work, it throws up an error. I had to use a[i].
(*(a+i))->setData()
2

Your syntax is close but slightly off. Use this instead:

Test **a;

...

a=new Test*[n];

for(int i=0; i<n; i++)
{
    a[i]=new Test();
    a[i]->setData(i*3);
}

...

// don't forget to free the memory when finished...

for(int i=0; i<n; i++)
{
    delete a[i];
}

delete[] a;

Since you are using C++, you should use std::vector instead. I would also suggest passing the desired value to the class constructor:

#include <iostream>
#include <vector>

class Test
{
    public:
        int x;

        Test(int n = 0) : x(n) { }
        Test(const Test &t) : x(t.x) { }
        void setData(int n) { x=n; }
};

int main()
{
    int n;
    std::vector<Test> a;

    cin >> n;
    a.reserve(n);

    for(int i=0; i<n; i++)
    {
        a.push_back(Test(i*3));
    }

    ...

    // memory is freed automatically when finished...

    return 0;
}

Comments

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.