0

I have a class named "obj" and another one named "aggregate" .

The second one is derived from the first one.

The class "obj" holds only an integer. The "aggregate" nothing more ( only more "methods").

class obj{
public:
  int t;
}

I have a function that returns "obj"

obj pop();

and I need to assign the result of it to a variable of class "aggregate".

aggregate a;a=pop();

I try to do it like:

a=static_cast<aggregate>(pop());
a=dynamic_cast<aggregate>(pop());

Because essentially on the stack the value of the structure is passed ( so essentially an integer) I cannot understand why I should do:

a=*((aggregate*)(&pop()));
BenMorel
  • 34,448
  • 50
  • 182
  • 322
George Kourtis
  • 2,381
  • 3
  • 18
  • 28
  • Because polymorphism in C++ is available only for pointers and references, Isn't it? – Gluttton Jun 15 '14 at 13:41
  • 1
    Complete. Minimal. Representative. Example. – Kerrek SB Jun 15 '14 at 13:41
  • You mean I have to add my definition of cast in order to override that limitation ? Something like : #define value_cast(type,value) *((type*)(&value)) . No other way ? – George Kourtis Jun 15 '14 at 13:51
  • Is your question about how to solve concrete practical problem or about why compiler not so clever? – Gluttton Jun 15 '14 at 14:13
  • It looks like you are not interested in polymorphism at all. You have an object and you want to create a different object out of it. To this end, you overload a cinstructor and an assignment operator in the second class. – n. m. could be an AI Jun 15 '14 at 14:19
  • My problem is in real code and I am actually trying to modify code where I was using just an "integer" named "token" and I am trying to replace it with an "obj" type, but I see difficulties. – George Kourtis Jun 15 '14 at 14:26
  • `My problem is in real code` - so give us complete and little example, as was said by @GeorgeKourtis. – Gluttton Jun 15 '14 at 14:31
  • 1
    I believe your question is not about up-casting, it's about down-converting. If that's correct, please fix the title and retag. – cmaster - reinstate monica Jun 15 '14 at 14:38

1 Answers1

1

To achieve polymorphism you need use pointers or references.

#include <stdlib.h>

class obj
{
    protected:
        virtual ~obj () {};
        int data;
};

class agregate : public obj
{
    public:
        void actionA () {};
        void actionB () {};
};

obj * pop ()
{
    return new agregate;
}

int main (int argc, char * argv [])
{
    agregate * a = dynamic_cast <agregate *> (pop () );

    return EXIT_SUCCESS;
}
Gluttton
  • 5,739
  • 3
  • 31
  • 58