0

I am having trouble calling a member function of a singleton class. I have the following

// my_class.hpp

class my_class {

    friend struct singleton;

    int m_x;

    my_class(int x)
    : m_x(x) {}

    // other private constructors here

public:

    const auto& get() const {
        return m_x;
    }
};


struct singleton {

    static auto& instance() {
        static my_class x(42);
        return x;
    }
};

When trying to call singleton::instance().get() outside of main(), the compiler says "expected function body after function declarator". Here is the relevant main file:

singleton::instance().get();

int main() {}

I have found that moving the call inside main everything works fine. I have also found that storing the result outside of main also works fine, like so

auto v = singleton::instance().get();

int main() {}

What I'd like to understand is why calling it outside of main() fails and if there is a workaround that doesn't require storing the result. Thank you.

linuxfever
  • 3,763
  • 2
  • 19
  • 43
  • Why the downvote? – linuxfever Aug 01 '17 at 11:08
  • 1
    I didn't downvote, but your question is confusing as it has nothing to do with singletons but is about statements out of functions or declarations. – stefaanv Aug 01 '17 at 11:13
  • Why do you think you should make the call while you don't intend to use the value? –  Aug 01 '17 at 11:15
  • Possible duplicate of [Is main() really start of a C++ program?](https://stackoverflow.com/questions/4783404/is-main-really-start-of-a-c-program) – stefaanv Aug 01 '17 at 11:22

2 Answers2

0

C++ standard says:

3.5 Program and linkage 1 A program consists of one or more translation units (Clause 2) linked together. A translation unit consists of a sequence of declarations.

This line:

auto v = singleton::instance().get();

is declaration of variable, But this line

singleton::instance().get();

is calling methods instance and get, and compiler treats it as declaration of function which is already declared.

ikleschenkov
  • 972
  • 5
  • 11
0

First of all, it's nothing to do with singletons.

main is the entrance of the program. What the compiler do before main are some declarations: variables, functions, classes. auto v = singleton::instance().get(); is fine, it's a declaration of global variable. Obviously, the compiler take singleton::instance().get(); as a declaraton of function, but actually it's not.

walter
  • 1,199
  • 7
  • 13