0

1).Why did I get this error? What is the correct syntax?

2).Is there a way to write the same code without using the library "vector"?

#include <vector>

myClass()
{
    public:
        myClass(int x,int y);
        void doThis()
        {
            //Something
        }
}

int main(void)
{
    std::vector<myClass>*ex_vector = new std::vector<myClass(5,myClass{10,10});
    ex_vector[0]->doThis(); //Error Here
    delete []ex_vector;
}

I get this error:

error: base operand of '->' has non-pointer type 'std::vector<myClass>'

1 Answer 1

5

The correct syntax is

(*ex_vector)[0].doThis();

Also, you should delete ex_vector; and not delete[] ex_vector; since the type of the new was not a raw array type.

However, there's rarely a good reason to new a std::vector. Just use a plain object.

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

4 Comments

2).Is there a way to write the same code without using the library "vector"?
Not easily, since myClass doesn't have a default constructor.
Vote up for the comment on preferring plain object over pointers. Note that if you are really desperate for pointers, use a smart pointer rather than a raw one.
Wishing I can add it. The point is that I have to deallocate memory in just end up using the vector.

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.