On May 2, 11:46 pm, nozyrev <drmapa...@gmail.comwrote:
I apologize in advance if this is a very dumb question. I've been
struggling with this problem for some time: I have an abstract base
class called Base and n derived classes D1, D2, ....Dn. I would like
to have a constructor for each derived class that takes any of the
other derived classes as an argument so that these statements are
valid:
D1 d1;
D2 d2;
D3 d3a(d1);
D3 d3b(d2);
What is the syntax that I have to use for those statements to compile.
I realize that, for any given derived class i, I can't use Di (const
Base& b) as the constructor.
You can, at least as far as the language rules are concerned.
Do i need to use virtual constructors?
There's no such thing.
The real problem isn't syntax: a constructor taking a reference
to the base class, or a templated constructor, both solve that
problem. The real problem is semantics. What does it mean to
construct a D3 object from a D2 or a D1? What happens to
information that is in D2 or D1, but isn't present in D3? How
do you initialize information that is present in a D3, but not
in a D1 or a D2? If all relevant information is present in the
base, and the derived classes just provide different means of
manipulating this information, a constructor from Base const& is
the obvious answer. If the necessary information is in the
derived class, but there are "standard" ways of accessing it,
and it is always present (or there is an appropriate default if
it isn't present), then a templated constructor is a solution.
If each pair Dn->Dm has distinctive semantics, there's not much
you can do but write n different constructors for each Dm.
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34