What is dynamic type of object
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:
- this may be
Base
- this may be
Derived
- this may be another derived class from
Base
that we know not yet
Therefore, in the following example:
int main(int argc, char* argv[]) {
if (argc == 1) {
Base base;
print();
} else {
Derived derived;
print(derived);
}
};
- The
static
anddynamic
type ofbase
isBase
andderived
isDerived
. - In the
print
method, thestatic
type ofb
isBase
(always) - Depending on the number of arguments, the
dynamic
ofb
is eitherBase
orDerived
It 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.
What i think is that dynamic type means dynamically allocated object using new.
Nope.
The dynamic type is the real type of an object that might be accessed via a reference (pointer included) that point to a base type of its real type.
That is, if we have :
class A {
};
class B : public A { };
B l;
A& k = l;
Here k is a reference to an object of type A, but the real type of the referred object, its dynamic type, is B.
Here "dynamic" has the meaning of "known only at run-time".
The static type is the type of the variable, which is the only type known at compile time (hence considered static - cannot change). The dynamic type is the type of the object that is actually being pointed at run-time. Dynamic here means it's only known at run time, which means it might change (namely one variable can point on various objects of various types).
The use of new
in this content is not relevant, as your own example shows. In your main, the static and dynamic type of d
is Derived
, because it's not a pointer or reference. p
, however, has a static type of Base
, but in your code, the dynamic type would be Derived
.