If a class instance uses 20 bytes, and its subclass uses 24 bytes since it as more members, how is it possible to store an instance of the subclass in a variable of the parent class?
Like:
Subclass s;
ParentClass p ;
p = s;
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You don’t “store” instances “in” pointers. Pointers merely point at the start of the instance in memory.
The pointer object itself contains a memory address, and the space that this takes up is always the same no matter what — or how much — data may be found at that address.
Edit (since the question has changed almost completely)
In the example you’ve added to your question, the code doesn’t do what you think it does. You are not storing a
Subclassin aParentClass; instead, you are slicing off the derived bits ofs, and copying only its base bits intop.You asked elsewhere how you can fit a
Derivedin an array ofBase; you can’t.