Question

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?

Was it helpful?

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;
}

OTHER TIPS

There is nothing wrong with what you're doing now. It's expressive, clear and correct. Don't try to ruin it.

If you're worried about "overhead" with using the this pointer, don't: it's already as efficient as it could possibly be. There is literally no way to make it faster.

If your question is slightly wrong and all you want to do is mention a member variable inside a member function, then:

struct MyClass
{
   int x;
   void myFunction();
};

void MyClass::myFunction()
{
   this->x = 4;
}

The function is equivalent to:

void MyClass::myFunction()
{
   x = 4;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top