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

3 Answers 3

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.
Sign up to request clarification or add additional context in comments.

Comments

2

You can use dynamic casting to accomplish this.

e.g.

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

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

2 Comments

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. :)
Ah okay, Thanks. I was taught to err on the side of too much casting, so sometimes I forget when it's unnecessary.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.