Search code examples
c++stringconstructorclass-constructors

How can we initialize a parametrized constructor as default for a string?


For an integer we can do it as

class A{
  int a;
public:
  A(int x = 0){ a = x; }
};

Solution

  • It is difficult to understand exactly what you are asking. I think you are asking how to specify a default value for a std::string parameter. If that is the case, you can do it like this:

    class A{
      string a;
    public:
      A(string x = ""){ a = x; }
    };
    

    or:

    class A{
      string a;
    public:
      A(const string &x = string()){ a = x; }
    };
    

    Though, in either case, you should be initializing the a member using the constructor's member initialization list instead of the constructor's body:

    class A{
      string a;
    public:
      A(string x = "") : a(x) { }
    };
    

    class A{
      string a;
    public:
      A(const string &x = string()) : a(x) { }
    };