LearnFrenzy
Sign in Take a free test

Classes and Objects · Find the Error · Question 5

Error: initializing a non-const static member in the class Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>

class Visitor {
public:
    static int count = 0;
    Visitor() { ++count; }
};

int main() {
    Visitor a, b;
    std::cout << Visitor::count << '\n';
    return 0;
}
  • A count must be private
  • B A non-const static data member cannot have an in-class initializer unless it is declared inline: static inline int count = 0; (C++17) Correct
  • C Visitor needs a destructor
  • D Static members cannot be incremented
Correct Answer: Option B

Before C++17 the alternative is to declare it in the class and define int Visitor::count = 0; in one source file.

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