• Advertisement
Sign in to follow this  

[c++] Initialize array of class with new

This topic is 3705 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

My class has this constructor: SceneTriangle(SceneObject* p); The variable that has this class is a dynamic array: class SceneObject { public: int TriangleCount; SceneTriangle *triangles; void DoSomething(); }; When I know the length of triangles, stored in TriangleCount, I try to create the array: void SceneObject::DoSomething() { triangles = new SceneTriangle[TriangleCount](this) } This doesn't compile unfortunately. What should I do?

Share this post


Link to post
Share on other sites
Advertisement
First of all, this:

triangles = new SceneTriangle[TriangleCount](this);


is invalid syntex. I understand what you're trying to do but that's not the way to do it. If you want the objects in the array to be created with a non-default c'tor, you must use an array of pointers, like so:


void SceneObject::DoSomething()
{
triangles = new SceneTriangle*[TriangleCount];
for (int i = 0; i < TriangleCount; ++i)
triangles = new SceneTriangle(this);
}


in this case, triangles would be declared as:
SceneTriangle **triangles;

Also, you should use std::vector and smart pointers. They will make your programming life much easier (and your code more robust).

Share this post


Link to post
Share on other sites
Quote:
Original post by Gage64
Also, you should use std::vector and smart pointers. They will make your programming life much easier (and your code more robust).

Or, in this case std::vector without smart pointers:
class SceneObject
{
public:
void DoSomething();
private:
std::vector< SceneTriangle > triangles;
};

void SceneObject::DoSomething()
{
triangles.assign(TriangleCount, SceneTriangle(this));
}

Σnigma

Share this post


Link to post
Share on other sites
Quote:

Original post by Enigma
Quote:
Original post by Gage64
Also, you should use std::vector and smart pointers. They will make your programming life much easier (and your code more robust).

Or, in this case std::vector without smart pointers:
*** source snippet removed ***


It's posts like these that make me wish I had spent more time learning the STL [smile].

Share this post


Link to post
Share on other sites
Thank you both :)


Quote:
It's posts like these that make me wish I had spent more time learning the STL


Same goes for me :P I'm a bit hesitant when it comes to C++ standard classes.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement