find size of derived class object using base class pointer

前端 未结 4 1219
名媛妹妹
名媛妹妹 2020-12-09 09:32

Is it possible to find the size of a derived class object using a base class pointer, when you don\'t know the derived type.

Thank you.

4条回答
  •  天命终不由人
    2020-12-09 10:05

    Considering the nice answer of @Dennis Zickefoose, there's a case where you can implement multiple levels of inheritance which requires you neither to have virtual functions nor an intermediate class between each layer of inheritance and the added complexity.

    And that's when all the intermediate (non-leaf) classes in the inheritance hierarchy are abstract classes, that is, they are not instantiated.

    If that's the case, you can write the non-leaf abstract classes templated (again) on derived concrete types.

    The example below demonstrates this:

    template 
    class Shape     // Base
    {
    public:
        float centerX;
        float centerY;
    
        int getSize()
        { return sizeof(TDerived); }
    
        void demo()
        {
            std::cout
                << static_cast(this)->getSize()
                << std::endl;
        }
    };
    
    class Circle : public Shape
    {
    public:
        float radius;
    };
    
    class Square : public Shape
    {
        // other data...
    };
    
    template 
    class Shape3D : public Shape
        // Note that this class provides the underlying class the template argument
        //   it receives itself, and note that Shape3D is (at least conceptually)
        //   abstract because we can't directly instantiate it without providing it
        //   the concrete type we want, and because we shouldn't.
    {
    public:
        float centerZ;
    };
    
    class Cube : public Shape3D
    {
        // other data...
    };
    
    class Polyhedron : public Shape3D
    {
    public:
        typedef float Point3D[3];
    
        int numPoints;
        Point3D points[MAX_POINTS];
    
        int getSize()   // override the polymorphic function
        { return sizeof(numPoints) + numPoints * sizeof(Point3D); }
        // This is for demonstration only. In real cases, care must be taken about memory alignment issues to correctly determine the size of Polyhedron.
    };
    


    Sample usage:

    Circle c;
    c.demo();
    
    Polyhedron p;
    p.numPoints = 4;
    p.demo();
    

提交回复
热议问题