New - With Constructors

I have been usually programming in C, so as usual used malloc/calloc in C++ for allocating memory for classes. I was in for a nice surprise that the contructors arent invoked. After realisation that new has to be used, can somebody help me with an equivalent code with new and delete? I checked this website for help but got more confused as they have used get_temporary_buffer function n stuff!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Triangle
{ 
public:
 double a,b,c; 
 int *tmp;
 Triangle()
 {
   tmp =  NULL;  
 }
 ~Triangle()
 {
  free(tmp);
 }
};

class Triangle *start_triangle=NULL;
int nTriangles = 100;
start_triangle = (Triangle *)calloc(nTriangles,sizeof(Triangle));
free(start_triangle);


Thanks in advance!

1
2
3
4
5
6
7
8
9
10
11
// Allocate 1 triangle and call default constructor on it
Triangle* t = new Triangle(); 

// Deallocate 1 triangle and call its destructor
delete t;

// Allocate 100 triangles and call default constructors on all of them
Triangle* array_t = new Triangle[ 100 ]; 

// Deallocate an array of triangles and call the destructor on all of them
delete [] array_t;


Note that when allocating arrays of objects with new, you can ONLY
call the default constructor on those objects. It is a limitation of the
language.
Thanks, I will try it right away. Default constructor is enough for me!
Topic archived. No new replies allowed.