LearnFrenzy
Sign in Take a free test

Modern C++ Features (C++11 to C++23) · Predict the Output · Question 18

inline static data members Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 18 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <string>

struct App {
    static inline int instances = 0;                    // C++17: defined right here, no .cpp definition
    static inline const std::string version = "2.1";
    App() { ++instances; }
};

inline int global_hits = 100;                           // one variable even if this header is included many times

int main() {
    App a, b;
    { App c; }
    global_hits += App::instances;
    std::cout << App::instances << ' ' << App::version << ' ' << global_hits << '\n';
    return 0;
}
  • A 3 2.1 103 Correct
  • B 2 2.1 102
  • C 3 2.1 100
  • D 0 2.1 100
Correct Answer: Option A

inline variables give one definition across all translation units, so static members can be initialised inside the class. The counter counts constructions (3), not live objects.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links