Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I assign a class enum based on a private/protected member?

I have a class and need to make the size of one of its protected members publicly available.

I cannot make the field public and don't want to introduce a new field, so I am trying to introduce an enum and assign it to the size of the field, like so:

class MyObject
{
  public:
    enum
    {
        myFieldSize = sizeof(myField),
    };
  protected:
    uint8_t myField;
}

However my compiler tells me that it can't find a declaration for "myField". Is this the expected behavior? I have other public functions that access myField, why is the enum seemingly unable to do so?

like image 782
mbowcutt Avatar asked Jan 01 '23 15:01

mbowcutt


1 Answers

This is one of those instances where the order of what you have in your class matters: myField does not exist at the point sizeof(myField) is reached.

A workaround is to have uint8_t myField; above the enum.

like image 73
Bathsheba Avatar answered Jan 03 '23 04:01

Bathsheba