default constructors

When dynamically allocating memory via new, as in new T[n], I understand that not only is a block of memory allocated, but each element is default initialsed via T's default initialiser. However, my book warns me that this will only work if T has a default constructor, but I cannot understand in what situation T would not have a default constructor, since one is synthesised if it is not defined in the class definition of T.

There doesn't seem to be a problem with primitive types, since the folloing code yields 0, which suggests that the system initialises to zero the elements of such an array:

1
2
3
int* a = new int[5];
 
        cout << *a;


So how can a type exist which doesn't have a default constructor (either user- defined of synthesisable)?

I'm guessing that perhaps if the class defines a copy constructor but not a defualt constructor, then this would be a problem.

Cheers.
owever, my book warns me that this will only work if T has a default constructor, but I cannot understand in what situation T would not have a default constructor,


Just to offer up a quick example of this, T would not have a default constructor int he following situation:

1
2
3
4
5
6
7
8
9
10
11
// T.h -- T header file
class T
{
  private :
   int x;
int y;
int z;
  public:
   T(int x, int y)
   T(int x, int y, int z)
   //lets say these are all your constructors. 


When constructors are created it is the programmers job to create a default constructor as well. For the above code, you would personally have to create the constructor "T()". Had you not defined any constructors the compiler would have taken the liberty to create the default constructor for you.
There doesn't seem to be a problem with primitive types, since the folloing code yields 0, which suggests that the system initialises to zero the elements of such an array:

You just got lucky in that case. With this code:

int* a = new int[5];

the block of memory is uninitialized, so they may all be garbage (or zero).

However, this will guarantee that each int is zero:

int* a = new int[5]()
Thanks, georgewashere and shacktar.

I'm starting to see now why creating default initialisers is so important. So for class types, is the situation that georegewashere describes, where some constructors are defined, but not the default constructor, the only (or main) obstacle for synthesising default constructors?

Also (and perhaps an esoteric question) is there any situation where one might want to write a class like the one in geaorgewashere's example, or is it a golden rule that one should always define a default constructor if one defines any constructor?
Topic archived. No new replies allowed.