Home > database >  Do I have to define a default constructor in C ?
Do I have to define a default constructor in C ?

Time:12-22

In general, say I define my own constructor in such way:

class Numbers
{
public:
Numbers(int a, int b);
}

Would I have to:

  1. Define a new default constructor? I know the default constructor no longer exists once I define my own but I didn't know if it was necessarily / recommended to include one

  2. Do the parameters need to be included in the class? i.e. should I add:

class Numbers
{
private:
int ma;
int mb;
};

Thank you in advance!

CodePudding user response:

  1. That's up for you to decide. A default constructor can be handy and makes life easier in most cases. But if you want the users of your class to always provide numbers, that's fine, too.

  2. Yes, if you want attributes, you need to declare them. C doesn't magically deduce them from constructor arguments

CodePudding user response:

during compile-time 2 constructors are created automatically if given class contains no constructors.

1 - default constructor 2 - copy constructor

if you create one default constructor then constructor created automatically will be replaced by your constructor.

  • Related