TITLE: terminology - static and dynamic (Newsgroups: comp.lang.c++.moderated, 20 Apr 98) KARMINDR: karmindr@one.net |> Hello. I just started learning C++ and I haven't nailed down the |> meanings of "static" and "dynamic". Could someone briefly explain |> these terms to me and perhaps some pros and cons among each. I |> see these terms MANY times and figured I better know what they mean |> REALLY soon if I plan to get anywhere! Thanks. [snip] KANZE: kanze@gabi-soft.fr (J. Kanze) [snip] Seriously, it's not surprising that you are having trouble nailing down the meanings, since they vary enormously according to context. First, since you are asking for the opposition "static" vs. "dynamic", I will suppose that we are not concerned with the keyword "static", which has five or six different meanings, since there is no keyword "dynamic". When used in direct binary opposition, these words generally refer to type resolution or function call dispatching (which is an effect of type resolution). In such cases: any given expression in C++ has a type, which can be completely determined by the expression at compile time. This is known as the static type -- because it is determined at compile time, it cannot vary during execution. In C++, however, expressions resulting from a reference, or dereferencing a pointer, also have a dynamic type, which is the type of the actual object refered to or pointed to, which generally is not known until runtime, and may vary during runtime. Thus: Base* p = new Derived ; *p // static type Base, // dynamic type Derived This effect is generally only significant in function calls, e.g.: p->f() ; // calls Derived::f(), supposing Base::f // is virtual. Calls to virtual functions are resolved (the function is dispatched) according to the dynamic type of the object. Another frequent use of the terms concerns memory allocation and object lifetime, although this use is not a pure binary opposition; there are in fact three types concerned, static, dynamic and local, or stack. Again, static refers to what is resolved completely at compile time; the memory for a static object is allocated before program start-up, and the object is pretty much guaranteed to exist whenever and where ever it is visible. (There are some problems concerning order of initialization and order of destruction.) Dynamic objects, on the other hand, are explicitly allocated and created by the programmer, by means of a new expression, and destructed and freed by means of a delete expression. Local objects are created automatically when they come into scope, and destructed when they leave scope.