Because if you pass by value, the objects will be split , and the run-time polymorphism cannot be achieved. And in your code, the very line Material m = Texture() causes the splitting of objects. Therefore, even if you pass m pointer (or reference), runtime polymorphism cannot be achieved.
In addition, run-time polymorphism is achieved by:
- base type pointer or
- base type link
So, if you need polymorphism at runtime, you use either a pointer or a link of the base type, and here are some examples of how you can achieve polymorphism at runtime:
Material* m1 = new Texture(); poly->setMaterial(m1); //achieved Texture* t1= new Texture(); poly->setMaterial(t1); //achieved Texture t2; poly->setMaterial( &t2); //achieved : notice '&' Material & m2 = t2; poly->setMaterial( &m2 ); //achieved : notice '&' Material m3; poly->setMaterial( &m3 ); //NOT achieved : notice '&'
Only in the last line do you not achieve polymorphism at run time.
Nawaz source share