0

The std::string class allows assigning its internal value from different types, such as 'char', 'const char*' and 'std::string', with the help of this operator. Which operator is needed to be overloaded in order to achieve the following?

class A {
public:
    A(std::string value)
        : m_value(value)
    {
    }

    // A a = std::string("some value")
    A& operator=(const std::string value) {
        m_value = value;
    }

    // std::string someValue = A("blabla")
    ???? operator ????

private:
    std::string m_value;
};

After that, we should be able to access std::string's functions through the A object, for example:

A a("foo");

printf("A's value: %s \n", a.c_str());
Yves Calaci
  • 1,019
  • 1
  • 11
  • 37
  • not related to your question, but `m_value = value;` should be `m_value = std::move(value);`, and `value` should be non-const. similarly for the constructor – M.M Mar 08 '16 at 20:54
  • @M.M why should std::move() be used in this case? – Yves Calaci Mar 09 '16 at 10:37
  • So that the resources held by `value` can be transferred to `m_value`, instead of making a copy and then destroying the old resource. – M.M Mar 09 '16 at 11:10

1 Answers1

0

You need to make it possible for class A to convert itself to type string.

This looks like:

class A
{
public:
    operator std::string() const { return m_value; }
};

After that, you can do this:

printf("A's value: %s \n", ((std::string)a).c_str());

Alternately, you can overload the -> operator:

class A
{
public:
    const std::string* operator->()const { return & m_value; }
}

printf("A's value: %s \n", a->c_str());

IDEOne link

abelenky
  • 63,815
  • 23
  • 109
  • 159
  • thats almost exactly what I'm looking for. I'm aware of the "operator std::string" (whats the name of this operator by the way?) but casting it to a std::string is really weird. The "->" operator almost does what I really need. Isnt it possible to override the "." operator (which one is this?) so that we could do "a.c_str()" and no pointers would be used/returned? – Yves Calaci Mar 08 '16 at 19:40
  • http://stackoverflow.com/questions/520035/why-cant-you-overload-the-operator-in-c – abelenky Mar 08 '16 at 19:41