Problem Ruby super inheritance | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Problem Ruby super inheritance

Hi, I was learning the Inheritance lesson of Ruby when I came to the super explanation. In one example there is this code wihich works good https://code.sololearn.com/1073/#rb I tried to extend it with one more parameter (size) https://code.sololearn.com/cinu9MTw1Qw2/#rb to test some things when I came up with an error because of the parameters of the base class. I do not understand that error. I just keep the same structure as the example. In both of them the base class has less parameters than the constructor needs, but I only received the error in the second one. Can anyone tell me why?

23rd Aug 2018, 10:42 PM
Ruben Rodriguez
Ruben Rodriguez - avatar
2 Answers
+ 2
When ruby constructs Cat it also has to construct Animal, which it inherits from. But Animal needs some arguments passed to it to be constructed, which is what super is for, it passes the arguments to the constructor( the initializer ) for Animal. In your first example Animal only needs to know about a name. In the Cat's constructor super(name) passes the name to the Animal's constructor. However in your 2nd example, Animal needs to know about a name and a size. But in the Cat's constructor you have only super. Which is not passing 2 arguments to the Animal's constructor. I believe if super is left without arguments it passes all, 3 in this case, parameters to Animal. So, Animal cannot be constructed and in turn Cat cannot be constructed. To fix it use super to pass name and size to the Animal's constructor. super(name,size)
23rd Aug 2018, 11:21 PM
Dennis
Dennis - avatar
0
Of course. I have completely missunderstood the meaning of super in the constructor and with parameters comparing with just super in a function. Now it is everything clear, and of course you are right! Thank you very much!
23rd Aug 2018, 11:41 PM
Ruben Rodriguez
Ruben Rodriguez - avatar