blackbeltJR
blackbeltJR

Reputation: 51

Inheriting from std::string

So I have this:

class myString : public std::string{

public:

    void translate(){
        std::string phrase = blarg;

        ... Code ...

        blarg = phrase;
    }

Now, I know it's not blarg, but what would I have to put here to access the string associated with the myString string inheritance?

In a main outside of this, I could do:

myString phrase;
phrase = "Roar";

So how do I access the "Roar" in my function?

Everything is included properly.

Upvotes: 1

Views: 2416

Answers (2)

ThomasMcLeod
ThomasMcLeod

Reputation: 7769

Just access the object with the this pointer.

class myString : public std::string
{
    public:

    void translate()
    {
        std::string phrase = *this;
        /*
        ... Code ...
        */
        *static_cast<string*> (this) = phrase;
    }
}

Upvotes: 0

Bryan Chen
Bryan Chen

Reputation: 46598

You are not supposed to do this.

But here is the code

#include <iostream>
#include <string>
#include <vector>

class myString : public std::string{
public:
    using std::string::string; // inheriting the constructors from std::string
    void translate(){
        // `std::string phrase = *this` won't work because no such constructor takes `myString` exist
        std::string phrase(this->c_str(), this->length()); 

        phrase += "2";

        // operator= won't work because type doesn't match
        // it is expecting `myString` type but not `std::string`
        this->assign(phrase); // use assign instead of operator=
    }    
};

int main()
{
    myString m = "test";
    std::cout << m << '\n'; // test
    m.translate();
    std::cout << m << '\n'; // test2
}

online demo

Upvotes: 1

Related Questions