Sign in to follow this  
Revelation60

[c++] Initialize array of class with new

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
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[i] = 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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this