473,804 Members | 3,509 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can a class have a non-static const array as a data member?

Here is my class:

class MyClass {
public:

MyClass();

~MyClass();

private:

// non-static const array as a data member
const int memArr_[5];
};

Is such a class (with non-static const array as a data member) valid?
Since I cannot see why it may not be valid, I presume that it is valid.

Therefore when an object of MyClass is constructed, memArr_[5], being a
const embedded object, will need to get initialized in the constructor.
My problems start here as I cannot write a constructor that has the
right initializer for the above array. Every attempt gives a
compilation error (the errors reported below are from VC++ 7.1 - but
I get similar errors in VC++ 6.0 and GCC 3.2.x on Linux).

Attempt 1:
==========

MyClass::MyClas s():
memArr_(0, 1, 2, 3, 4)
// error C2536: 'MyClass::MyCla ss::c_memArr_' :
// cannot specify explicit initializer for arrays
{ }
Attempt 2:
==========

MyClass::MyClas s():
memArr_({0, 1, 2, 3, 4})
// error C2958: the left parenthesis '('
// found at '...\myclass.hx x(17)' was
// not matched correctly
{ }
Attempt 3:
==========

MyClass::MyClas s()
// error C2439: 'MyClass::c_mem Arr_' :
// member could not be initialized
{ }
Can anyone tell me if I am missing something here and show me how to
write the initializer correctly? Or if this is wrong according to C++
standard and why (I cannot convince myself why should this be wrong)?
Or is this a compiler limitation?

Apr 4 '06 #1
5 2463
Why don't you use std::vector?

Apr 4 '06 #2
pa**********@gm ail.com wrote:
Here is my class:

class MyClass {
public:

MyClass();

~MyClass();

private:

// non-static const array as a data member
const int memArr_[5];
};

Is such a class (with non-static const array as a data member) valid?
Since I cannot see why it may not be valid, I presume that it is valid.

Therefore when an object of MyClass is constructed, memArr_[5], being a
const embedded object, will need to get initialized in the constructor.
My problems start here as I cannot write a constructor that has the
right initializer for the above array. Every attempt gives a
compilation error (the errors reported below are from VC++ 7.1 - but
I get similar errors in VC++ 6.0 and GCC 3.2.x on Linux).


My understanding is that there's nothing which prohibits you from having
such a member however, since it must be initialized in the ctor, its
usefulness is quite limited. As you discovered, lists (with or without
brackets) are not valid initializers. The only valid initialization I
know of is memArr_() which will default initialize all of the array
elements (0 for built-in types). Or you can not explicitly initialize
it and take whatever junk the compiler gives you.

Mark
Apr 4 '06 #3
Mark P <us****@fall200 5remove.fastmai lcaps.fm> wrote:
The only valid initialization I
know of is memArr_() which will default initialize all of the array
elements (0 for built-in types).


However, be aware that at least one popular compiler (VS .NET 2003, aka
VC++ 7.1) does not do this correctly:

http://groups.google.com/group/comp....b44a8b786b6a79

and read the response by Dietmar Kuehl also.
However, they did fix it in the new version (VS .NET 2005, aka VC++
8.0), and Patrick Kowalzick has also posted a work-around for the older
version:

http://groups.google.com/group/micro...a339bdd2c2aa6e

--
Marcus Kwok
Apr 4 '06 #4

pa**********@gm ail.com wrote:
Here is my class:

class MyClass {
public:

MyClass();

~MyClass();

private:

// non-static const array as a data member
const int memArr_[5];
};

Is such a class (with non-static const array as a data member) valid?
Since I cannot see why it may not be valid, I presume that it is valid.


It's valid. Consider that the elements could be of class type. In that
case, they will be nicely initialized by their default constructors.

Also, an array could be wrapped in a struct. The const qualifier could
be put on the struct member instead of the array, like this:

const struct Foo {
int array[5];
} s; // s is the non-static member of the class

