1

I am trying to implement the following class. However, when I try to instantiate an object of the class within its definition and pass "0" as value to initialize the object, i get an error:

"a type specifier is expected".

Can anyone explain how can i remove this error?

class MessageType
{
public:
    static const MessageType  msgEvent(0);

private:
    MessageType();
    virtual ~MessageType();
    MessageType(int);

};

2 Answers 2

1

You need to initialize(define) it outside the class definition in a cpp file.

MessageType const MessageType::msgEvent;

However, Your intent in doing so is not very clear. Are you trying to implement a Singleton Pattern, probably this sample implementation might help, I leave it to you to decide, whether you really need a singleton, inspite of its disadvantages:

//MessageType.h
#include <boost/noncopyable.hpp>
class MessageType: private boost::noncopyable
{
   public:
     static MessageType* instance();

   private:
     MessageType();
     ~MessageType();
     static bool g_initialised;
     // static  initialisation
     static MessageType g_instance;
     // dynamic initialisation
};

// MessageType.cpp
 #include "MessageType.hpp"
 #include <ostream>
 #include <iostream>
 #include <cstring>
 bool MessageType::g_initialised;
    // static  initialisation
MessageType MessageType::g_instance;

    // dynamic initialisation
 MessageType::MessageType()
 {
     g_initialised = true;
 }

 MessageType::~MessageType()
 {
     g_initialised = false;
 }

 MessageType* MessageType::instance()
 {
     return g_initialised ? &g_instance : 0;
 }
Sign up to request clarification or add additional context in comments.

2 Comments

but if i just create an object without supplying an initializing value, it works just fine.
@sufyan siddique: It doesn't work fine, it just compiles. Eventually you'll see linker errors.
1

You can only initialize static member variables in the definition if they are of int type.

class MessageType
{
public:
    static int sCount = 0; // That is fine.
    static std::string sLogName; // That is fine.
    static std::string sLogName("log.txt"); // Fail!
};

There's no way around this rule. If you want to initialize a static member variable, then you have to do it in the cpp:

std::string MessageType::sLogName("log.txt"); // fine, in the cpp.

This same rule applies directly to your MessageType instance, and has nothing to do with the fact that the class is of it's own type.

Comments

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.