Skip to content

Instantly share code, notes, and snippets.

@hpcx82
Created May 29, 2012 02:15
Show Gist options
  • Save hpcx82/2822167 to your computer and use it in GitHub Desktop.
Save hpcx82/2822167 to your computer and use it in GitHub Desktop.
Demonstrate the operator hidden problem and solution
#include "stdafx.h"
#include <iostream>
using namespace std;
/**
* operator= is generated implicitly by compiler, and derived class will hide ones from base class.
* If you want to use base class's operator=, there are 2 solutions.
*
* A common usage to reuse operator= in derived class should be using tempplate parameter as argument type:
* http://stackoverflow.com/questions/4122214/why-operator-doesnt-get-inherited-from-a-template-class
*
*/
class Base
{
public:
Base& operator = (Base* p)
{
cout << "Base& operator = (Base* p)" << endl;
return *this;
}
};
/**
* By default, derived class hide base class's operator=;
*/
class Derived0: public Base
{
};
/**
* The first solution is introduce the base class operator= to derived class by "using".
* But this way it will introduce all operator= from base class with different argument types:
* operator = (Base* p)
* operator = (const Base& base)
*/
class Derived1: public Base
{
public:
using Base::operator=;
};
/**
* The second solution is define operator= explictly in the derived class, then delegate to base class
* implmentation.
*
* This is a cleaner one without namespace pollution. And should also work well with muliple inheritance
* as you can reuse operator= from all base classes.
*/
class Derived2: public Base
{
public:
Derived2 operator = (Base* p)
{
Base::operator=(p);
return *this;
}
};
int main()
{
// Derived0
Derived0 d0;
//d0 = new Base();
// Derived1
Derived1 d1;
d1 = new Base();
d1 = Base();
// Derived2
Derived2 d2;
d2 = new Base();
//d2 = Base();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment