Search code examples
c++stringreferenceclass-methodclass-members

C++: String member alias in method


My constructor:

bnf::bnf(string encoded)
{
    this->encoded = encoded;
}

copies the string data to a member. (Or does it..?)

I will have a recursive decode method, but would like to avoid writing this->encoded all the time.

How can I validly and simply create an alias/reference to the member within a method?

Will this have overhead best avoided?


Solution

  • You can just pass in a different named parameter. This is assuming that encoded is a private string member of your bnf class

    bnf::bnf(string en)
    {
        encoded = en;
    }
    

    In your other functions, you still don't need to write this if you don't want to:

    void bnf::printCode(){
         cout << encoded << endl;
    }
    

    Assuming your class looks like this:

    class bnf{
        public:
             bnf(string en};
             void printCode();
             //<some other functions>
        private:
             string encoded;
    }