0

Should we need to provide a default constructor in c++ if we use a parameter constructor? my code is like this.

ReadConfigParams::ReadConfigParams(char *file)
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
munawwerali
  • 167
  • 2
  • 12

3 Answers3

1

It depends on how you want a client of ReadConfigParams class should instantiate an object of this class.

If the class ReadConfigParams always requires a file name (as in most of the cases), you should NOT define a default constructor because it doesn't make sense to instantiate ReadConfigParams without an associated file. This will effectively prevent a client from creating an object of this class without a given file name.

But if the class ReadConfigParams can provide some default configuration values then you SHOULD define a default constructor. This will enable a client of this class to instantiate and hence access the default values without a file reading operation.

MNS
  • 1,354
  • 15
  • 26
1

Usually, if you don't declare a default constructor for a class, the compiler supplies one for you.

However, note that, the default constructor will only be created by the compiler if you provide no constructor whatsoever. For your example, you have provided one constructor that takes one argument, the compiler will then NOT create the default constructor for you.

Example-1:

class A
{
};

int main() 
{
    A a; // OK, as the compiler creates one for you
}

Example-2:

class A
{
public:
    A(int){}
};

int main() 
{
    A a; // NOT OK, error: no appropriate default constructor available!
}

Example-3:

class A
{
public:
    A(){}
    A(int){}
};

int main() 
{
    A a; // OK, as you explicitly provide one default constructor
}

Also, according to "C++11 – ISO-IEC 14882-2011" §8.5/6:

If a program calls for the default initialization of an object of a const-qualified type T, T shall be a class type with a user-provided default constructor.

You can check out this thread for more info.

Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
0

Question Should we need to provide a default constructor in c++ if we use a parameter constructor?

Answer It depends.

If you wish to create an array of objects, you must provide a default constructor.

ReadConfigParams array[10];

won't work if you have a don't have a default constructor. Similarly, you can't allocate an array of object using operator new.

ReadConfigParams* arrayPtr = new ReadConfigParams[10];

won't work either.

If you don't have any need for creating arrays, in stack or from heap, not providing a default constructor is fine.

R Sahu
  • 204,454
  • 14
  • 159
  • 270