[Ns-developers] C++ virtual method overloading and inheritance = disaster?
Sam Jansen
sam.jansen at gmail.com
Tue Jul 8 18:35:27 PDT 2008
2008/7/8 Gustavo Carneiro <gjcarneiro at gmail.com>:
> -----------
> struct Socket
> {
> virtual int Bind () { return -1; }
> virtual int Bind (int address) { return address; }
> };
>
> struct UdpSocket : public Socket
> {
> virtual int Bind () { return 0; }
> };
>
>
> int main(void)
> {
> UdpSocket sock;
> sock.Bind (123);
> }
>
> ---------------
>
> Compiling the above program I get:
>
> gjc at dark-tower:tmp$ g++ test.cc
> test.cc: In function 'int main()':
> test.cc:18: error: no matching function for call to 'UdpSocket::Bind(int)'
> test.cc:11: note: candidates are: virtual int UdpSocket::Bind()
>
> WTF? How come a Bind() method in UdpSocket hides the other Bind() method
> defined in the base Socket class?
>
http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.9
>
> Commenting out the Bind() method in UdpSocket makes the program compile.
>
> I bring this example this because this problem appears in NS-3, and Python
> bindings suffer.
>
> Let me explain (easier than creating a bug report). In
> ns-3-dev/src/node/socket.h,
>
> class Socket {
> [...]
> virtual int Bind (const Address &address) = 0;
> virtual int Bind () = 0;
> [...]
> };
>
> In ns-3-dev/src/node/udp-socket.h:
>
> class UdpSocket : Socket {
> [...]
> // missing: virtual int Bind (const Address &address) = 0;
> virtual int Bind () = 0;
> [...]
> };
>
> Now, what happens next. When I call socketFactory.CreateSocket () from
> Python, the Python bindings know that the method is supposed to return
> Socket*. However, they also know that there exists a known public class
> UdpSocket, and use C++ RTTI (typeid(*pointer)) to discover this is actually
> a UdpSocket object, not a Socket. Finally, when I call socket.Bind
> (address) from Python, the call fails because apparently only one Bind()
> method exists, and not the other.
>
> A long story just to explain why we need to fix UdpSocket, adding the
> missing Bind method. And to vent some of my frustration at this (having
> spent some hours trying to support this use case in PyBindGen only to find
> out that C++ itself does not support it :P).
>
> --
> Gustavo J. A. M. Carneiro
> INESC Porto, Telecommunications and Multimedia Unit
> "The universe is always one step beyond logic." -- Frank Herbert
>
More information about the Ns-developers
mailing list