CallingClass::CallingFunc()
{
SomeClass obj;
obj.Construct(*Singleton::GetInstance()); // passing the listener
// Singleton::GetInstance() returns a static pointer.
//Singleton is derived from IListener
}
SomeClass::Construct(const IListener &listener)
{
IListener* pListener = const_cast<IListener*>(&listener);
}
After const_cast
pListener
is null.
Is it possible to perform such typecasting?
Thanks
Two questions:
Without wishing to be unkind I would honestly say that it might be better to start again. There are a couple of issues I would have with this code:
Firstly, the Singleton pattern should ensure that only one of a specific object is ever created, therefore it is usually returned by pointer, reference or some derivative thereof (i.e. boost shared pointer etc.) It need not necessarily be const though and the fact that it is here indicates that the author did not intend it to be used in a non-const way.
Second, you're then passing this object by reference into a function. No need. That's the one of the major features (and drawbacks) of the singleton pattern: You can access it from anywhere. So you could just as easily write:
SomeClass::Construct()
{
IListener* pListener = const_cast<IListener*>(*Singleton::GetInstance());
}
Although this still doesn't really help you. One thing it does do is make your interface a bit clearer. You see, when you write SomeClass::Construct(const IListener&listener)
anyone reading your could reasonably imply that listener
is treated as const
within the function and by using const_cast
, you've broken that implied contract. This is a very good reason that you should not use const_cast
- at least not in these circumstances.
The fundamental question that you need to ask yourself is when your IListener
is const, why do you need to use it in a non-const way within Construct
? Either the singleton should not return a const object or your function should not need it to be non-const.
This is a design issue that you need to sort out before you take any further steps.