Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get access to a variable in a class without copying it

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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; 
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading