473,623 Members | 2,433 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Init an array in a class

Vij
I can do this
int a [] = { 5,6,7,8,9};

but how can I do this inside a class? something like this

class CTest
{
private:
int a [] // Init the array here
};

Sep 6 '05 #1
3 7491
Vij wrote:
I can do this
int a [] = { 5,6,7,8,9};

but how can I do this inside a class? something like this

class CTest
{
private:
int a [] // Init the array here
};

I would do it like this:
// header file
#include <vector>
class CTest
{
public:
CTest();
private:
std::vector<int > a;
}

//source file
namespace{
// solution 1 for short arrays:
std::vector<int > init_a()
{
std::vector<int > result(5);
a.at(0) = 5;
//...
a.at(4) = 9;
return result;
}

// solution 2 for long array:
std::vector<int > init_a()
{
const int a [] = {5, 6, 7, 8, 9};
return std::vector<int >(a, &a[5]); // You might have been looking for
this? vector constructor can take two iterators.
// or, to be very safe:
// return std::vector<int >(a, &a[sizeof(a) / sizeof(int) - 1]);
}

} // unnamed namespace

CTest()
: a(init_a())
{}

- Gabriel
Sep 6 '05 #2
On Tue, 06 Sep 2005 15:30:24 +0400, Vij <vi******@gmail .com> wrote:
I can do this
int a [] = { 5,6,7,8,9};
but how can I do this inside a class? something like this
class CTest
{
private:
int a [] // Init the array here
};


You can't specify explicit initializers for arrays in constructor's
initialization list nor in class declration. You can initialize array as
described before or use static arrays:

struct A
{
static int a[];
};

int A::a[] = {1,2,3};

void main() {
A x;
}
Sep 6 '05 #3
Vij wrote:
I can do this
int a [] = { 5,6,7,8,9};

but how can I do this inside a class?
You can't.
something like this

class CTest
{
private:
int a [] // Init the array here
};


An array needs a size. In the first example, the size can be deduced from
the initializer. But in a class, you can't put an initializer here, so you
must specify a size. Further, non-static array members cannot be
initialized at all in C++.
So the only thing you can do is explicitly specify a size for the array and
assign all the elements in the constructor, like:

class CTest
{
public:
CTest()
{
a[0] = 5;
a[1] = 6;
a[2] = 7;
a[3] = 8;
a[4] = 9;
private:
int a [5];
};

Sep 6 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
13274
by: Victor Hannak | last post by:
I have a class that needs to reference a const array in several of its methods. Where should I put the declaration/initialization of this array so that it is only created once when the class is instantiated, but is visible to all of the methods of only this class ? const unsigned short ConstantVectorWidth = 10; const float ConstantVector = {5,10,15,20,25,30,35,40,45,50}; Does this syntax look correct?
10
3868
by: Wylbur via DotNetMonster.com | last post by:
Hello to all of you geniuses, I'm having a problem trying to get an Init handler to fire for a Placeholder control at the initialization phase. I’ve posted this problem to 3 other ASP.NET forums, and noone wants to touch it. I tried to attach a literal control to a placeholder: <>-<>-<>-<>-<>-<>-<>-<>-<>-<>-<>-<>
3
1974
by: kk_oop | last post by:
Hi. I recently wrote a simple little template that defines an array that checks attempts to use out of bounds indexes. The only problem is that it does provide the use array style value initialization when the type is instantiated. Any suggestions for a mod that would allow array initialization syntax? ***********Here's the type: #ifndef CHECKED_ARRAY_ #define CHECKED_ARRAY_
0
2498
by: metaperl | last post by:
A Comparison of Python Class Objects and Init Files for Program Configuration ============================================================================= Terrence Brannon bauhaus@metaperl.com http://www.livingcosmos.org/Members/sundevil/python/articles/a-comparison-of-python-class-objects-and-init-files-for-program-configuration/view
8
2731
by: Grizlyk | last post by:
Good morning. Look here: http://groups.google.com/group/fido7.ru.cpp.chainik/browse_frm/thread/7341aba5238c0f79 and here: http://groups.google.com/group/fido7.ru.cpp.chainik/browse_frm/thread/cb014f4ba9df614a Can anybody answer? Who can't read in russian:
7
2083
by: recover | last post by:
class Obj { public: Obj(int a){} } class MyContainer { private: Obj m_obj;
4
7012
by: josh | last post by:
Hi, which is the way to init a static array inside a constructor function? i.e. if I had to init ---> int x = {100,200}
4
3702
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and value-initialization. I think default-init calls default constructor for class objects and sets garbage values to PODs. Value-init also calls default constructor for class objects and sets 0s to POD types. This is what I've learned from the books (especially...
3
15222
by: indiarocks | last post by:
Let's say I have a class A which inherits from B. If I need to call the init function of B, I could just say super(A,self).__init__() in the init function of A. I was wondering how do I call the init function of B from class C, where I instantiate A. Usual case would be Class A(b.B): def __init__(self): super(A,self).__init__()
0
8227
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8165
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8670
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
7150
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6106
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5561
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4164
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1778
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1473
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.