Difference between static vs dynamic type for a non-class type expression

143 Views Asked by At

Consider below code sample:

#include <cstdlib>
#include <iostream>

int main()
{
    void *ptr  = malloc(sizeof(int));

    char *cptr = reinterpret_cast<char*>(ptr);
    *cptr;   // (0) What is the dynamic type here? Would sizeof(*cptr) return size of static or dynamic type and what would it be here?

    int *iptr  = new (ptr) int{2};
    *iptr;   // (1) Both static and dynamic type are int

    cptr = reinterpret_cast<char*>(iptr);    
    *cptr;   // (2) Is static type char and dynamic type int here?
}


So far my understanding was that the static and dynamic type usually differ for class types due to inheritance coming into picture. If my understanding of (2) is correct, are there any other cases for non-class type where this differs?

The reason I'm asking this is because of following definition from the C++ standard:

[defns.dynamic.type]

<glvalue> type of the most derived object ([intro.object]) to which the glvalue denoted by a glvalue expression refers [ Example: if a pointer ([dcl.ptr]) p whose static type is "pointer to class B" is pointing to an object of class D, derived from B (Clause [class.derived]), the dynamic type of the expression *p is "D." References ([dcl.ref]) are treated similarly. — end example ]

[defns.static.type]

type of an expression ([basic.types]) resulting from analysis of the program without considering execution semantics [ Note: The static type of an expression depends only on the form of the program in which the expression appears, and does not change while the program is executing. — end note ]

1

There are 1 best solutions below

0
comingstorm On

In context, the answer is "no": the C++ dynamic type depends on its dynamic dispatch mechanism, which is only used when calling virtual methods of a class.

Note that in C++, struct is an alternate way of declaring a class.