c++ - Polymorphic operator<< from virtual base class -
i want overload operator<< specialized operation within context of polymorphic classes. give direct example of want (using int example):
base* = new a; (*a) << 10;
i use syntax because portion of program same operation using <<, on non-polymorphic classes.
the problem is, base pure virtual, , @ loss how implement sort of system without complete, valid base class. example:
class base { public: virtual void avirtualfunction() = 0; virtual base operator<<( int ) = 0; }; class : public base { base operator<<( int ) { // } }; class b : public base { base operator<<( int ) { // } };
this generates error because base abstract.
i can't put overloads in inherited classes, need access operator pointer base class without casting child.
my question similar question asked in overloading << operator polymorphism, except base class not valid object on own.
your code doesn't work can't return base
object because pure virtual. return reference base
instead.
then, whole thing handeable using standard inheritance. consider following code:
class base { public: virtual void avirtualfunction() = 0; virtual base& operator<<( int ) = 0; }; class : public base { virtual a& operator<<( int ) override { // return *this; } }; class b : public base { virtual b& operator<<( int ) override { // return *this; } };
note overloads of operator<<(int)
not return base&
, rather a&
, b&
. called covariance.
Comments
Post a Comment