Re: Distinguishing between alternative constructors.
* pauldepstein@att.net:
Class A has two constructors A( someclass& asomeclassvar,
someotherclass& asomeotherclassvar) and also A(someclass&
asomeclassvar, someotherclass& asomeotherclassvar, yetanotherclass&
ayetanotherclassvar) Get and Set methods are available for the
parameters from someclass, someotherclass and yetanother class.
Sometimes these Get and Set Methods are accessed from a base
class
I want to write code like:
A* NewPointerToClass = new(PreviouslyDefinedPointerToMyClass ->
Getasomeclassvar(), PreviouslyDefinedPointerToMyClass-
Getsomeotherclassvar ..);
My problem is that I don't know which of the two possible constructors
is available via PreviouslyDefinedPointerToMyClass
I only want to call a Get method if it corresponds to a variable
that's present in the constructor.
So it seems like I need to know how to say, in c++
if(the thing being pointed to has been defined using such and such a
constructor) do...
else if the thing being pointed to has been defined using such and
such a constructor) do...
I would guess this is a common situation in c++ What is the most
standard way of handling this?
First, the terminology above is quite confused, so I'll have to make a
stab at what you probably mean. My interpretation is: you have a class
A with two constructors; depending on which constructor was used an
instance of A will contain different information; you have a pointer to
such an instance, and you want to clone that instance.
Then, if that interpretation is correct, just define a clone() member
function in class A.
That clone function will itself be very simple:
A* clone() { return new A( *this ); }
using class A's copy constructor.
Then you can write
A* newPointerToClass = previouslyDefinedPointerToMyClass->clone();
For safety you might consider using std::auto_ptr<A> as the result type
for the clone() function (expressing and enforcing an ownership
transfer), and you might further consider whether it is such a good idea
to have possibly invalid operations available on an instance, i.e.,
whether it might not be better to have two different classes rather than
just one. E.g. it might be that things would be simpler with A and a
derived class B. In that case make clone() virtual.
Cheers, & hth.,
- Alf
PS: clone functions are also discussed in the FAQ, there called "virtual
construction" or some such.
--
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?