Initializing a data member within the class definition

Is it possible? For example, I have an array of 26 characters (one for each letter of the alphabet) in the private section of my class. Visual C++ won't allow me to define the values right there and when I try to define the array within a method, it doesn't even recognize the array.

Is there any good way around this?

EDIT:: To clarify, when I mentioned the method not recognizing the array, the compiler says "expected an expression".
Last edited on
Could you post some code? The only things you can define inside of a class definition are static integral types, so you'll need to be a bit more specific about what you want to do.
closed account (zb0S216C)
If you're trying to initialize members within a class deceleration, you need to make them static and constant. Consider the following code snippet.

1
2
3
4
5
6
7
8
9
typedef class EXAMPLE_CLASS
{
    public:
        static const char  Alphabet[ 26 ]; // Declare the array first.
}ExampleClass;

// Initialize the member.
const char EXAMPLE_CLASS::Alphabet[ 26 ] = { 'a', 'b', ... };


The downside to this is that you cannot modify the array once it's been initialized.
The problem that I'm having is that the array is supposed to be a private attribute. Here's some code, if it helps at all:

1
2
3
4
5
6
7
8
9
10
class advancedCaesar: public caesarCipher{

private:
	char cipherAlphabet[26];

public:
	void print();
	advancedCaesar();
	advancedCaesar(int cipherLetter);
};


1
2
3
4
5
6
7
8
9
10
11
12
13
void advancedCaesar::print(){

	cipherAlphabet[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
	cout<<"The shift value is "<<shift<<endl;
	cout<<"The cipher alphabet is: "<<endl;

	for (int j = 0; j < 26; j++){
		cipherAlphabet[j] = cipherAlphabet[j] + shift;
	}

	cout<<cipherAlphabet;

}


I need to be able to initialize the array and still have it be modifiable. Thanks in advance to anybody who can help me out.
closed account (zb0S216C)
By the sounds of it, you're going to have to initialize the array in the class constructor( or in a class method - which you will have to call first ) manually. That way, it's not constant nor static and still modifiable.

They way you're declaring the array on line 3, second code block, is not allowed.

EDIT:
You've made your array private which means if you want to be able to modify the array, you need a class method to be able to edit the array. If the array remains private, external methods( or direct access ) will be denied.
Last edited on
Topic archived. No new replies allowed.