2

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?

user1305904
  • 21
  • 1
  • 3

3 Answers3

2

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?

Péter Török
  • 114,404
  • 31
  • 268
  • 329
  • Thanks for your answer. Now, I understand why I can't do this. But, how could I realise my purpose that convert Fraction to iFraction – user1305904 Apr 19 '12 at 12:30
  • the class Fraction has two data members, one for numerator and one for denominator. The class iFraction has one more data memeber iNum which represents the part of integer – user1305904 Apr 19 '12 at 12:34
  • @user1305904, after double checking the terms, now I am sure that your inheritance relationship is not right: a mixed fraction is **not** an improper fraction. Of course, conversion between the two is entirely sensible. – Péter Török Apr 19 '12 at 13:01
  • you may be right. This code is just for practicing my prgramming skill. thanks for your opinion anyway. – user1305904 Apr 19 '12 at 13:20
2

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.

DumbCoder
  • 5,696
  • 3
  • 29
  • 40
0

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

Always try to understand the concept first.

Ockham
  • 455
  • 1
  • 6
  • 16