Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > How to detect overwritten virtual method in base class?

Reply
Thread Tools

How to detect overwritten virtual method in base class?

 
 
macracan
Guest
Posts: n/a
 
      08-23-2007
It has been discussed before, but I still can't find a solution and I
have a need. So here goes:

The problem:
I'm writing a something to handle messages from XWindows. The idea is
to have virtual handlers for different
kind of messages. But XWindows has a feature thereby you have to
subscribe to messages you're interested in.
I was thinking of providing empty handlers by default, and overwrite
them in derived classes. And I would need
to automatically detect which virtual fcts are overwritten, so I can
tell XWindows to which message I wish to subscribe.
Somewhat like so:
struct WindowSink
{
// ...
// default empty handlers
virtual void Move(int x, int y){}
virtual void Draw(){}
};
//...
struct MyWindowSink : public WindowSink
{
// overwrite Draw only
void Draw(){ /*some different behavior*/}
};
void Subscribe(WindowSink &sink)
{
static WindowSink sinkref; // some reference to compare with
long mask = 0;
// figure out which messages to subscribe to
if (&sinkref.Move != &sink.Move) mask |= 1;
if (&sinkref.Draw != &sink.Draw) mask |= 2;

// subscribe to messages based on mask
XSelectInput(/* some other params */, mask);
}
int main()
{
MyWindodwSink sink;
//...
Enable(sink);
// ...
return 0;
}

Now as the group already knows, the lines
if (&sinkref.Move != &sink.Move) mask |= 1;
if (&sinkref.Draw != &sink.Draw) mask |= 2;
are not valid C++ code anymore.
Is there any way I can write it?

BTW, I've looked into rtti (didn't find solution), and low level non-
portable magic (got lost and gave up).
I haven't thought it through completely, but am quite sure I can solve
the problem if I use something other then
virtual functions. I could use functionoids (hope I got the right word
here) or could emulate the virtual fct mechanism completely under my
control. The first alternative is not as elegant as using virt
functions (and lacks from data members being inaccessible inside
functionoids), while the second is downright ugly.
Thanx,
Adrian

 
Reply With Quote
 
 
 
 
Gianni Mariani
Guest
Posts: n/a
 
      08-23-2007
macracan wrote:
....
> Is there any way I can write it?



How about this:

// override check helper class
struct OverriddenCheck
{
friend class WindowSink;
friend void Subscribe(WindowSink &sink);

bool m_checking;

OverriddenCheck() : m_checking() {}

private:
enum OverrideState { Overridden, Default };

public:
void IsOverridden()
{
if ( m_checking ) throw Overridden;
}

private:
void IsDefault()
{
if ( m_checking ) throw Default;
}

}

struct WindowSink
{
OverriddenCheck m_check;

// ...
// default empty handlers
virtual void Move(int x, int y)
{
IsDefault();
}
virtual void Draw()
{
IsDefault();
}

private:
void IsDefault() // can only be called by methods in WindowSink
{
m_check.IsDefault();
}
};
//...
struct MyWindowSink : public WindowSink
{
// overwrite Draw only
void Draw()
{
m_check.IsOverridden();
}
};


void Subscribe(WindowSink &sink)
{
static WindowSink sinkref; // some reference to compare with
long mask = 0;

sink.m_check.m_checking = true;

try {
sink.Move(0,0);
// improperly implemented sink
abort();
} catch ( OverriddenCheck::OverrideState l_override )
if ( l_override == Overridden ) mask |= 1;
}

try {
sink.Draw();
// improperly implemented sink
abort();
} catch ( OverriddenCheck::OverrideState l_override )
if ( l_override == Overridden ) mask |= 2;
}

// there is probably some kind of template you can use to
// eliminate most of the try-catch blocks and write somthing like:

CheckOverride( sink, &WindowSink:raw, mask, 1 );
CheckOverride( sink, &WindowSink::Move, mask, 2 );


sink.m_check.m_checking = false;

// subscribe to messages based on mask
XSelectInput(/* some other params */, mask);
}
int main()
{
MyWindodwSink sink;
//...
Enable(sink);
// ...
return 0;
}
 
Reply With Quote
 
 
 
 
macracan
Guest
Posts: n/a
 
      08-24-2007
