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?

3 Answers 3

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.

1
  • Thanks for your answer. However, I don't know what's dynamic_cast now. I am just a newbie. Apr 19, 2012 at 12:56
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?

4
  • 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 Apr 19, 2012 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 Apr 19, 2012 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. Apr 19, 2012 at 13:01
  • you may be right. This code is just for practicing my prgramming skill. thanks for your opinion anyway. Apr 19, 2012 at 13:20
0

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

Always try to understand the concept first.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.