Re: returning pure virtual object
Philipp Kraus <philipp.kraus@flashpixx.de> wrote in
news:kbktsq$2b7$1@online.de:
Hello,
I have got two pure virtual class like
class Base1 {
public :
virtual Base2 getReturn( void ) const = 0;
}
class Base2 {
public :
virtual void doSomething() = 0;
}
My implementated classes shows
class myReturn : public Base2 { .... }
class myObj : public Base1 {
public :
myObj() : m_data( myReturn() );
Base2 getReturn() { return m_data }
private :
myReturn m_data
}
You cannot return polymorphic objects by value (this would cause
slicing). In general, the size of a derived object may be larger than of
the base class object, so it would even not fit physically in the memory
provided for it.
Instead, you access polymoprhic objects via pointers or references.
Depending on the situation, you can either return a reference to m_data
*inside* myObj:
class Base1 {
...
virtual Base2& getReturn() const = 0;
};
class myObj : public Base1 {
...
Base2& getReturn() { return m_data; }
};
or you can return a cloned copy of m_data:
class Base1 {
...
virtual Base2* getReturn() const = 0;
};
class Base2 {
...
virtual void doSomething() = 0;
virtual Base2* Clone()=0;
};
class myReturn : public Base2 {
....
virtual Base2* Clone() {return new myReturn(*this);}
};
class myObj : public Base1 {
...
Base2* getReturn() { return m_data.Clone(); }
};
Instead of bare pointers, you should of course use a suitable
smartpointer instead.
See also: http://www.parashift.com/c++-faq/virtual-ctors.html
hth
Paavo