eugene
eugene

Reputation: 41665

c++ get base class object from derived class pointer?

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

Upvotes: 1

Views: 12589

Answers (3)

Xeo
Xeo

Reputation: 131799

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

Upvotes: 0

Drooling_Sheep
Drooling_Sheep

Reputation: 322

You can use dynamic casting to accomplish this.

e.g.

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

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

Upvotes: 2

Mahesh
Mahesh

Reputation: 34625

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.

Upvotes: 3

Related Questions