How to initialize a variable in class
-
How to initialize a variable array in a class? it should be static defined? class{ ... char array[] = "asdhajsdjasgdj"; ... }
9ine
9ine wrote:
How to initialize a variable array in a class?
Use member initialization list. But in above case varaible is array, so cant use member initialization list. In constructor body you can initialize(re) it.
class A
{
int i;
char array[1];
public:
A():i(0)
{
array[0]=0;
}};
9ine wrote:
it should be static defined?
Not necessary.
Prasad Notifier using ATL
-
How to initialize a variable array in a class? it should be static defined? class{ ... char array[] = "asdhajsdjasgdj"; ... }
9ine
in C++ (by opposition to C# or java), almost all the members should be initialized in the constructor. the only exception are static members, which init should be done outside of the class definition.
TOXCCT >>> GEII power
[VisualCalc 3.0 updated ][Flags Beginner's Guide new! ]
-
How to initialize a variable array in a class? it should be static defined? class{ ... char array[] = "asdhajsdjasgdj"; ... }
9ine
-
How to initialize a variable array in a class? it should be static defined? class{ ... char array[] = "asdhajsdjasgdj"; ... }
9ine
In general, you would initialize member variables as part of the Constructor (either in the implicit parameter list, or in the constructor). For the example you give, you may consider writing it the following way:
// In the header file class MyClass { public: MyClass() {} ~MyClass() {} static const char* ms_MyString; }; // In the implementation file const char* MyClass::ms_MyString = "0123456789";
This gives you a single copy of the string regardless of the number of objects of this type you have. It will remain constant (that is, you can't change it), and it will remain in the same location in memory for the entire lifetime of your application. If you need to have an array that you can change, you would initialize it in the constructor:
// In the header file class MyClass { public: MyClass() : m_MyString(0) {memset(m_MyOtherString, 0, 100);} ~MyClass() {} char* m_MyString; // pointer-style array char m_MyOtherString[100]; // allocated array };
If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac