class GenericClass {
public:
virtualint doit(int* array, int sizeOfArray) = 0;
};
class Class1: public GenericClass {
public:
int doit(int* array, int sizeOfArray);
};
class Class2: public GenericClass {
public:
int doit(int* array, int sizeOfArray);
};
Then, in another class's definitions:
1 2 3 4
int OtherClass::doThis(GenericClass* gc)
{
// Code to be written
}
Where I've stated, "code to be written", how do I call the doit() function from each class?
int OtherClass::doThis(GenericClass* gc)
{
gc->doit(TheArray, TheSizeOfTheArray);
}
I don't know what you mean by 'from each class'; unless the object is an instance of a class that extends both Class1 and Class2, the object can only be an instance of one or the other, and you can only call the appropriate function.
The compiler doesn't know because that is determined at runtime, not compile time. The compiler just knows that it has to generate the code to figure out what to do at runtime.
If I understand correctly, the argument passed into doThis() must be one or the other (Class1 or Class2). And that will be determined by the code that calls doThis(). Right?
No. Generally, the way it works is that polymorphic classes store pointers to a table containing function addresses. At runtime you take the instance (you don't care what type it is) and just call the function pointed to by the table (it's called a vtable).
Essentially, no code ever knows what the actual run time type of an object is - instead you just call the functions associated with the instance passed to you. (This is all handled for you, of course, the compiler generates this code for you)