[c++] Initialize array of class with new

Started by
3 comments, last by Revelation60 16 years, 3 months ago
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?
Currently working on WalledIn
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).
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 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].
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.
Currently working on WalledIn

This topic is closed to new replies.

Advertisement