1

Suppose I have Derived* derivedPtr;
I want Base baseObject from the derivedPtr;

Base baseObject = *derivedPtr; would create the baseObject with the appropriate Base class member variables?

Thank you

eugene
  • 39,839
  • 68
  • 255
  • 489

3 Answers3

3

It is Object Slicing

Derived* obj = new Derived;
base objOne = (*obj) ;  // Object slicing. Coping only the  Base class sub-object
                        // that was constructed by eariler statement.
Community
  • 1
  • 1
Mahesh
  • 34,573
  • 20
  • 89
  • 115
2

You can use dynamic casting to accomplish this.

e.g.

Base* baseObject = dynamic_cast<Base*>(derivedPtr);

http://www.cplusplus.com/doc/tutorial/typecasting/

Drooling_Sheep
  • 322
  • 2
  • 10
  • 3
    You don't need dynamic cast for this. You only need it for a cast from a Base to Derived. And since the OP wanted a new Base object, you don't need casting at all. :) – Xeo Mar 22 '11 at 04:43
  • Ah okay, Thanks. I was taught to err on the side of too much casting, so sometimes I forget when it's unnecessary. – Drooling_Sheep Mar 22 '11 at 04:53
0

Yes. That's actually called 'slicing', since you just slice off everything from the derived class.

Xeo
  • 129,499
  • 52
  • 291
  • 397