简体   繁体   中英

Base pointer to derived object?

If Child inherits from parent, and I do:

Child* c = new Child();
Parent* p = c;

what is the purpose of p ? If Child contained additional data members, do they follow on from p , just that p cannot access them?

I am trying to understand the difference between whats actually in memory and what the pointer can access, depending on its static type.

In the tiny snippet of code shown, it's not possible to tell what MAY be the purpose of p . However, in general, using pointer or reference to a base class to store objects that are polymorphic in nature is a common practice. For example, the classic example of shapes:

// Base class for all shapes. 
class Shape
{
  ... 
};

class Circle: public Shape
{
  ...
};

class Square: public Shape
{
  ...
};

Now, if we want to store a bunch of shapes, we can use:

std::vector<Shape*> shapes;

shapes.push_back(new Circle);
shapes.push_back(new Square);

and then do:

for(auto &s : shapes)
{
   s.Draw();    // Draw shapes on screen... 
}

The vector needs to hold pointers or references, so that the type is determined by the actual object stored. If we made a vector std::vector<Shape> shapes , then we'd get "slicing", where any extra information stored in the Circle (such as radius ) or Square (such as side ) would be lost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM