[quote]Update: I bet I am not understanding the role of statically in your answer. Can you elaborate on what you mean by that here?
[/quote]
When you have a pointer to some object, the static type information available to the compiler determines what you can do syntactically with that object; for example, can you apply the dot notation to it?
For example, imagine the following scenario (using very simple C++ code):
// details all open...
struct SolarPanel
{
unsigned long maxPowerRating;
};
const SolarPanel * solarPanel (const char * brandName);
Also imagine that the compiler has seen the above code, before encountering the following code:
const SolarPanel * panel1 = solarPanel ("brand 1");
const SolarPanel * panel2 = solarPanel ("brand 2");
if (panel1->maxPowerRating > panel2->maxPowerRating) {
// add panel1 to favourites
}
Since the static type information available reveals that a SolarPanel object has a property named maxPowerRating, the if statement above compiles without errors.
Now imagine the following scenario:
// details all hidden...
struct SolarPanel;
const SolarPanel * solarPanel (const char * brandName);
unsigned long maxPowerRating (const SolarPanel *);
Also imagine that the compiler has seen only the above code, before encountering the following code:
const SolarPanel * panel1 = solarPanel ("brand 1");
const SolarPanel * panel2 = solarPanel ("brand 2");
if (panel1->maxPowerRating > panel2->maxPowerRating) {
// add panel1 to favourites
}
Since the static type information available in this case reveals nothing about a SolarPanel object, the compiler is unable to tell that maxPowerRating is a property of that object and therefore complains about the test expression of the if statement.
If, however, the compiler saw the following code:
const SolarPanel * panel1 = solarPanel ("brand 1");
const SolarPanel * panel2 = solarPanel ("brand 2");
if (maxPowerRating (panel1) > maxPowerRating (panel2)) {
// add panel1 to favourites
}
It would happily compile that code, even though the compiler still does not know that a SolarPanel object has a property named maxPowerRating. This is because, presumably, the unsigned long maxPowerRating (const SolarPanel *) function knows what a SolarPanel object looks like on the inside.
Yes
That’s because you can send any message to an object statically typed as id; however,if the object does not understand that message, a runtime error is triggered, for which you have to be prepared.
I hope this clears things up a bit for you.