Re: overloading << and inheritance
Ook wrote:
The following code compiles and runs. In my overloaded operator<<, I
call Parent.stuff. I would expect it to call Child.stuff, since Child
is the child class, but it does not. What am I missing, and how can I
get it to call Child.stuff. Eventually I'll have different child
classes, and I need it to call stuff() from the associated child
class, not Parent.stuff.
#include <iostream>
#include <ostream>
#include <string>
using namespace std;
class Parent
{
public:
string stuff(){ return "Parent.stuff";}
virtual string stuff(){ return "Parent.stuff";}
};
class Child : public Parent
{
public:
string stuff(){ return "Child.stuff";}
};
ostream& operator<<(ostream& out, Parent * p)
{
// Overloaded << operator
out << p->stuff() << endl;
return out;
}
void printStuff( Parent * p ) { cout << p; }
int main()
{
Child c;
printStuff( &c );
return 0;
}
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask