sufyan siddique
sufyan siddique

Reputation: 1481

error initializing an object of the same class within class definition - C++

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);

};

Upvotes: 1

Views: 98

Answers (2)

Jeffeb3
Jeffeb3

Reputation: 111

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.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206636

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;
 }

Upvotes: 1

Related Questions