Hi all,
I've got quite a simple question and after searching here and on other websites I can't seem to resolve what the "correct way" of doing this is in C++. Below is a simple piece of code illustrating what I am trying to do:
#include <iostream>
class BaseClass
{
public:
BaseClass( ){ }
~BaseClass( ){ }
friend std::ostream& operator<<( std::ostream& stream, BaseClass* pointerToBaseClass )
{
std::cout << "Value in this object is set to: "
<< pointerToBaseClass->value << std::endl;
}
protected:
double value;
private:
};
class DerivedClass : public BaseClass
{
public:
DerivedClass( ){ }
~DerivedClass( ){ }
protected:
private:
}
int main( )
{
DerivedClass myDerivedClass;
myDerivedClass.value = 10.0;
std::cout << myDerivedClass << std::endl;
return 0;
}
This for some reason is not working for me. All the examples I've seen define the second argument of the ostream operator overload as: BaseClass& baseClass. If I do this however, I can't seem to use inheritance for the operator overload for the DerivedClass class. I'm not quite sure why the way I'm doing it doesn't work, as the pointer given is in affect simply a memory address too.
The error I'm getting from the compiler is:
Undefined symbols:
"operator<<(std::basic_ostream<char, std::char_traits<char> >&, BaseClass const&)", referenced from:
_main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
I'm guessing this is just something simple that boils down to understand how the operator overloading actually works. I've got my head in bit of a knot now after hunting down solutions online, so I'd appreciate it if someone could let me know what's going wrong with what I've done.
Thanks in advance!
Cheers,
Spidey