mans
mans

Reputation: 18168

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.

Upvotes: 6

Views: 3665

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122585

You dont need to initialize a string member with an empty string, though it can help to do it anyhows. Consider:

struct foo {
    std::string a;
    std::string b;
    foo() : a("foo") {}
};

Was it by accident or on purpose that b does not get a value in the constructor? I'd prefer

foo() : a("foo"), b() {}

because it makes the intend explicit for no price (not counting a few keystrokes).

Upvotes: 0

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136306

Do I need to initialize std::string

No. std::string default constructor initialises a nice empty string for you.

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.

Remove clutter then:

struct myclass {
    std::string str;
};

Fundamental types though, do not get initialised by default, you need to initialize them explicitly:

struct myclass {
    std::string str;
    int i = 1; // <--- initialize to 1.
};

Upvotes: 8

Related Questions