userdefinedTypes

constexpr – Variables and Objects

If you declare a variable as constexpr the compiler will evaluate them at compile time. This holds not only true for built-in types but also for instantiations of user-defined types. There are a few serious restrictions for objects to evaluate at compile time.

 

To make it easier, I will use built-in types like bool, char, int, and double. I will call the remaining data types user-defined data types. These are, for example, std::string, types from the C++ library, and user-defined data types. User-defined types typically hold built-in types.

Variables

By using the keyword constexpr the variable becomes a constant expression.

constexpr double myDouble= 5.2;

 

Therefore, I can use the variable in contexts requiring constant expression. For example, if I want to define the size of an array. This has to be done at compile time.

For the declaration of constexpr variable, you have to keep a few rules in mind.

The variable

Rainer D 6 P2 500x500

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (open)
  • "Generic Programming (Templates) with C++": October 2024
  • "Embedded Programming with Modern C++": October 2024
  • "Clean Code: Best Practices for Modern C++": March 2025
  • Do you want to stay informed: Subscribe.

     

    • is implicitly const.
    • has to be initialized.
    • requires a constant expression for initialization.

    The rule makes sense. If I evaluate a variable at compile time, the variable can only depend on values that can be evaluated at compile time.

    The invocation of the constructor creates the objects. The constructor has a few special rules.

    User-defined types

    The class MyDistance from the post Constant expressions with constexpr fulfills all requirements to be initialized at compile time. But what are the requirements?

    A constexpr constructor can only be invoked with constant expressions.

    1. can not use exception handling.
    2. has to be declared as default or delete or the function body must be empty (C++11).

    The constexpr user-defined type

    1. can not have virtual base classes.
    2. requires that each base object and each non-static member has to be initialized in the initialization list of the constructor or directly in the class body. Consequently, it holds that each used constructor (e.g of a base class) has to be constexpr constructor and that the applied initializers have to be constant expressions.

    Sorry, but the details are even harder: cppreference.com. To make the theory obvious I define the class MyInt. MyInt shows the just mentioned points. The class has in addition constexpr methods. There are special rules for constexpr methods and functions. These rules will follow in the next post, so we can concentrate in this post on the essentials about variables and user-defined types.

     

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    // userdefinedTypes.cpp
    
    #include <iostream>
    #include <ostream>
    
    class MyInt{
    public:
      constexpr MyInt()= default;
      constexpr MyInt(int fir, int sec): myVal1(fir), myVal2(sec){}
      MyInt(int i){
    	myVal1= i-2;
    	myVal2= i+3;
      }
      
      constexpr MyInt(const MyInt& oth)= default;
      constexpr MyInt(MyInt&& oth)= delete;
      
      constexpr int getSum(){ return myVal1+myVal2; }
      
      friend std::ostream& operator<< (std::ostream &out, const MyInt& myInt){
        out << "(" << myInt.myVal1 << "," << myInt.myVal2 << ")";  
        return out;
      }
    
    private:
      int myVal1= 1998;
      int myVal2= 2003;
    
    };
    
    int main(){
      
      std::cout << std::endl;
      
      constexpr MyInt myIntConst1;
      MyInt myInt2;
      
      constexpr int sec= 2014;
      constexpr MyInt myIntConst3(2011,sec);
      std::cout << "myIntConst3.getSum(): " << myIntConst3.getSum() << std::endl;
      
      std::cout << std::endl;
      
      int a= 1998;
      int b= 2003;
      MyInt myInt4(a,b);
      std::cout << "myInt4.getSum(): " << myInt4.getSum() << std::endl;
      std::cout << myInt4 << std::endl;
      
      std::cout << std::endl;
      
      // constexpr MyInt myIntConst5(2000);  ERROR
      MyInt myInt6(2000);
      std::cout << "myInt6.getSum(): " << myInt4.getSum() << std::endl;
      std::cout << myInt6 << std::endl;
      
      // constexpr MyInt myInt7(myInt4); ERROR
      constexpr MyInt myInt8(myIntConst3);
      
      std::cout << std::endl;
      
      int arr[myIntConst3.getSum()];
      static_assert( myIntConst3.getSum() == 4025, "2011 + 2014 should be 4025" );
      
    }
    

     

    The class MyInt has three constructors. A constexpr default constructor (line 8) and a constructor taking two (line 9) and taking one argument (line 10). The constructor with two arguments is a constexpr constructor. Therefore, its body is empty. This holds not true for the non-constexpr constructor with one argument. The definition goes on with a defaulted copy-constructor (line 15) and a deleted move-constructor (line 16).  Additionally, the class has two methods, but only the method getSum is a const expression. I can only define the variables myVal1 and myVal2 (lines 26 and 27) in two ways if I want to use them in constexpr objects. At first, I can initialize them in the initialization list of the constructor (line 9); second, I can initialize them in the class body (lines 26 and 27). The initialization in the initialization list of the constructor has a higher priority. It’s not allowed to define both variables in the body of the constructor (lines 11 and 12). 

    To put the theory to practice, here is the output of the program.

     

     userdefinedTypes

    The program shows a few special points:

    • You can use a constexpr constructor at run time. Of course, there is no constant expression (line 36 and line 46).
    • If you declare a non-constant expression as constexpr, you will get a compiler error (lines 52 and 57).
    • constexpr constructors can coexist with non-constexpr constructors. The same holds for the methods of a class.

    The key observation is: A constexpr object can only use constexpr methods.

    But stop. What’s the story about the two last lines, 62 and 63, in the main function?

    The proof

    Quite straightforward. They prove that the call myIntConst3.getSum() is performed at compile time.

    At first, C++ requires that an array’s size be a constant expression. Second, static_assert evaluates its expression at compile time. If not, static_assert will not compile.

    If I replace line 63

    static_assert( myIntConst3.getSum() == 4025, "2011 + 2014 should be 4025" );
    

    with the line

    static_assert( myIntConst4.getSum() == 4001, "1998 + 2003 should be 4001" );
    

    , I will get a compiler error.

     userdefinedTypesError

    What’s next?

    I think you know it already. In the next post, I will write about contexpr functions. They have with C++11 a lot of restrictions that will almost disappear with C++14. constexpr functions in C++14 feel almost like normal functions. Of course, my points about functions will also hold for methods of classes.

     

     

     

     

     

     

    Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery, Matt Godbolt, and Honey Sukesan.

    Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Modernes C++ GmbH

    Modernes C++ Mentoring (English)

    Do you want to stay informed about my mentoring programs? Subscribe Here

    Rainer Grimm
    Yalovastraße 20
    72108 Rottenburg

    Mobil: +49 176 5506 5086
    Mail: schulung@ModernesCpp.de
    Mentoring: www.ModernesCpp.org

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *