* Morten Lemvigh:
I'm trying to make something like a Java interface. I have a class, that
needs a distance measure. The distance measure is itself a class passed
to the constructor:
MyClass::MyClass(vector v, DistanceMeasure dm)...
Then I have different specific distance measures inheriting from
DistanceMeasure (fx. CosDistance), and I would like to be able to do fx.
CosDisance cs;
Vector v;
MyClass ms(v, cs);
If I make the methods in DistanceMeasure virtual, I'm told by the
linker, that it's an undefined reference.
You forgot to link in a definition of the function in question.
If I make them pure virtual,
I'm told that the constructor declaration above is illegal, because dm
is abstract.
You forgot to make the constructor argument a reference. What you have
is a copy of the DistanceMeasure part, of type DistanceMeasure. You
can't make an instance of an abstract class.
If I provide a dummy implementation in DistanceMeasure it's
the DistanceMeasure methods that are called from MyClass and not the
overriding methods from CosDistance.
You forgot to make the constructor argument a reference. What you have
is a copy of the DistanceMeasure part, of type DistanceMeasure. For a
non-abstract DistanceMeasure that results in a slice operation.
How can I specify an interface for a distance measure, and make MyClass
indifferent to the class implementing the interface, and use the methods
from the class provided in the constructor???
I'm not that familiar with c++, so any help or ideas would be highly
appreciated.
It's a very large design space:
* Run-time versus compile-time specification.
* Identification by type (infinite variation possible) versus values.
* Different measures per MyClass instance or per class.
For the case of run-time identification of distance measure per instance:
* Passing in identifying value.
* Passing in factory object.
* Passing in std::auto_ptr (ownership transfer), or other smart
pointer.
* Passing in ref to object managed by client code.
* Passing in a callback.
Whether any of these solutions are reasonable depends on what you want
to achieve.
"Java interface" is something else entirely, but given that you have a
Java background, you may find it easiest to do the smart pointer thing.
For that you should get yourself the Boost library's smart pointer
collection (can be used without compiling the library, all code in
header files) and use boost::shared_ptr.
--
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?