Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't polymorphism work without pointers/references?

I did find some questions already on SO with similar title- but when I read the answers they were focussing on different parts of the question which were really specific (e.g. STL/containers)..

Could someone please show me why you must use pointers/references for implementing polymorphism? I can understand pointers may help- but surely references only differentiate between pass-by-value and pass-by-reference??

Surely so long as you allocate memory on the heap- so that you can have dynamic binding then this would have been enough- obviously not.

like image 446
user997112 Avatar asked Mar 03 '13 18:03

user997112


People also ask

Why do we use pointers in polymorphism?

For polymorphism, you need virtual functions, besides having (and actually using) pointers to the base class. Try making attack a pure virtual function in the Enemy class, and use e.g. enemy1->attack() and enemy2->attack() instead. There is no polymorphism in your examples, since there are no virtual functions.

How polymorphism works under the hood?

“Under the Hood” of Polymorphism. Compiler to adds internal pointers to every object of class Shape and its derived classes, so that pointers to correct methods can be accessed from any object via any pointer. Creates three levels of indirection to access a virtual method.

Why reference is not sum as a pointer?

A pointer to reference is illegal in C++, because -unlike a pointer- a reference is just a concept that allows the programmer to make aliases of something else. A pointer is a place in memory that has the address of something else, but a reference is NOT.

What is a polymorphic pointer?

Pointers to base class One of the key features of class inheritance is that a pointer to a derived class is type-compatible with a pointer to its base class. Polymorphism is the art of taking advantage of this simple but powerful and versatile feature.


1 Answers

"Surely so long as you allocate memory on the heap" - where the memory is allocated has nothing to do with it. It's all about the semantics. Take, for instance:

Derived d; Base* b = &d; 

d is on the stack (automatic memory), but polymorphism will still work on b.

If you don't have a base class pointer or reference to a derived class, polymorphism doesn't work because you no longer have a derived class. Take

Base c = Derived(); 

The c object isn't a Derived, but a Base, because of slicing. So, technically, polymorphism still works, it's just that you no longer have a Derived object to talk about.

Now take

Base* c = new Derived(); 

c just points to some place in memory, and you don't really care whether that's actually a Base or a Derived, but the call to a virtual method will be resolved dynamically.

like image 87
Luchian Grigore Avatar answered Sep 23 '22 05:09

Luchian Grigore