4

I need to create a static object inside a class definition. It is possible in Java, but in C++ I get an error:

../PlaceID.h:9:43: error: invalid use of incomplete type ‘class
PlaceID’ ../PlaceID.h:3:7: error: forward declaration of ‘class
PlaceID’ ../PlaceID.h:9:43: error: invalid in-class initialization of static data 

My class looks like this:

#include <string>

class PlaceID {

public:

    inline PlaceID(const std::string placeName):mPlaceName(placeName) {}

    const static PlaceID OUTSIDE = PlaceID("");

private:
    std::string mPlaceName;
};

Is it possible to make an object of a class inside this class? What are prerequisites that it must hold?

0

1 Answer 1

12

You can't define the member variable because the class isn't fully defined yet. You have to do like this instead:

class PlaceID {

public:

    inline PlaceID(const std::string placeName):mPlaceName(placeName) {}

    const static PlaceID OUTSIDE;

private:
    std::string mPlaceName;
};

const PlaceID PlaceID::OUTSIDE = PlaceID("");
Sign up to request clarification or add additional context in comments.

9 Comments

I was thinking about this, but my concern was about memory. But now I realized, that memory used in both options are actually equal. BTW, in your answer should be "const static" but you're right anyway.
@Benjamin The static keyword is only needed when declaring the variable inside the class, and not when defining it outside.
Getting a compiler warning for multiple declarations of the static const in classes where I include this class. LNK4006: already defined in x.obj
@MNCODE Definitions must happen only once. Move the definition to a single source file.
Thank you I defined the static const in the header file after class definition. It works in the source file.
|

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.