So now you can initialize the thing in the constructor, because what
you are initializing is a struct object, and not an array member.

MyClass::MyClas s(Foo init)
: s(init)
{
}

Or:

// static member function
MyClass::Foo MyClass::makeFo oStruct( ... args ...)
{
}

MyClass::MyClas s()
: s(makeFooStruct (... args ...))
{
}

I.e. you write some function that constructs a Foo according to some
parameters, and then call it in your constructor's initializing
expression.

Apr 4 '06 #5
Marcus Kwok wrote:
Mark P <us****@fall200 5remove.fastmai lcaps.fm> wrote:
The only valid initialization I
know of is memArr_() which will default initialize all of the array
elements (0 for built-in types).


However, be aware that at least one popular compiler (VS .NET 2003, aka
VC++ 7.1) does not do this correctly:


A good point, and in fact, not the only compiler with this defect. I've
seen problems with a version of the Sun CC compiler too.
Apr 4 '06 #6

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

Similar topics

50
6392
by: Dan Perl | last post by:
There is something with initializing mutable class attributes that I am struggling with. I'll use an example to explain: class Father: attr1=None # this is OK attr2= # this is wrong def foo(self, data): self.attr1=data self.attr2.append(data) The initialization of attr1 is obviously OK, all instances of Father redefine it in the method foo. But the initialization of attr2 is wrong
2
1428
by: Capstar | last post by:
Hi NG, Is it possible to make a template class, which has only one method that makes use of the template type. The rest of the methods will work on the base class of which the template type should always be derived. I want the template to have a compile-time check of the type, but I don't want a "full" template class because all generic methods will be generated for every type I use this class with, which is a waste of resources.
10
7337
by: Matthias | last post by:
Hello, I thought one major advantage of using functors as e.g. sorting predicates over functions would be that I can do something like this: void foo() { class Predicate { public:
3
2473
by: Parvesh | last post by:
hi, I am using a webservice which Returns the Result in an XML string, The XML response i get i svery cumbersome to parse, But if i could convert it to the Corresponding Class using the System.Xml.Serialization, i think that can solve my problem. But i tried using the Deserialize method for converting the XML to the Corresponding Object, neither i get error nor i get any luck for converting it to Object.
17
3579
by: baibaichen | last post by:
i have written some code to verify how to disable slicing copy according C++ Gotchas item 30 the follow is my class hierarchy, and note that B is abstract class!! class B { public: explicit B(INT32 i =0):i_(i){} virtual ~B(){}
2
1485
by: flopbucket | last post by:
Hi, If I have the following: template<class T> class A { public: int a; };
1
6175
by: bytebugs | last post by:
Hi, As a matter of principle I have refranied from creating an instance of Form or UserControl from within a class that does not inherit from System.Windows.Form. I am looking for comments on Pros and Cons of the approach. My logic has been that UI is always executed on the main application thread. I use Control.InvokeRequired or delegates to ensure that I am
5
1611
by: The Cool Giraffe | last post by:
I'm designing an ABC and in connection to that i have run into some "huh!" and "oh...". Let me put it as a list. 1. Since the class will only contain bodies of the methods, only the header file is needed. There will be no definitions provided until i derive the ABC. True or false? 2. Since i'll have two different classes (both derived from the original ABC) i'll use the following syntax in my main class using the derivation.
15
7371
by: Anthony Greene | last post by:
This is probably a very introductory object-oriented question, but it has been nagging me for years, and since I've never been able to find the right answer, I've had to work around it with non-optimal code. However, I suspect there must be a proper object-oriented approach to solving this problem. Perhaps someone might be able to help me out. Oftentimes I need to convert an object declared as a base type into a object of one of its...
5
4186
by: Sin Jeong-hun | last post by:
class Engine { Thread Worker; public event ... EngineMessage; public void Start() { Worker=new Thread(new ThreadStart(Run)); Worker.Start(); } private Run()
0
9708
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...
1
10327
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10085
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6857
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
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4302
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3828
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2999
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.