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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,064
Latest member
naturesElixirCBDReview

Latest Threads

Top