Yes we can do so . We can create an array of objects for any class , irrespective of whether it has a default constructor or not . Moreover , the default constructor is also provided by the compiler . :D

We can create an array of objects for any class , irrespective of whether it has a default constructor or not

Is the above really true?

Please see ...
http://en.wikipedia.org/wiki/Default_constructor
and note the following example that needs
to have a defined default ctor

/*
If some constructors are defined, but they are all non-default, 
the compiler will not implicitly define a default constructor. 
Hence, a default constructor may not exist for a class.
This is the reason for a typical error which can be demonstrated 
by the following example.
*/
class MyClass 
{
  public:
    MyClass (int y); // a value constructor     

  private:
    int x;
};

MyClass :: MyClass (int y)
{
    x = y;
}

int main()
{
    MyClass object(100);     // value constructor called
    MyClass* pointer;        // do not need to know about any existing ctors
    pointer = new MyClass;   // error: no default constructor    
    return 0;
}

Edited 2 Years Ago by David W

No we cannot do so because when if we define a single constructor in the class than the compiler does not provide default constructor , so in that situation we have compulsary write the default constructor otherwise it creates error

@Akash_Soni

Your reply is true ... in the case where your design actually does call (i.e. the program uses it) the default ctor ... other-wise (sometimes) ... you may not want to code for the default ctor ... i.e. the case where you want your compiler to issue an error if programmer inadvently codes for a call to the default ctor (and your design was to prevent that from happening.)

Edited 2 Years Ago by David W

when you create object of a class

MyClass obj;

this calls the default constructor and the compiler generates an error that "no default constructor" and than you have to define default constructor

so in the above program which u have posted in that u have define a constructor which takes single argument so the compiler does not provide an default constructor and throws an error tha "no default constructor"

The C++ default constructor has no argument at all. So if you don't define a constructor at all, that and the default copy constructor are the only constructors in the class. In that case:

Myclass a[10]; //Valid.
Myclass b[2] = {0, 1}; //Error.

But If you define only a constructor with an integer argument in the class, then:

Myclass a[10]; //Invalid as no zero argument constructor is present.
Myclass b[2] = {0, 1}; //Valid.
Myclass b[2] = {Myclass(0), Myclass(1)}; //Valid.

So it is always advisable to create both a one argument and a zero argument constructor for your class, if you wanna work with arrays.

Edited 2 Years Ago by tapananand

This article has been dead for over six months. Start a new discussion instead.