Reputation: 2078
In a template class, I overloaded the ostream<< operator with the following:
friend std::ostream& operator<<(std::ostream &out,
const DataItem<T> &cDataItem) {
out << cDataItem.m_value;
return out;
}
And m_value
is declared as a pointer to the generic type
T *m_value;
But for some reason, when I cout the object, it prints an hexadecimal value, which I guess is the address and NOT the value, as I expect:
Value: 0x7fff418f9d40
I learned that cout with a char* should print the content of the char*, not the address. Why then is this happening? Is the template a problem?
Upvotes: 3
Views: 2230
Reputation: 19233
The problem is that in your case, T
is char[40]
which is a pointer already (equivalent to char*
). This means that if you use T*
, it becomes char**
and that's what you are trying to print. Since it's a pointer to the pointer, generic template for pointers get applied and the address is printed.
For a test, you may try to print:
friend std::ostream& operator<<(std::ostream &out,
const DataItem<T> &cDataItem) {
out << *cDataItem.m_value;
return out;
}
In this case, you will dereference the pointer to the original value, that is char[40]
and you should get the expected output.
Also, I think your operator=
is wrong. Since you pass T
to it, and assign it to T* m_value
, you implicitly store a pointer to a local value. You probably want to make it take T*
likewise in the constructor. Or a T&
reference in both cases.
Upvotes: -1
Reputation: 182761
char *
is a special case. For any other pointer, unless you have some specialization you implemented yourself, outputting a pointer outputs that pointer, not what it points to.
Upvotes: 3