Why only object is sliced , not the pointer | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 1

Why only object is sliced , not the pointer

Refer code below : I have idea about object slicing and it works as expected for display1 and display2 When it comes to pointer , i have questions : 1. Why display3 works and dont show characteristic of slicing ? 2. Why passed pointer as reference shows same address both from demopointer and display3 3. Whats error if i uncomment display4 and how to solve this ? https://code.sololearn.com/cb3TobmTBIs1/?ref=app

4th Dec 2022, 3:02 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Antworten
+ 3
[2/2] The compiler still throws an error. This is because you are passing a "reference to (pointer to shape)" (shape*) where a "reference to (pointer to (const shape))" (const shape*&) is expected. This obviously, is not the same as "reference to (const pointer to shape)" (shape* const&) which is what you need here https://code.sololearn.com/ce0CWaq9r3OW/?ref=app Note that this change in type also solves point 3 of your question without any additional assignment (because not your function expects a const reference which accepts both lvalue and rvalue reference) https://code.sololearn.com/cH8FVfLc9iG8/?ref=app
5th Dec 2022, 4:12 AM
XXX
XXX - avatar
+ 3
[1/2] 1. Object slicing occurs when an object of a derived class is "assigned" to a base class. References and pointers do not cause object slicing. Any reference or pointer to a derived class can be safely casted to that of a base class. This happening in your display3 function 2. I don't quite understand what you're trying to ask. Are you asking why `pobj` in display3() shows the same address as pShape in pointerDemo()? It is because pobj and pShape point to the same address. pbj is a shape* which has been casted from pShape and literally refers to the 'shape' part of a 'triangle', a new object hasn't been formed 3. The problem is that when you pass a triangle* where a shape* (or const shape*&) is expected, the triangle* is casted to a shape*. This casting forms a new pointer of type shape* which is an rvalue (since it's not attached to the scope). The fix to this is to make a separate shape* variable and then pass it to the function. https://code.sololearn.com/cvBXVutMK5so/?ref=app
5th Dec 2022, 4:04 AM
XXX
XXX - avatar