On Aug 23, 7:13 pm, Gianni Mariani <gi3nos...@mariani.ws> wrote:
....

The idea has merit, in the sense that calling a virtual function seems
to be just about the only reliable way to figure out where it lands
you. While I have no problem calling in members in WindowSink, I think
it would be weird to mandate a call through methods of MyWindowSink.
Not that it would force a certain syntax, because that can be
eliminated. I'm more worried about side-effects that 'faking' a
message from XWindows would have.
A fix would be to instead implement the handler in the virtual
function, rather link the virtual fct in MyWindowSink with the actual
handler via a puch-through mechanism: the first call establishes the
route followed in subsequent calls. And yet it seems strained...

More mulling required...

A

PS. this issue kinda reminds me of quantum mechanics. You don't know
the state of a qbit (value of a virtual pointer) until you measure it
(invoke it), but by that time you've altered the state (triggered
possible side-effects). How do you then figure out where a virtual
pointer points without calling it??? Hmmm... C++ has quantum
uncertainty...

 
Reply With Quote
 
Alf P. Steinbach
Guest
Posts: n/a
 
      08-24-2007
* macracan:
> It has been discussed before, but I still can't find a solution and I
> have a need. So here goes:
>
> The problem:
> I'm writing a something to handle messages from XWindows. The idea is
> to have virtual handlers for different
> kind of messages. But XWindows has a feature thereby you have to
> subscribe to messages you're interested in.
> I was thinking of providing empty handlers by default, and overwrite
> them in derived classes. And I would need
> to automatically detect which virtual fcts are overwritten, so I can
> tell XWindows to which message I wish to subscribe.
> Somewhat like so:
> struct WindowSink
> {
> // ...
> // default empty handlers
> virtual void Move(int x, int y){}
> virtual void Draw(){}
> };
> //...
> struct MyWindowSink : public WindowSink
> {
> // overwrite Draw only
> void Draw(){ /*some different behavior*/}
> };
> void Subscribe(WindowSink &sink)
> {
> static WindowSink sinkref; // some reference to compare with
> long mask = 0;
> // figure out which messages to subscribe to
> if (&sinkref.Move != &sink.Move) mask |= 1;
> if (&sinkref.Draw != &sink.Draw) mask |= 2;
>
> // subscribe to messages based on mask
> XSelectInput(/* some other params */, mask);
> }
> int main()
> {
> MyWindodwSink sink;
> //...
> Enable(sink);
> // ...
> return 0;
> }
>
> Now as the group already knows, the lines
> if (&sinkref.Move != &sink.Move) mask |= 1;
> if (&sinkref.Draw != &sink.Draw) mask |= 2;
> are not valid C++ code anymore.
> Is there any way I can write it?
>
> BTW, I've looked into rtti (didn't find solution), and low level non-
> portable magic (got lost and gave up).
> I haven't thought it through completely, but am quite sure I can solve
> the problem if I use something other then
> virtual functions. I could use functionoids (hope I got the right word
> here) or could emulate the virtual fct mechanism completely under my
> control. The first alternative is not as elegant as using virt
> functions (and lacks from data members being inaccessible inside
> functionoids), while the second is downright ugly.


In order to land on a good solution you have to consider also dispatch
to the event handler functions, and extensibility, i.e. adding new ones.

And that general problem is quite complex.

I remember having a long discussion with Andrei Alexandrescu over in
comp.lang.c++.moderated about this. Andrei maintained that this problem
showed the need for language support for post-constructors in C++, I
maintained that it did not, but then, the concrete problem wasn't
explained until well into the debate where I'd already made my stand.
Anyways, the solution sketch below uses the idea of post-construction:

<code>
#include <cstddef>
#include <map>
#include <memory>

#include <iostream>
#include <ostream>

void say( char const s[] ) { std::cout << s << std::endl; }

namespace windowEvent
{
struct Data { long id; Data( long x ): id( x ) {} };

class Dispatcher
{
public:
virtual void dispatch( Data const& ) = 0;
};

class Handler;
};

