I have the following code in my .h/.cpp files:
.h:
class Foo;
typedef Foo * pFoo;
class Foo {
public:
char c;
};
std::ostream& operator<<(std::ostream &out, const Foo &f);
std::ostream& operator<<(std::ostream &out, const pFoo &f);
.cpp:
std::ostream& operator<<(std::ostream &out, const Foo &f) { out << f.c; return out; }
std::ostream& operator<<(std::ostream &out, const pFoo &f) { out << f->c; return out; }
In main when I run the following code:
Foo f;
f.c = 'a';
std::cout << "As foo object:" << f << std::endl;
std::cout << "As foo pointer:" << &f << std::endl;
I get the output:
As foo object:a
As foo pointer:a
But, if, for instance, I replace my typedef with:
#define pFoo Foo*
Instead I get the output:
As foo object:a
As foo pointer:0x7fff5fbff980
I know you cannot overload operators for built-in types. Is typedef really creating a new type, or is it just an alias for the existing type? The answer seems to be that it is creating a new type. I’m basically looking for a deeper explanation between the difference in behavior. (I’m not trying to do this in production code.)
typedefintroduces aliases or synonyms for types.What happens here is that when you use the typedef,
const pFoois aconstpointer to aFoo.When you just replace
pFoowithFoo*using a define, the function argument isconst Foo*, which is a pointer to aconst Foo.Try out the following variations as the parameter type:
Note that as you can always dereference pointers, there shouldn’t be any need for the second overload: