how to alloct dynamiclly with a class

N

Nikki

Hi,
I have a question when I am programming. I define a class
(Component{};) and I want to use "new" to dynamiclly alloct a class
array, such as Component C[num].
I know how to do with one element: Component *C = new Component();
But how to do with an array? I use: Component **C = new
*Component()[4]; But it's not right.
If you can give me any information, I'll be so appreciated.

Nikki
 
V

Victor Bazarov

Nikki said:
I have a question when I am programming. I define a class
(Component{};) and I want to use "new" to dynamiclly alloct a class
array, such as Component C[num].
I know how to do with one element: Component *C = new Component();
But how to do with an array? I use: Component **C = new
*Component()[4]; But it's not right.
If you can give me any information, I'll be so appreciated.

Please try not to ask questions in a newsgroup that can be read in
a book. It's a huge waste of your (and our) time. If you can't
find some answers in your favourite C++ book, do start with a search
on the Web, then the FAQ. Only if everything else fails post your
question here.

class Component {};
int main()
{
Component *componentArray = new Component[42]; // allocate
componentArray[33]; // access an element
delete[] componentArray; // deallocate
return 0;
}
 
R

Rob Williscroft

Nikki wrote in
Hi,
I have a question when I am programming. I define a class
(Component{};) and I want to use "new" to dynamiclly alloct a class
array, such as Component C[num].
I know how to do with one element: Component *C = new Component();
But how to do with an array? I use: Component **C = new
*Component()[4]; But it's not right.
If you can give me any information, I'll be so appreciated.

Component *C = new Component[4];

remember to delete it with:

delete [] C; // NOT delete C!

But if possible use std::vector<>:

#include <vector>

struct Component {};

int main()
{
std::vector< Component > C( 4 );
}

HTH.

Rob.
 
J

Jonathan Turkanis

Victor Bazarov said:
... Only if everything else fails post your
question here.

That's a bit of an overstatement, isn't it? The main problem with the
question is that it shows such a lack of familiarity with the language
that no short answer will suffice.

But I agree -- read a good C++ introduction.

Jonathan
 

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
474,159
Messages
2,570,881
Members
47,418
Latest member
NoellaXku

Latest Threads

Top