Archived

This topic is now archived and is closed to further replies.

Marsupial Rodentia

init const class members?

Recommended Posts

A C++ class can have a constant. And I can initialize the value of the constant in the constructor, for example:
  
class MyClass
{
public:
const int MyConstant;

MyClass();  // Default Constructor

};

MyClass::MyClass() : MyConstant(2) // Initialize my constant member

{

}
  
Now my question is, what is the syntax for initializing an array of constants as a class member?

Share this post


Link to post
Share on other sites
Compiler error messages are there to help.
C:\projects\test\test.cpp(10) : error C2536: ''Test::arr'' : cannot specify explicit initializer for arrays

The articles the error messages link to in MSDN are also helpful:
quote:

Compiler Error C2536
''identifier1::identifier2'' : cannot specify explicit initializer for arrays

The specified member of a class, structure, or union could not be initialized.

This error can be caused if a constructor is not available to initialize one or more members of an array. If the size of the array is greater than the number of initializers, then a default constructor must be defined.

[bold]
Alternatively, this error can be caused by declaring a nonstatic array with the const specifier. This kind of array cannot be explicitly initialized.
[/bold]


Share this post


Link to post
Share on other sites
The constant should be explicitly initialized.

The syntax uses a seperate statement either in your header file or cpp file:

MyClass::MyConstant = 2;


Arun

Share this post


Link to post
Share on other sites