Milad
Milad

Reputation: 5490

Accessing elements of an array defined in a class (C++)

Assume that int array arrayName is a member of class className, How can I access its element in my main program?? className.arrayName[0] doesn't seem to work

Upvotes: 1

Views: 8887

Answers (2)

Draco Ater
Draco Ater

Reputation: 21206

If arrayName is static inside class className, then you can access it like that:

//Declaration
class className{
public: 
  static int arrayName[5];
};

//Access
className::arrayName[index];

If it is not static, you must create an instance of your class first.

//Declaration
class className{
public: 
  int arrayName[5];
};

//Access
className a;
a.arrayName[index];

Upvotes: 12

Vlad
Vlad

Reputation: 35584

It should be objectName.arrayName[index], where objectName is an instance of your class. Don't forget to declare your arrayName public.

(Assuming that your arrayName is not static.)

Upvotes: 3

Related Questions