Subclassing std::string confusion?

Discussion in 'C++' started by petertwocakes, Nov 28, 2009.

  1. Hi

    class StringSubClass : public string {
    public:
    StringSubClass();
    StringSubClass(const char* v) : string(v) {} // casting constructor
    virtual ~StringSubClass(){};
    StringSubClass& operator=(const string& str) { return
    (StringSubClass&)this->assign(str); }

    };

    If I don't have the casting constructor, then
    StringSubClass str = "abc";
    fails;

    If I don't have the operator=, then
    StringSubClass str;
    str = "abc";
    fails;

    But, if I have them both I get the error:
    ambiguous overload for 'operator=' in 'sub = "abc"'

    How can I define it such that all of the following work?

    StringSubClass subStr = "abc";
    subStr = "abc";
    string stdStr;
    StringSubClass subStr2 = stdStr;
    subStr2 = stdStr;

    I've tried many permutations, but at least one always fails for either
    having no definition, or ambiguous overload.

    Thanks
    petertwocakes, Nov 28, 2009
    #1
    1. Advertising

  2. petertwocakes

    Balog Pal Guest

    "petertwocakes" <>
    > But, if I have them both I get the error:
    > ambiguous overload for 'operator=' in 'sub = "abc"'


    so make another overload of = to take const char *.
    Balog Pal, Nov 28, 2009
    #2
    1. Advertising

  3. On 28 Nov, 12:28, "Balog Pal" <> wrote:
    > "petertwocakes" <>
    >
    > > But, if I have them both I get the error:
    > > ambiguous overload for 'operator=' in 'sub = "abc"'

    >
    > so make another overload of = to take const char *.


    Many thanks Balog, this works now.

    class StringSub : public string
    {
    public:
    // Constructors
    StringSub();
    StringSub(const char* ch) : string(ch) {}
    StringSub(const string& str) : string(str) {}
    virtual ~StringSub(){};
    //-- Operator"="
    StringSub& operator=(const string& str) { return (StringSub&)this-
    >assign(str); }

    StringSub& operator=(const char* ch) { return (StringSub&)this->assign
    (ch); }

    ....

    }
    petertwocakes, Nov 28, 2009
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Peter Jansson
    Replies:
    5
    Views:
    6,304
    Ivan Vecerina
    Mar 17, 2005
  2. Vinu
    Replies:
    4
    Views:
    357
    Jim Langston
    Jul 7, 2005
  3. Fei Liu
    Replies:
    9
    Views:
    442
  4. Jeffrey Walton
    Replies:
    10
    Views:
    938
    Mathias Gaunard
    Nov 26, 2006
  5. Andrew Tomazos
    Replies:
    9
    Views:
    742
    Joshua Maurice
    Dec 2, 2011
Loading...

Share This Page