What i think is that dynamic type means dynamically allocated object using new. In the following case, do you say p points to dynamic type or stati
In a statically typed language, such as C++ or Java for example, static may refer to the information known at compilation time while dynamic refers to the information known at runtime.
For example:
struct Base { virtual std::string name() const { return "Base"; } };
struct Derived: Base { std::string name() const { return "Derived"; } };
void print(Base const& b) { std::cout << b.name() << "\n"; }
In the print method, the static type of b is Base const&. Therefore, the compiler will check that all methods called exist in the context of a Base object.
However, when execution comes, the call to name, as the method is virtual, is performed with regard to the dynamic type of the object:
BaseDerivedBase that we know not yetTherefore, in the following example:
int main(int argc, char* argv[]) {
if (argc == 1) {
Base base;
print();
} else {
Derived derived;
print(derived);
}
};
static and dynamic type of base is Base and derived is Derived.print method, the static type of b is Base (always)dynamic of b is either Base or DerivedIt is a current mistake to assume that polymorphism is necessarily based on dynamic memory allocation, but the two concepts, while not orthogonal, can be used without one another in some conditions.