सीधे नहीं, लेकिन आप वास्तविक वर्चुअल फ़ंक्शंस को कक्षा के बाहर से पहुंचने और वर्चुअल फ़ंक्शन कॉल को गैर-वर्चुअल फ़ंक्शन में लपेटकर नकली बना सकते हैं। नकारात्मकता यह है कि आपको प्रत्येक व्युत्पन्न वर्ग पर इस रैपर फ़ंक्शन को लागू करना याद रखना होगा। लेकिन आप वर्चुअल फ़ंक्शन घोषणा और मैक्रो में रैपर दोनों डालकर इसे प्राप्त कर सकते हैं।
using namespace boost; // for shared_ptr, make_shared and static_pointer_cast.
// "Fake" implementation of the clone() function.
#define CLONE(MyType) \
shared_ptr<MyType> clone() \
{ \
shared_ptr<Base> res = clone_impl(); \
assert(dynamic_cast<MyType*>(res.get()) != 0); \
return static_pointer_cast<MyType>(res); \
}
class Base
{
protected:
// The actual implementation of the clone() function.
virtual shared_ptr<Base> clone_impl() { return make_shared<Base>(*this); }
public:
// non-virtual shared_ptr<Base> clone();
CLONE(Base)
};
class Derived : public Base
{
protected:
virtual shared_ptr<Base> clone_impl() { return make_shared<Derived>(*this); }
public:
// non-virtual shared_ptr<Derived> clone();
CLONE(Derived)
};
int main()
{
shared_ptr<Derived> p = make_shared<Derived>();
shared_ptr<Derived> clone = p->clone();
return 0;
}
http://stackoverflow.com/questions/196733/how-can-i-use-covariant-return-types-with-smart-pointers –