Can Constructor argument have value assigned to it?

class UsbSocket : public Socket
    struct USBStatus
      char txReady       : 1;
      char rxReady       : 1;
      char hw_connected  : 1;
      char connected     : 1;
      char suspended     : 1;
      char rxRetry       : 1;
      char txFull        : 1;

    /// <summary>Constructor
    /// </summary>
    UsbSocket(unsigned short tId = 0);

In above constructor,  is argument assigned value of 0.  Can value be passed to this constructor?
Who is Participating?
evilrixConnect With a Mentor Senior Software Engineer (Avast)Commented:
A constructor is just a function (all be it a slightly special one) and, yes, it can have a default value just like any other function can.

In your example the default value for the parameter is, indeed, zero but you can override that by passing an explicit argument yourself.
naseeamAuthor Commented:
What's the use of assigning default value when it will be overridden when the functions is called?
evilrixConnect With a Mentor Senior Software Engineer (Avast)Commented:
Well, it doesn't have to be. The idea is it's a sensible default but it gives you, the consumer of that class, the ability to override it. For example, a bank account class might default to a balance of zero but it could be constructed with a balance of more than zero if the customer was planning on paying in at the same time the account is opened.
naseeamAuthor Commented:
What will be the syntax of the function call if customer makes the call with default argument?
jkrConnect With a Mentor Commented:
The syntax would be like

UsbSocket a(2); // explicit argument
UsbSocket b; // default argument

Open in new window


UsbSocket* pa = new UsbSocket(2); // explicit argument
UsbSocket* pb = new UsbSocket; // default argument

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.