class WithFinalInit
{
template< typename T> friend
std::auto_ptr<T> fullyInitialized( std::auto_ptr<T> );

public:
struct Obscurity {};

static void* operator new( std::size_t size, Obscurity const& )
{
return :perator new( size );
}

static void operator delete( void* p, Obscurity const& )
{
:perator delete( p );
}

virtual ~WithFinalInit() {}

private:
virtual void doFinalInit() = 0;
};

template< typename T >
std::auto_ptr<T> fullyInitialized( std::auto_ptr<T> p )
{
static_cast<WithFinalInit*>( p.get() )->doFinalInit();
return p;
}

#define NEW_WINDOW( type, args ) \
fullyInitialized( std::auto_ptr<type>( \
new((WithFinalInit::Obscurity())) type args ) \
)

class WindowWithEvents
: public WithFinalInit
, protected windowEvent:ispatcher
{
friend class windowEvent::Handler;
friend class Window;

private:
typedef std::map<long, windowEvent:ispatcher*> EventMap;
EventMap myEvents;

void addEventHandler( long id, windowEvent:ispatcher& handler )
{
say( "Adding event handler" );
myEvents[id] = &handler;
}

virtual void dispatch( windowEvent:ata const& eventData )
{
EventMap::const_iterator const it = myEvents.find( eventData.id );
if( it != myEvents.end() )
{
windowEvent:ispatcher* const handler = it->second;
handler->dispatch( eventData );
}
}

virtual void doFinalInit()
{
long mask = 0;
for(
EventMap::const_iterator it = myEvents.begin();
it != myEvents.end();
++it
)
{
mask |= it->first;
}
say( "XSelect()" );
//XSelectInput(/* some other params */, mask);
}

WindowWithEvents()
{ say( "WindowWithEvents::<init>() finished" ); }

public:
virtual ~WindowWithEvents() {}
};

class Window: public WindowWithEvents
{
// Note: this class is necessary even without any member functions.
public:
void testDispatch( long id ) { dispatch( id ); }
};

namespace windowEvent
{
class Handler: public Dispatcher
{
protected:
Handler( WindowWithEvents& w, long id )
{
w.addEventHandler( id, *this );
say( "Handler::<init>() finished" );
}
};

class Move: public Handler
{
protected:
virtual void dispatch( Data const& eventData )
{
onMove( 123, 456 );
}

public:
Move( WindowWithEvents* w ): Handler( *w, 1 )
{ say( "Move::<init>() finished" ); }

virtual void onMove( int x, int y ) = 0;
};

class Draw: public Handler
{
protected:
virtual void dispatch( Data const& eventData )
{
onDraw();
}

public:
Draw( WindowWithEvents* w ): Handler( *w, 2 )
{ say( "Draw::<init>() finished" ); }

virtual void onDraw() = 0;
};
} // namespace windowEvent


//------------------------ Client code:

struct MyWindow
: Window
, windowEvent::Move
, windowEvent:raw
{
protected:
virtual void onMove( int x, int y ) { say( "Moving" ); }
virtual void onDraw() { say( "Drawing" ); }

public:
MyWindow()
: windowEvent::Move( this )
, windowEvent:raw( this )
{ say( "MyWindow::<init>() finished" ); }

~MyWindow() { say( "MyWindow::<destroy>()" ); }
};

int main()
{
std::auto_ptr<MyWindow> w = NEW_WINDOW( MyWindow,() );
w->testDispatch( 1 );
w->testDispatch( 2 );
}
</code>

<output>
WindowWithEvents::<init>() finished
Adding event handler
Handler::<init>() finished
Move::<init>() finished
Adding event handler
Handler::<init>() finished
Draw::<init>() finished
MyWindow::<init>() finished
XSelect()
Moving
Drawing
MyWindow::<destroy>()
</output>

It's an interesting question whether this program exhibits formally
Undefined Behavior.

Disclaimer: only tested with one (old) compiler.

Cheers, and hth.,

- Alf

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
Any way to detect the absense of virtual destructor in base class? Qi C++ 16 11-26-2011 12:16 PM
SAX parser: problems with overwritten characters method leo Java 1 04-13-2005 02:26 PM
I see no difference in an inheirited non-virtual method and an inheirited virtual method jlopes C++ 7 11-19-2004 07:47 PM
Overwritten method has no access to local variable if it contains field data Daniel Java 5 07-22-2004 09:11 AM



Advertisments