Say I have a class:

class foo
{
   public:
      foo();
      int len{return 1};

};

Then in main I have a class pointer:

foo *var[5];

My question is when do class pointers get initialized? Or do they not? How would one initialize them?

Recommended Answers

All 4 Replies

When you assign them memory or you may point then to an existing object which should already be initialized.

Your example 'class foo' returns len which does not exist....

Sorry about the example. I was just trying to write something quick and basic.
Excuse me if I'm being dense but what do mean by 'when you assign them memory'?

This line:

foo * var[5];

creates five pointers to a foo object, but that does not create five foo objects. var will hold 5 pointers to no-where or anywhere, which is the same.

To initialize five foo objects for those pointers to point to, you need to do this:

foo* var[5];
  for(int i=0;i<5;++i)
    var[i] = new foo;

Then you need to delete them with:

for(int i=0;i<5;++i)
    delete var[i];

Ok I get it now. I guess I need to brush up more than I thought :). Its been a while since I programmed C++. Thanks for the help everyone.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.