template boy
template boy

Reputation: 10480

Creating an array of classes not working

I'm trying to create an array of classes using a vector, but I think I'm getting the syntax wrong from instantiating the array. The error I'm getting is:

error: request for member 'setX' in objects[0], which is of non-class type 'std::vector'

#include <iostream>
#include <vector>

using std::cout;

class A {
    public:
        void setX(int a) { x = a; }
        int getX() { return x; }
    private:
        int x;
};

int main() {

    std::vector<A> *objects[1];

    objects[0].setX(5);
    objects[1].setX(6);

    cout << "object[0].getX() = " << objects[0].getX() << "\nobject[1].getX() = " << objects[1].getX() << std::endl;
}

Upvotes: 1

Views: 367

Answers (4)

Baiyan Huang
Baiyan Huang

Reputation: 6781

here what you did is define an array with 1 element of type std::vector*, you may want to read more about vector and array first.

The correct way to define it is:

std::vector<A> objects(2);

or using pointers if that is what you intend to

std::vector<A*> objects(2);
objects[0] = new A();
objects[1] = new A();

Upvotes: -1

Grozz
Grozz

Reputation: 8425

std::vector<A> objects; // declare a vector of objects of type A
objects.push_back(A()); // add one object of type A to that vector
objects[0].setX(5); // call method on the first element of the vector

Upvotes: 5

Jason
Jason

Reputation: 32510

An array and std::vector are two completely different container types. An array is actually a fixed-size block of memory, where-as a std:vector object is a dynamic sequential container type, meaning it can be dynamically "grown" and "shrunk" at run-time, and the object itself manages the memory allocation of the objects it owns. Their apparent similarities are that both can access members in O(1) complexity and can use the bracket syntax for accessing members.

What you want is something like the following:

int main() 
{

    //make a call to the std::vector<T> cstor to create a vector that contains
    //two objects of type A
    std::vector<A> objects(2);

    //you can now access those objects in the std::vector through bracket-syntax

    objects[0].setX(5);
    objects[1].setX(6);

    cout << "object[0].getX() = " << objects[0].getX() << "\nobject[1].getX() = " << objects[1].getX() << std::endl;

    return 0;
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726589

With an asterisk and a square brackets, you are declaring an array of pointers to vectors instead of a vector. With std::vector<T> you do not need square brackets or an asterisk:

std::vector<A> objects(2); // 2 is the number of elements; Valid indexes are 0..1, 2 is excluded

objects[0].setX(5); // This will work
objects[1].setX(6);

The reason the compiler thought that you were trying to call setX on a vector is that the square bracket operator, overloaded by the vector, is also a valid operator on an array or a pointer.

Upvotes: 3

Related Questions