0

Lane.h

class Lane{
    //other declarations..
public:
    Lane(){}
    static Lane left_line;
    static Lane right_line;
};

Lane.cpp

Lane Lane::left_line;

main.cpp

int main(){
    Lane::left_line();  //doesn't work

What am I doing wrong or am I doing everything wrong. I am actually confused about how the static objects work exactly.

10
  • Show us the error messages. Commented Aug 26, 2017 at 14:33
  • @BrianRodriguez "call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type" Commented Aug 26, 2017 at 14:37
  • @Mat I am trying to initialize the left_line object through constructor. Commented Aug 26, 2017 at 14:38
  • 2
    I'm not sure I understand why you want to do that, the goal of a static object is to be initialized once and used everywhere without thinking about it again. Maybe there's different behavior you're actually interested in seeing? Commented Aug 26, 2017 at 14:50
  • 1
    @user3673025 Alright, so I suggest either rewording your question to include this information, or to start a new one since the correct solution has already been given. Also, FYI, we call these types of problems an "XY Problem"; keep them in mind in the future to get quicker help! Commented Aug 26, 2017 at 15:14

1 Answer 1

1

static members get declared inside a class and initialized once outside the class. There is no need to call the constructor once again. I've added a method to your Lane class to make it clearer.

class Lane{
    //other declarations..
public:
    Lane(){}
    static Lane left_line; //<declaration
    static Lane right_line;

   void use() {};
};

Lane.cpp

Lane Lane::left_line; //< initialisation, calls the default constructor of Lane

main.cpp

int main() {
  // Lane::left_line(); //< would try to call a static function called left_line which does not exist
  Lane::left_line.use(); //< just use it, it was already initialised
}

You can make the initialisation even more obvious by doing this:

Lane Lane::left_line = Lane();

in Lane.cpp.

Sign up to request clarification or add additional context in comments.

1 Comment

No. Static initialisation takes place before main gets called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.