Number at runtime

I

ikl

class A
{
....
};

For class A, several instances of it could be created, but their number is
unknown until runtime. How to do this?

Thanks!
 
J

John Harrison

ikl said:
class A
{
...
};

For class A, several instances of it could be created, but their number is
unknown until runtime. How to do this?

Use a vector.

#include <vector>

std::vector<A> vec(n); // creates n A objects

john
 
I

ikl

John Harrison said:
Use a vector.

#include <vector>

std::vector<A> vec(n); // creates n A objects

john
When I try it gives error: "error C2061: syntax error : identifier 'n'"
Does anyone know why? Thanks!

#include <vector>

using std::vector;

class B
{
};

int n = 1;

class A
{
vector<B> vec(n);

};
 
J

Jon Willeke

ikl said:
When I try it gives error: "error C2061: syntax error : identifier 'n'"
Does anyone know why? Thanks!

#include <vector>

using std::vector;

class B
{
};

int n = 1;

class A
{
vector<B> vec(n);

};

Member initialization is the constructor's responsibility:

class A
{
vector<B> vec;
public:
A() : vec( n ) {}
}
 
I

ikl

Jon Willeke said:
Member initialization is the constructor's responsibility:

class A
{
vector<B> vec;
public:
A() : vec( n ) {}
}

Why have to use constructor to initialize "vec"? Why not just like,

class B
{
int Number[10];
};

and don't need to initialize with "10"?

Thanks!
 

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
473,774
Messages
2,569,596
Members
45,140
Latest member
SweetcalmCBDreview
Top