dcsimg
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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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