简体   繁体   中英

const object or private/const data members (variables) in C++?

We know that const object members cannot be modified once declared but what is the real use of them? We can individually declare variables to be const inside the class or declare them private .

If there is any other significance of const object in C++ , then please mention that too.

const is one of the most elementary subjects in C++, in my opinion. Something that is way too often overlooked.

Generally const has three use cases:

  • Allowing the compiler to optimize more aggressively
  • Allowing the compiler to point out our mistakes when we accidentally try to change a const value
  • Convey intend by specifying that we do not want an object changed

In the case of a const member of a class, we force the object to be initialized during instantiation of the class. Preventing us from accidentally changing it's value in member functions. Which is the big difference to just using a private member variable. We still can accidentally change a private member variable anywhere inside the class.

One of the most useful ways to use const is with parameters:

  • This can allow major optimization for the compiler, for various reasons that are out of scope of this answer.
  • And in the case of const references, the compiler can prevent you from accidentally changing the value of that reference.
  • Most importantly, it allows you to define the signature of your function in a more clarifying way.

I luckily use this once(so far). And i never thought i would need to use a const in a member variable.

class TypeA {
protected:
    DataX const* m_data;        //get a pointer to a data that shouldn't be modified even inside the class.
public:
    TypeA(DataX const* p){
        m_data = p;
    }
    auto& getData(){ return *m_data; }   //will return DataX const&
}

For the private member variables, i think they are best for helper-variables in the current class that are really not part of the object logically. Maybe for caching, temporary holder of some data that should be there for a time duration, a counter for an algorithm, etc. And they are only used and should be used in the current class. You don't want other programmers to use them in the derived class because they have a very special use so you hide them in private .

Another example for const member are for constant values aside for enum s. I prefer enum over a variable that takes storage but some programmer prefer following on what they used to however you convinced them not to(maybe i'm wrong, and they are really correct, and maybe in the future for some reason the const in the language changed, and then using const might be better.)

class TypeA {
public:
     const int HEY_VALUE = 101;
     const int YOH_VALUE = 102;
     const int HELP_VALUE = 911;
     const float MIN_SOMETHING = 0.01;
     static const int HELLO_EARTH = 10;
     //...

}

I can't find this specific code of mine, but i think i used & instead of const* . I used it like this.

class TypeA {
protected:
    DataX& m_data;        
public:
    TypeA(DataX& p):m_data(p){   //you can only set this once in the constructor

    }
    auto& getData(){ return m_data; }   //will return DataX const&
}

I really prefer using . instead of -> for personal reasons so I really pushing myself to achieve the syntax i want and i came with these weird solutions. It's fun because I discovered that those weird approaches are still valid and achievable in c++.


Update

If there is any other significance of const object in C++, then please mention that too.

Maybe you can const some filler bytes on specific part of the class.

class TypeA {
protected:
     const int HEADER_BYTES = 0x00616263;
     int m_data1;
     int m_data2;
     const uint8_t ANOTHER_FILLER_FOR_SOME_REASON = 0xffffffff; //maybe forcing offset address, or alignment, etc.
     int m_anotherData;
}

To answer your question literally:

If you make members of a class const , that applies to every instance of the class, but only to the members that you made const .

If you make an object const , that applies to a single instance of that class, but it does apply to all members of that instance.

Generally, const keyword is being used to improve readability of the code you are writing.

However, in some cases const can also allow compiler optimizations. Let's see the following code snippet:

int const i = 1;
fun(&i);
printf("%d\n", i);

Here, trying to modify the variable i would cause an Undefined Behaviour. Therefore, the compiler will assume modification won't be even tried so it will pass the value 1 to the printf function.

Same is valid for const data members.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM