1
#include <iostream>

enum types { INTEGER, DOUBLE, BOOL, STRING };

class Descriptor {

public:
    Descriptor(types type):
        _type{type}
    {}
    types &type() { return _type; }


    virtual ~Descriptor() = default;

private:
    types _type;
};

class Number: public Descriptor {

public:
    Number(types descType):
        Descriptor(descType)
    {}

    virtual ~Number() = default;

    int intValue;
};


void printValue(Descriptor t) {

  auto cast = dynamic_cast<Number *>(&t);
  if (cast == nullptr) {
    std::cout << "Err" << std::endl;
  } else {
    std::cout << "Works" << std::endl;
  }
}


int main() {

  Number t =  Number(INTEGER);
  t.intValue = 1;

  printValue(t);
}

The output is always Err. However when I change Number (in main) to be allocated on the heap with new the cast works and is able to access any functions within class Number?

Whats the difference in casting a stack object? When I tried to use static cast and access "intValue" it just gave me a garbage value. Is it possible to cast a stack object?

Nate
  • 81
  • 9
  • 1
    The issue is not heap vs stack. This issue `Descriptor t` is a `Descriptor` object, but `Descriptor* t` is a pointer to a `Descriptor` **or derived** object. In the first case you definitely have an object of your base class, in the second you may have a pointer to your derived class. You might want to look up *object slicing*. – john Mar 17 '19 at 20:30
  • @john Why are you answering in the comments section? – Lightness Races in Orbit Mar 17 '19 at 20:32
  • @LightnessRacesinOrbit coz I don't have time for a fully considered answer. – john Mar 17 '19 at 20:33
  • @john Then simply leave the task to somebody who does. The comments area is not kitted out for answers. This lack of peer review functionality is _especially_ important when, by your own admission, your answer has not been given full due consideration and is therefore even more likely to require said review. You have almost 40k rep and have been a user for more than seven years, so you ought to have grasped the Q&A mechanic by now. Thanks. – Lightness Races in Orbit Mar 17 '19 at 20:56

1 Answers1

2

Your call to printValue(t); slices your object into a Descriptor.

If you want this to work, you'd need to define the parameter to as Descriptor &t, so that the function refers to the original object:

void printValue(Descriptor &t) {
    ...
}

Online demo

Christophe
  • 68,716
  • 7
  • 72
  • 138