jeudi 17 mai 2018

Do I need to initialize std::string

I have this code:

class myclass
{
    std::string str;
public:
    void setStr(std::string value)
    { 
        str=value;
    }
    std::string getStr()
    {
        return str;
    }
 }

 main()
 {
   myclass ms;
   std::cout<<ms.getStr()<<std::endl;
 }

when I compile and run this code, there is o error and in windows I am always getting str as "".

Is this always valid?

I need the above behavior in the fact that if user did not call set, str would be always a blank string.

should I initialize str in constructor as follow:

class myclass
{
    std::string str;
public:
    myclass():str(""){}
    void setStr(std::string value)
    { 
        str=value;
    }
    std::string getStr()
    {
        return str;
    }
 }

I want to make sure that behavior is the same on all platform and also make sure that code is as small and neat as possible.

Aucun commentaire:

Enregistrer un commentaire