2

I stumbled uppon this code and I am quite confused on how it compiles since one of the function from A refers to static B. Also what it's suppose to do.

where B is derived from A.

In A.h file

static A*   instance();

in B.h

static B* instance() { return dynamic_cast<B*>(A::instance()); }

in B.cpp

A* A::instance()
{
    static B s_instance;
    return &s_instance;
}

Class definitions and such were omitted to lighten the code.

DogDog
  • 4,400
  • 12
  • 42
  • 61

1 Answers1

1
  • A::instance() gives you a A* that points to a B. Always the same B.
  • B::instance() gives you the result of A::instance(), dynamic_casted to B*.

There is no reason for this to cause a compilation failure (except that definitions of A and B are missing, that is).

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
  • Is there another way to do this type of thing? – DogDog Feb 22 '12 at 15:59
  • @Apoc: That entirely depends on what the code is using these functions for. What problem are you trying to solve? – Lightness Races in Orbit Feb 22 '12 at 16:03
  • Having 2 types of singletons, where one is derived from the other, but only having one instance for both types. – DogDog Feb 22 '12 at 16:06
  • 2
    @Apoc: Putting the object inside `B::instance()`, and having `A::instance()` convert the pointer implicitly, would be neater and wouldn't require the types to be polymorphic. Not using a singleton at all would be even [better](http://stackoverflow.com/questions/137975). – Mike Seymour Feb 22 '12 at 16:10
  • @Mike Seymour, well for not using the singleton, I guess I'll to read more about it and propose that to the team if I find it suitable. That's how they've been dealing with this type of problem for quite a long time. – DogDog Feb 22 '12 at 16:31
  • 2
    @Apoc What type of problem? I've never seen a need for a singleton. – Peter Wood Feb 22 '12 at 16:54
  • In the project it's used to shared entities among several objects. Lets say object A,B,C,D need to make use of several Widgets. I was told to just put them in a manager (singleton), To share them. – DogDog Feb 22 '12 at 17:20
  • "I was told to" is not a reason. – Lightness Races in Orbit Feb 22 '12 at 17:42
  • To someone with little experience, and who doesn't know a better alternative, I think it's fair. – DogDog Feb 22 '12 at 20:01