[c++] Initialize array of class with new
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?
First of all, 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:
in this case, triangles would be declared as:
Also, you should use std::vector and smart pointers. They will make your programming life much easier (and your code more robust).
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).
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
Quote:
Original post by EnigmaQuote: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].
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement