I was wondering if we could have a class member be named by 2 names, for example my class has the variables _width and _height and I want my code to use _width by either using _width or _rows. I though I could use macros, but is there another way to do it in C++. Also is it a good practice to do so?
Thanks
            Asked
            
        
        
            Active
            
        
            Viewed 100 times
        
    0
            
            
        
        hakuna matata
        
- 3,243
 - 13
 - 56
 - 93
 
- 
                    3It's possible but what's the gain of doing this? – billz Apr 07 '13 at 10:49
 - 
                    It could of course be done with a preprocessor macro, but then _all_ instances of .e.g. `_rows` will be replaced by `_width`, and that might not be suitable everywhere. Also I wouldn't say it's good practice. – Some programmer dude Apr 07 '13 at 10:50
 - 
                    You can use reference. But keep in mind, it takes memory(unless compiler is smart). – KAction Apr 07 '13 at 10:50
 - 
                    1`uint& _rows() { return _width; }` would be one way. But that doesn't gain anything to you. – iammilind Apr 07 '13 at 10:51
 - 
                    In my code I'm using 2D arrays, so I want to be able to use both in case I used one by mistake not to have any problems when doing so – hakuna matata Apr 07 '13 at 10:53
 - 
                    3"use both in case I used one by mistake" ?? Isn't it easier to make sure you don't make that mistake than to write unnecessary code to hide the mistake? – Andrei Apr 07 '13 at 11:07
 - 
                    Compilers are awfully smart nowadays, @KAction. Usually smarter than us! – Cody Gray - on strike Apr 07 '13 at 11:23
 - 
                    As far as I know, compilers are not allowed to reorder struct members. Wiping member out is even worse, is not it, @Cody Gray? – KAction Apr 07 '13 at 14:29
 - 
                    You said a "reference". How does that require reordering struct members or wiping them out? – Cody Gray - on strike Apr 07 '13 at 14:41
 - 
                    Reference is just pointer in disgue. So it takes exactly `sizeof(void *)` memory. Take a look at this: https://gist.github.com/5334967. On my machine, 16 vs 8. @CodyGray – KAction Apr 08 '13 at 07:45
 
2 Answers
2
            
            
        An anonymous union?
class two_names
{
  union
  {
    int width;
    int columns;
  };
};
In C++11 you can even put non PODs in there. Just be sure you know what you are doing.
        StoryTeller - Unslander Monica
        
- 165,132
 - 21
 - 377
 - 458
 
1
            
            
        Try this:
class StrangeOne {
  int _width, _height;
  int &_rows;
public:
  StrangeOne(int width,int height):
    _width(width),
    _height(height),
    _rows(_width)
  {
  };
};
        KAction
        
- 1,977
 - 15
 - 31