I am writing an assignment using operator overloading. The assignment using reference works fine. I also try to use pointer, however it does not seems to use the function. See code below:
#include "stdafx.h"
#include <stdio.h>
class Base
{
private:
int a;
public:
int p;
Base(){};
~Base(){};
Base &operator=( const Base &src )
{
printf( "assign using reference\n");
if ( &src != this )
{
a = src.a;
p = src.p;
}
return *this;
}
Base &operator=( const Base *src )
{
printf("assign using pointer\n");
if ( src != this )
{
a = src->a;
p = src->p;
}
return *this;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Base b1;
Base b2;
Base *pb1;
Base *pb2;
pb1 = new Base();
pb2 = new Base();
b2 = b1;
pb2 = pb1;
return 0;
}
The output is:
assign using reference
I was hoping it will use the following function for the pointer assignment:
Base &operator=( const Base *src )
The compile is using default assignment when doing assignment: pb2 = pb1 instead of my assignment. So what is happing here? Any comments on this will be appreciated.