Re: Some misc C++ questions (multimap, derived class function argument,
virtual static)
Digital Puer wrote:
I have several C++ questions:
1. Why are the interfaces for multiset and multimap so complicated for
getting multiple values?
Instead of
multimap<Key, Value>
I usually prefer
map<Key, vector<Value> >
Isn't that much easier to use?
For some things. But consider the difference between the sequences
delimited by the respective begin() and end() iterators.
2. Suppose I have a base class that looks like:
class Base
{
public:
virtual void combine(const Base &other, Base &result) = 0;
}
class Derived : public Base
{
private:
string _name;
public:
void combine(const Derived &other, Derived &other) {}
}
When I try to instantiate Derived, g++ is telling me that the
pure virtual method Base.combine() is not implemented.
Why does Derived.combine() above not override Base.combine()?
It doesn't have the same signature.
And note that if overriding wiht mixed base and derived types was
allowed, it would have to go the other way: Derived& in the base
function could be replaced by Base& in the derived function. As written
above, what would happen here:
class OtherDerived : public Base
{
// whatever
};
base *bp = new Derived;
OtherDerived d2;
bp->combine(d2, d2);
Now there's a serious problem, because the code attempts to pass a
reference to OtherDerived to a function that expects a reference to Derived.
Instead, I have to do some casting, like:
void combine(const Base &other, Base &result)
{
Derived &a = (Derived &)other;
string combination = _name + a._name;
((Derived &)result)._name = combination;
}
This code assumes that the objects passed as other and result are of
type Derived.
Is there a better approach?
Yup. Don't do that. If combine will always be called with objects of
type Derived, then write it to take objects of type Derived.
3. For my abstract Base class, I want to specify a static "Factory"
method that produces a Base*:
class Base
{
virtual static Base* createRandomInstance();
}
I want to force all my Derived classes to provide such a factory
method that produces a Derived *.
However, apparently I cannot have a virtual static method
in C++ (or in Java). What is the best way to force that all
derived classes have such a factory method?
Specification and testing. Beyond that, why do you care? If someone
wants to derived from your class but not provide a factory, what harm
does it do?
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of
"The Standard C++ Library Extensions: a Tutorial and Reference"
(www.petebecker.com/tr1book)