• Advertisement
Sign in to follow this  

Calling Overloaded Oper from an inherited class!

This topic is 4375 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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 */);
}


Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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);
}
};

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement