user1305904
user1305904

Reputation: 21

friend function of base class and derived class

I have a base class Fraction and a derived class iFraction. Fraction represents the improper fractions and iFraction represents the mixed fractions.

class Fraction {...};
class iFraction : public Fraction {...};

Now, I want to declare a friend function of these two class, namely convertF. The function convertF can convert the improper fractions(Fraction) to mixed fractions(iFraction). How cold I do this? Actually, I'd like to declare the function like this:

friend iFraction convertF (Fraction &Fra);

However, it can't be declared within the base calss Fraction. why?

Upvotes: 2

Views: 2813

Answers (3)

Péter Török
Péter Török

Reputation: 116306

Since friend relationships aren't inherited, you need to declare convertF as a friend of both classes. But you need this only if the function needs access the internals of these classes - are you sure the public interface of the classes doesn't suffice?

One further reason to try to avoid such a double friend is that it would create a circular dependency between these classes via the signature of convertF.

Update: This is exactly why you can't declare your friend function the way you show above. For this to work, the compiler would need to know the full definition of iFraction while it is still not finished with the definition of the base class Fraction, which is impossible.

Technically it could work the other way around, by forward declaring iFraction. Although I still wouldn't consider it a good solution. Are you sure your class hierarchy is right?

Upvotes: 2

Ockham
Ockham

Reputation: 475

Read this: http://www.cprogramming.com/tutorial/friends.html

Always try to understand the concept first.

Upvotes: 0

DumbCoder
DumbCoder

Reputation: 5766

You don't need a friend function for this. There are two ways to do this use dynamic_cast or write a conversion constructor which takes a Fraction object and converts it into a iFraction object. I am not so sure if the second option is at all a good option, but woth a try.

Upvotes: 2

Related Questions