fork download
#include 
#include 

template < typename T > struct magic
{
    magic() { objects.insert( static_cast(this) ) ; }
    magic( const magic& ) : magic() {}
    magic( magic&& ) : magic() {}
    ~magic() { objects.erase( static_cast(this) ) ; }

    template< typename FN > static void for_each_instance( FN fn )
    { for( T* p : objects ) fn(p) ; }

    static std::unordered_set objects ;
};

template < typename T > std::unordered_set magic::objects ;

struct A : magic
{
    void foo( int i, char c )
    { std::cout << "A::foo( " << this << ", " << i << ", " << c << " )\n" ; }
};

struct B : magic
{
    void bar( double d ) const
    { std::cout << "B::bar( " << this << ", " << d << " )\n" ; }
};

int main()
{
    A one ;
    B two ;
    {
        A three = one ;
        B b[2] ;
        A::for_each_instance( []( A* p ) { p->foo( 99, 'X' ) ; } ) ;
        B::for_each_instance( []( B* p ) { p->bar( 12.8 ) ; } ) ;
    }
    std::cout << "------------------------\n" ;
    A::for_each_instance( []( A* p ) { p->foo( -7, 'Y' ) ; } ) ;
    B::for_each_instance( []( B* p ) { p->bar( 123.45 ) ; } ) ;
}
stdin
Standard input is empty
stdout
A::foo( 0xbfaa5073, 99, X )
A::foo( 0xbfaa5071, 99, X )
B::bar( 0xbfaa5077, 12.8 )
B::bar( 0xbfaa5076, 12.8 )
B::bar( 0xbfaa5072, 12.8 )
------------------------
A::foo( 0xbfaa5071, -7, Y )
B::bar( 0xbfaa5072, 123.45 )