开发者

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

开发者 https://www.devze.com 2023-02-18 02:40 出处:网络
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?

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


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.


You can use dynamic casting to accomplish this.

e.g.

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

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消