Nobody wrote:
On Sun, 24 Jul 2011 17:40:02 +0200, TP wrote:
I convert a Python/Qt program (PyQt) in C++/Qt. The programmer has used
the duck typing of Python, thus I would like to have duck typing in
C++,
Is it possible in C++?
Duck typing is just interfaces, which are just classes with no member
variables and only pure virtual methods.
I have tried to convert the example of the webpage I mentioned:
#include<iostream>
class InterfaceDuck
{
public:
virtual void Quack() = 0;
};
class Daffy
{
public:
void Quack()
{
std::cout<< "coin coin"<< std::endl;
}
};
int main( void )
{
InterfaceDuck * d = new Daffy;
d->Quack();
delete d;
return 0;
}
At the compilation, I obtain:
$ g++ -Wall test.cpp
test.cpp: In function ?int main()?:
test.cpp:21:21: error: cannot convert ?Daffy*? to ?InterfaceDuck*? in
initialization
Now, if I replace the line:
InterfaceDuck * d = new Daffy;
by:
InterfaceDuck * d = (InterfaceDuck *) new Daffy;
It compiles without warning, but it segfaults at the execution.
So, what is the correct way of doing things with pure virtual classes?
Thanks,
You will have to derive Daffy from InterfaceDuck. Of course that way it