If I remember correctly, in Java we can pass a subclass of a function to a superclass. The code will look as follows.
Fruit apple = new Apple();
Fruit pineapple = new Pineapple();
public void iHaveAPenIHaveAn(Fruit fruit) { ... }
...
public static void main(String[] arg)
{
iHaveAPenIHaveAn(apple);
iHaveAPenIHaveAn(pineapple);
}
However, in C ++, I noticed from here that you need to use a reference variable of the base class (is this the correct term?) Instead of the usual variable of the base class.
Assuming you have two classes: the base class Aand the A-closed class B.
class A { ... };
class B : A { ... };
If we have a function neverGonna()that takes a class argument A, then why should the function look like this:
void neverGonna(A& a) { ... }
...
B giveYouUp;
neverGonna(giveYouUp);
instead of this?
void neverGonna(A a) { ... }
...
B letYouDown;
neverGonna(letYouDown);
What are the reasons for this?