Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Aug 8, 2000

How to Initialize an Array

Question:
How do you initialize or assign values to an array in a class?

Answer:
The short answer is that you can't initialize an array member as you would initialize a scalar data member. You can use memset to zero all the elements of the array inside the constructor's body or use a loop that assigns values to each array element.

class A
{
 private:
  int ar[10];
 public:
 A() 
 { 
  for (int i=0; i<10; ++i)
   ar[i] = i;
 }
}

In most cases, it's best to use a vector object instead of a built-in array, thereby avoiding the initialization problem right from the start:

class A
{
private:
std::vector < int > vi;//instead of array
//...
};
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date