class A {...}
class B : public A {...}
class C : public A {...}
void M(A* a) {
A* aa = new B(* a)
...
}
int main()
{
B b = new B();
M(b);
...
}
So what I want is to do is call the copy constructor of the object (“a”) that is passed to M without having to know whether it’s of type B or C etc (instead of the “new B( a)” as above).
Of course, I can use dynamic cast and check for a null ptr etc or use typeid, but there must be an easier way?
Thanks in advance.
One way to get the same effect would be to use the
clone()pattern. Give class A a virtual function that copies it, overriding that function in each subclass. Pass an instance of A to your function by reference, and thencloneit within that function. A bit messy, but works.