Originally Posted by
vaibhavs17
Could you please explain with an example?
As you wish:
Code:
#include <ostream>
#include <memory>
#include <iostream>
class X
{
public:
virtual ~X() {}
virtual X* clone() const = 0;
virtual void identify(std::ostream& out) const = 0;
};
class Y : public X
{
public:
explicit Y(int n) : n(n) {}
virtual Y* clone() const
{
return new Y(*this);
}
virtual void identify(std::ostream& out) const
{
out << "I am of type Y with n = " << n << std::endl;
}
private:
int n;
};
class Z : public X
{
public:
explicit Z(int n) : n(n + n) {}
virtual Z* clone() const
{
return new Z(*this);
}
virtual void identify(std::ostream& out) const
{
out << "I am of type Z with n = " << n << std::endl;
}
private:
int n;
};
X* foo(int n)
{
if (n % 2 == 0)
{
return new Y(n);
}
else
{
return new Z(n);
}
}
int main(int argc, char* argv[])
{
std::auto_ptr<X> p1(foo(argc));
std::auto_ptr<X> p2(p1->clone());
p2->identify(std::cout);
}
Notice that p2 in the global main function points to a copy of the object pointed to by p1, but all we know is that the type of object that p1 points to is a subtype of X.