Declaring a class property in an extended class with the same name as a property in a base class affects all methods in the extended class, regardless of whether they are virtual or not. Class inheritance is defined in such a way that a search for a class property starts in the local class first and then its super class, and then the next super class.
It’s usually a bad idea to give properties the same name in different levels of class inheritance. p.i and p.get both always refer to the same property in the base class Packet. But since the task set() is virtual, it calls the task defined in LinkedPacket and begins its search there. When i is defined in that class, the i defined in Packet is never set.
Thanks Dave for the answer.
But for the last sentence " When i is defined in that class, the i defined in Packet is never set."
I think you meant " When i is defined in LinkedPacket, the i defined in Packet is never set."
But from the result it looks like with i re-defined in LinkedPacket, the i defined in Packet is set to 1 which is set by the task set in the base class Packet.
Ah, I see.
I was wrong in the last reply, if Packet::set() had worked it should have printed “print pkt.i=3”.
I think it’s better to have linter to avoid re-declaration of properties in the subclasses to avoid confusion.
Thank you Dave.