waiwai933
waiwai933

Reputation: 14559

Can the attributes of a class be an array?

I'm new to OOP, so please bear with me if this is a simple question. If I create a class, which has attributes "a", "b", and "c", is it possible for the attributes to be an array, such that attribute a[2] has a meaning?

Upvotes: 0

Views: 3826

Answers (2)

Dominic Rodger
Dominic Rodger

Reputation: 99801

Assuming that by "attributes" you mean what C++ refers to as "member variables" (i.e. members of a particular objects):

class MyClass:
public:
    MyClass() {
       a.push_back(3);
       a.push_back(4);
       a.push_back(5);
       cout << a[2] << endl; // should output "5"
    }
private:
    std::vector<int> a;
};

Upvotes: 6

Jesper
Jesper

Reputation: 206876

Member variables can ofcourse be arrays. Example:

class MyClass {
    int a[3];  // Array containing three ints
    int b;
    int c;
};

Upvotes: 13

Related Questions