Home > OS >  Get access to a variable in a class without copying it
Get access to a variable in a class without copying it

Time:11-25

I would like to get access to fields from a class without copying it.

I have a class that stores two variables (simplified version here). In the get_cutting_types method I check where the user inputs true or false and pass the object back by reference. But here I have to use =, meaning the data is copied.

Is there a direct way to pass a field without re-assignment?

class joint
{
    std::vector<char> m_letters;
    std::vector<char> f_letters;

    void get_cutting_types(bool flag, std::vector<char>& letters) {
        if (flag) {
            letters= m_letters;
        } else {
            letters= f_letters;
        }
    }
}

CodePudding user response:

There's a lot to unpack here, but:

  • I don't think you're going to be able to avoid using an "=" sign somwhere along the way. And I don't see any reason that's a problem.

  • If all you want is to return a boolean value: then maybe just add a new public method to your class, e.g.

    public:
      bool isMale() { return <<some test>>; } // Easy peasy!
    

Q: Does this address your concern(s)?

Q: Or do you need "something else"? If so, please clarify.


Sorry maybe there was confusion in the code of variable naming. It is only a return values of char not a single boolean flag.

OK, maybe you want something like this:

public:
    const std::vector<char>& get_cutting_types(bool is_male) {
      return (is_male) ? m_letters : f_letters; 
    }
  • Related