static array initialization

  • Thread starter Makis Papapanagiotou
  • Start date
M

Makis Papapanagiotou

Hello,

I really don't understand the simplest thing at the moment. I have a static
array of pointers to a class . How do we initialize it?

class classA
{
public:
int x1;
};

class classB
{
public:
void foo() { cout<< m_ptr[0]->x1; }
static classA* m_ptr[4];
};

classA* classB::m_ptr[0]=0; // This is not correct !!!
classA* classB::m_ptr[1]=0; // This is not correct !!!
classA* classB::m_ptr[2]=0; // This is not correct !!!
classA* classB::m_ptr[3]=0; // This is not correct !!!

int main()
{
classB* ptr = new classB;

ptr->foo();

return 0;
}

Any idea? If "m_ptr" was not an array of pointers I would had initialize it
like this: "classA* classB::m_ptr=0;"
What about arrays now?
 
J

John Harrison

Makis Papapanagiotou said:
Hello,

I really don't understand the simplest thing at the moment. I have a static
array of pointers to a class . How do we initialize it?

class classA
{
public:
int x1;
};

class classB
{
public:
void foo() { cout<< m_ptr[0]->x1; }
static classA* m_ptr[4];
};

classA* classB::m_ptr[0]=0; // This is not correct !!!
classA* classB::m_ptr[1]=0; // This is not correct !!!
classA* classB::m_ptr[2]=0; // This is not correct !!!
classA* classB::m_ptr[3]=0; // This is not correct !!!

int main()
{
classB* ptr = new classB;

ptr->foo();

return 0;
}

Any idea? If "m_ptr" was not an array of pointers I would had initialize it
like this: "classA* classB::m_ptr=0;"
What about arrays now?

Same way you initialise any array

classA* classB::m_ptr[4] = { 0, 0, 0, 0 };

but since zero initialisation is the default, you don't need to initialise
it at all.

classA* classB::m_ptr[4];

john
 
J

Josephine Schafer

Makis Papapanagiotou said:
Hello,

I really don't understand the simplest thing at the moment. I have a static
array of pointers to a class . How do we initialize it?

class classA
{
public:
int x1;
};

class classB
{
public:
void foo() { cout<< m_ptr[0]->x1; }
static classA* m_ptr[4];
};

classA* classB::m_ptr[0]=0; // This is not correct !!!
classA* classB::m_ptr[1]=0; // This is not correct !!!
classA* classB::m_ptr[2]=0; // This is not correct !!!
classA* classB::m_ptr[3]=0; // This is not correct !!!

Try this -
classA* classB::m_ptr[]={0};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top