Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

virtual friends, overloaded operator inheritance

Status
Not open for further replies.

Wolfie7873

Technical User
Jan 15, 2004
94
US
So, I've learned from the g++ compiler that virtual functions can not be friends, so this leaves me in a quandry.

Typically, when overloading an output operator in a given class, it's common practice to declare the operator globally with the 'friend' keyword giving the function access to the private data members of the class.

When implementing derived classes for proper inheritance and polymorphism, the base class functions are declared as virtual and then properly implemented in the derived classes.

OK, so tell us something we don't know... ;)

If I want to overload the output operator for each derived class but it still be called polymorphically at runtime, how do I do it? i know that I can't declare the original function as a friend. Can I declare it as a member function and everything work ok? I'm so used to declaring overloaded operators as friends that i've hesitated.

Thanks
Eddie
 
Some workaround of the problem (improvisation;):
Code:
class A
{
public:
  virtual void printMe(ostream&) const;
};
/// Full access via this member
void A::printMe(ostream& out) const
{
  out << &quot; Print A &quot;; // For example only
}
/// It's not a friend. Real worker is virtual printMe
ostream& operator << (ostream& out, const A& a)
{
  a.printMe(out);
  return out;
}

class B: public A
{
public:
  void printMe(ostream&) const;
};
/// We can see B object here...
void B::printMe(ostream& out) const
{
  out << &quot; Print B &quot;;
}
/// No special output ops, A::printMe() working...
class C: public A
{
};
The key point: use virtual member to do any real output, declare
Code:
operator <<()
as a proxy, not a friend.
 
hmm... I had intended my base class to be abstract, but i think i get the idea:
//:abstract.h
class abstract {
public:
virtual ostream& output(ostream& out, object& o);
};

//: derived.h
class derived public: abstract {
public:
ostream& output(ostream& out, derivedobj& d_obj);
friend ostream& operator<<(ostream& out, object& o);
};

//: derived.cpp
ostream&
derived::eek:utput(ostream& out, derivedobj& d_obj) {
out << d_obj.private1 << d_obj.private2 /* etc */;
return out;
}

does that look like it could work?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top