简体   繁体   中英

Need explanation on this code with polymorphism

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 Ah file

static A*   instance();

in Bh

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.

  • 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_cast ed to B* .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM