0

I'd like to build a Fraction class and to do that I want to use the class to declare the attributes inside of it like this.

class Function {
     private:
          Fraction num;
          Fraction den;
     public:
         // Methods...
}

How can I do it? Thank you in advance for your time.

P.S.: sorry for my bad english and also for my bad programming, I'm new to OOP :D.

  • 1
    You cannot declare a class that has a member variable of that self-same class in the class (because of infinite recursion, the class would be infinitely big). You can declare a class that has a member variable pointer of that self-same class in the class. – Eljay May 25 '21 at 11:16
  • No. https://stackoverflow.com/questions/2706129/can-a-c-class-include-itself-as-an-member – Raildex May 25 '21 at 11:18
  • I'm not sure what you are asking. It seems like you already have (almost) working code. Maybe you should take our [tour] and see [ask], then provide a [mre] and ask a more specific question. What's wrong with the piece of code you've shown? – Lukas-T May 25 '21 at 11:20
  • @churill, I am pretty sure that code does not work. – kesarling He-Him May 25 '21 at 11:20
  • The numerator and denominator of a fraction are integers, not fractions. – molbdnilo May 25 '21 at 11:40

1 Answers1

0

you cannot use class itself as member.

but you can do something like that with pointers:

class A
{
public:
  A* first;
  A* something_else;
}

most data structure like linked list or list or tree used this approach.

N0ll_Boy
  • 500
  • 3
  • 6