hjk41的日志

Avatar

More Effective C++ 25: Virtualize constructors and non-member functions

Though constructors and non-member functions can't be declared virtual, we can make them behave virtually.

Consider three classes as following:


class Base{
  ...
};

class Derived1:public Base{
  ...
};

class Derived2:public Base{
  ...
};

Derived1 d1;
Derived d2;
cout<<d1<<d2<<endl;


In order to do cout<<d1<<d2<<endl we must overload the operator << twice. However, we can do it another way:


class Base{
public:
    virtual void print(ostream &s);
    ...
}

class Derived1:public Base{
    virtual void print(ostream &s);
    ....
};

class Derived2:public Base{
    virtual void print(ostream &s);
    ...
};

inline
ostream& operator<<(ostream& s, const Base & b)
{
  return b.print(s);
}


This way, we can overload only one operator<< and still have the ability to do cout<<d1<<d2<<endl;

评论已关闭