Questions

I

ikl

Is it right to define an array of pointers pointing to a list of objects
like this?

class A
{
};

A* ptr[15];

int i = 0;
for(i=0; i<15; ++i){
ptr = new A();
}

Is it possible to define a list of references referring to a list of
objects?

Thanks!
 
J

John Harrison

ikl said:
Is it right to define an array of pointers pointing to a list of objects
like this?

class A
{
};

A* ptr[15];

int i = 0;
for(i=0; i<15; ++i){
ptr = new A();
}


Whether its right or not depends on your requirements. It's not something I
would recommend to a newbie. You should use a vector.
Is it possible to define a list of references referring to a list of
objects?

It's impossible to create an array of references, which is what I think you
are asking.

john
 
J

jonathanmcdougall

Is it right to define an array of pointers pointing to a list of objects
like this?

class A
{
};

A* ptr[15];

int i = 0;
for(i=0; i<15; ++i){
ptr = new A();
}


"Right" depends on what you want to do. This code compiles fine, and
probably does what you want, except that you forgot to delete the content
of the array :

for (int i=0; i<15; ++i)
delete ptr;

But I would recommend using std::vector :

# include <vector>

class A
{
public:
A(int a, int b);
};

int main()
{
std::vector<A> v;

v.push_back( A() );
v.push_back( A(1, 3) );
}

Look in your textbook for some more informations.
Is it possible to define a list of references referring to a list of
objects?

No.


Jonathan
 
K

Kevin Goodsell

ikl said:
Is it right to define an array of pointers pointing to a list of objects
like this?

class A
{
};

A* ptr[15];

int i = 0;
for(i=0; i<15; ++i){
ptr = new A();
}


If the items are all the same type, as is the case here, then there's no
need for pointers at all. You could simply create the array this way:

A some_array[15];

Or use a std::vector, as others suggested. This is preferable in most
cases, because of the increased flexibility and ease of use.

-Kevin
 

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,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top