Thursday, August 9, 2007

operator= & Inheritance c++


One interesting thing about operator = is that it can't be inherited.. So even if your base class has operator=  , no use for derived class. For example CString has operator= , but if you derive a class from CString you will not get = operator functionality in your derived class.

But there is a neat trick that will explicitly put this operator= in to the derived class. Here it is

class CString
{
public :
  CString& operator=(char *)
  {
     // some codes
     return *this;
  }
};
class CMyString : public CString
{
public:
  //We explicitly inserted the operator.
   using CString::operator=; 
};

Now CMyString gets the operator from CString.

No comments: