C++ vs Java: Method Overriding and Runtime Polymorphism

people often say that 𝐦𝐞𝐭𝐡𝐨𝐝 𝐨𝐯𝐞𝐫𝐫𝐢𝐝𝐢𝐧𝐠 𝐢𝐬 𝐫𝐮𝐧𝐭𝐢𝐦𝐞 𝐩𝐨𝐥𝐲𝐦𝐨𝐫𝐩𝐡𝐢𝐬𝐦 but that statement isn’t entirely accurate with c++ 𝗺𝗲𝘁𝗵𝗼𝗱 𝗼𝘃𝗲𝗿𝗿𝗶𝗱𝗶𝗻𝗴 simply means a child class provides its own implementation of a function that already exists in the parent class with the same signature, however, runtime polymorphism only happens when the method call is resolved based on the actual object type at runtime in c++(my fav), this only happens if the base class function is marked 𝐯𝐢𝐫𝐭𝐮𝐚𝐥 and the call is made through a 𝐛𝐚𝐬𝐞 𝐜𝐥𝐚𝐬𝐬 𝐩𝐨𝐢𝐧𝐭𝐞𝐫 𝐨𝐫 𝐫𝐞𝐟𝐞𝐫𝐞𝐧𝐜𝐞 𝘦.𝘨. 𝘉𝘢𝘴𝘦* 𝘱𝘵𝘳 = 𝘯𝘦𝘸 𝘋𝘦𝘳𝘪𝘷𝘦𝘥(); 𝘱𝘵𝘳->𝘥𝘪𝘴𝘱𝘭𝘢𝘺(); without virtual, the call is resolved at compile time, even if the object is actually 𝘋𝘦𝘳𝘪𝘷𝘦𝘥 but wow (𝘢𝘯𝘰𝘵𝘩𝘦𝘳 𝘳𝘦𝘢𝘴𝘰𝘯 𝘯𝘰𝘵 𝘵𝘰 𝘩𝘢𝘵𝘦 𝘫𝘢𝘷𝘢), 𝐦𝐞𝐭𝐡𝐨𝐝𝐬 𝐚𝐫𝐞 𝐯𝐢𝐫𝐭𝐮𝐚𝐥 𝐛𝐲 𝐝𝐞𝐟𝐚𝐮𝐥𝐭 in java (except static, final, and private), when a method is overridden, runtime polymorphism happens automatically :) java performs 𝐝𝐲𝐧𝐚𝐦𝐢𝐜 𝐝𝐢𝐬𝐩𝐚𝐭𝐜𝐡 𝐚𝐮𝐭𝐨𝐦𝐚𝐭𝐢𝐜𝐚𝐥𝐥𝐲, without needing a virtual keyword #CPP #Java #OOP #SystemDesign #Programming

To view or add a comment, sign in

Explore content categories