• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 524
  • Last Modified:

Can Constructor argument have value assigned to it?

class UsbSocket : public Socket
{
  public:
   
    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?
0
naseeam
Asked:
naseeam
  • 2
  • 2
3 Solutions
 
evilrixSenior 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.
0
 
naseeamAuthor Commented:
What's the use of assigning default value when it will be overridden when the functions is called?
0
 
evilrixSenior 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.
0
 
naseeamAuthor Commented:
What will be the syntax of the function call if customer makes the call with default argument?
0
 
jkrCommented:
The syntax would be like

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

Open in new window


or

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

Open in new window

0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now