Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The reason why not able to use polymorphism with values but references and pointers

I found below post C++ polymorphism without pointers that explains to have polymorphism feature C++ must use pointer or reference types.

I looked into some further resources all of them says the same but the reason .

Is there any technical difficulty to support polymorphism with values or it is possible but C++ have decided to not to provide that ability ?

like image 523
nish1013 Avatar asked Jul 08 '13 19:07

nish1013


People also ask

Does polymorphism only work with pointers?

And the only way to use polymorphism without pointers is with references.

What is the purpose of polymorphism in C++?

Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance. Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks.

What makes a function considered as polymorphic?

A function that can evaluate to or be applied to values of different types is known as a polymorphic function. A data type that can appear to be of a generalized type (e.g. a list with elements of arbitrary type) is designated polymorphic data type like the generalized type from which such specializations are made.


2 Answers

The problem with treating values polymorphically boils down to the object slicing issue: since derived objects could use more memory than their base class, declaring a value in the automatic storage (i.e. on the stack) leads to allocating memory only for the base, not for the derived object. Therefore, parts of the object that belong to the derived class may be sliced off. That is why C++ designers made a conscious decision to re-route virtual member-functions to the implementations in the base class, which cannot touch the data members of the derived class.

like image 182
Sergey Kalinichenko Avatar answered Sep 28 '22 18:09

Sergey Kalinichenko


The difficulty comes from the fact that what you call objects are allocated in automatic memory (on the stack) and the size must be known at compile-time.

Size of pointers are known at compile-time regardless of what they point to, and references are implemented as pointers under the hood, so no worries there.

Consider objects though:

BaseObject obj = ObjectFactory::createDerived();

How much memory should be allocated for obj if createDerived() conditionally returns derived objects? To overcome this, the object returned is sliced and "converted* to a BaseObject whose size is known.

This all stems from the "pay for what you use" mentality.

like image 27
Luchian Grigore Avatar answered Sep 28 '22 17:09

Luchian Grigore