Calling Overloaded Oper from an inherited class!

Started by
5 comments, last by dominicoder 17 years, 11 months ago
In c++ oop, Is there a way to call a an overloaded << friend function in a base class from a derived class? I read somewhere that friend functions from a base class isnt inherited so in order to use them they have to be called from a inherited class? Any idea on how this would work? Heres an example, let's say I had a class Pet, and a class Dog inherited from class pet. Inside my class Pet i have an overloaded << friend function that outputs lets say the pets name or something, how would i use that same function in class Dog? Thanks for the time MasterDario
n/a
Advertisement
If I understand you set up correctly, you should be able to use the scope-resolution operator ('::') to call the function from the derived class. So, going off your Dog / Pet example:

void Dog::CallBase(){ Pet::operator<<(/* arguments here */);}
Have the overloaded << function call a private virtual function in pet to get the information required. Then override that function in dog.

#include <iostream>#include <string>class pet{public:    friend std::ostream& operator << (std::ostream& os, pet& p)    {        os << p.whatAmI();        return os;    }    virtual ~pet(){}private:    virtual std::string whatAmI()const    {        return "I am a pet";    }};class dog : public pet{private:    virtual std::string whatAmI()const    {        return "I am a dog";    }};int main(){    dog aDog;    std::cout << aDog;}
thats what i figured, but the problem is that my overloaded << function is a friend function so its not really a member of my base class.
n/a
Hmmm ... woulda thought you could access the friend function that way. In that case go with Nitage's suggestion.
hmm is there a way to do it without virtual functions though because i don't know much about them yet. Like i tried overloading the operator << without making it a friend function but if i do it that way it wont allow more than one paramater.
n/a
You can try declaring a member function in the base that forwards the call to the overloaded operator. Then you could call that function from the derived class.
Something like this:
class Pet{ public:  friend std::ostream& operator<<(std::ostream& os, Pet& p)  {   /* Do whatever */   return os;  }  // Member function just calls the << operator with itself  // as the argument.  std::ostream& CallStreamOperator(std::ostream& os)  {   return (os << *this);  }};class Dog{ public:  std::ostream&CallStreamOperator(std::ostream& os)  {   /* Do whatever with os here */   return Pet::CallStreamOperator(os);  }};

This topic is closed to new replies.

Advertisement