What is significance of static keyword in Java and in C++? - static

What is the importance of Static keyword in Java and in C++ and how it's functionality differ in both programming languages ?

Maybe this link will give you a better idea: http://www.pp.rhul.ac.uk/~george/PH2150/html/node48.html
It has a visual diagram that may make it easier to understand.

There are 2 meanings for static. The first if you have a static variable, this means there is only 1 instance of this variable. It works pretty much the same in all programming languages with the keyword.
A static function is a function that can be called, even if the class it resides in is not instantiated. Static functions are necessary in C# and Java because you cant declare functions in these languages which have no encompassing class.
in C++, you can declare functions in the global namespace. In this language, static functions are used to denote that a function belongs to the class, but you dont have to instantiate the class to use the function. You could use a static function to access private variables of the class. Also note that in C++, static functions have a known memory address, so you can use function pointers to point to them without instantiating the class.

For Java, Understanding Instance and Class Members is a good place to start.
For C++, Microsoft has a reference on the static keyword.
There are many readily available programming language resources that will help you understand what the static keyword means. The above are two of them that I found with a quick Google search.

Use static for fields and methods that can only have one instance. That means they are not relevant to instances of a class, but to the class itself. For example the main thread (public static void main).

It works the same way in both languages. I assume you know what's object-oriented programming, and what's the difference between classes and objects/instances. So, if you mark a method or variable as "static", it operates on a class level, not instance level. All objects/instances share the same value of the "static" variable.

Related

Is there a technical reason why I cannot declare a public array in a VBA class?

I just discovered that it's apparently not possible to declare a public array in a VBA class while it is fine to declare it private.
I am wondering if this is has a technical reason or if this is a design choice on Microsoft's part.
Either explanation doesn't make much sense to me: I cannot see a technical reason that would prevent a member to be private while it can be public as this is only an access check that is checked at runtime.
On the other hand, I don't understand why it shouldn't be possible to declare public arrays while it is perfectly fine to declare public integers or other data types.
I'd appreciate if someone could explain the rational behind all this.
I believe you'd need to ask the persons who created the Visual Basic (or maybe even Basic) programming language as to "why". It seems to be inherent to the languages. As far as VBA goes, the restriction comes from VB6, on which VBA bases. I find this reference in a Google search:
Declaring data as Public in a Form means you are creating a Property
on that Form, using abbreviated syntax. A Property cannot be an array
using that shortcut syntax.
To say this another way, "Public" only means "global" for
old-fashioned static (BAS) modules. For everything else Public means
something entirely different.
And this:
Instead of Arrays, You can use Collection object or Your own
Collection Class. VB6 does not allow to declare Constants, Arrays,
User Defined Types as Public.
From the VBA Help topic Constants, fixed-length strings, arrays, user-defined types, and Declare statements not allowed as Public members of an object module
Not all variables in an object module can be declared as Public.
However, procedures are Public by default, and Property procedures can
be used to simulate variables syntactically. This error has the
following causes and solutions:
Concerning arrays, specifically
You declared a Public array in an object module. Although a procedure
can't return an array, it can return a Variant that contains an array.
To simulate a Public array in a class module, use a set of Property
procedures that accept and return a Variant containing an array.

The method that will be called only within the class, still the method should be static?

I understand the benefits of using the static method, invoking functionality without the instance of the class and hence saves memory.
But what about if the method will be called only within the class? still, is there any benefit using the static method?
Class Test {
sayHelloWorld() {
print "Hello" + getWorld()
}
// this method never will be called out side of the class
// IDE say 'this method can be static'
private getWorld() {
return "world"
}
}
Your concern as a programmer in 2017 should not be about saving memory, but more about placing your abstractions in the right place. If you are using an Object-oriented language, using static methods is a smell of bad design IMHO. It allows C-style programming with global variables and functions, and make the code generally less testable.

Accessing an array without static references in another class (OOP)

I'm new to object-oriented-programming, and I have set a strict goal for myself for my current project which is not using static variables. In the process I will try to learn about OOP.
I'm using the Haxe language and it's one of the best languages I've ever seen.
I know a bit about C pointers, and that pointers only store the address of a variable so its pretty much the same variable, just taking up less space (especially for large variables).
Now back to the present, I want to have pointer references to an array of objects of one class because
I want these objects to interact with each other,
and I don't want to have any static references,
and I don't want to have every object holding a copy of that array.
How should I go along accessing this array?
Or is there another OOP design pattern or something?
Please correct me if I got something wrong.
There are many questions in this brief.
You can just pass along a context along all your variables, it will be passed by pointer
class Context{
var level:Level=null;
var enemies:Array<Enemy>=[];
}
class Enemy{
var ctx:Context;
function new(ctx){ this.ctx=ctx; }
}
class Main{
static function main(){
new Game(new Context());
}
}
and in game, pass along the context to everyone :
new Enemy(ctx);
etc...
Frankly it is often easier to use static for contexts, like
class Context{
static var level:Level;
}
But that's up to you :)
As a side note, all non primitives are pointers to structure (ex arrays) just like java.

GObject OOP Syntax

I'm looking for a GObject cheat sheet, how common OOP concepts map to GObject's facilities. Consider for example:
AnyGObject *o;
o = anygobject_new();
Now, what are the conventions for...
calling a method
calling a method declared by a base class
calling a method declared by an interface the class is implementing
calling a class method
calling a class method declared by a base class
calling a virtual method
casting to a base class
casting to a derived class
casting to an interface the class is implementing
testing whether an object is of a particular type
...
Clarification:
The GObject Reference Manual and GObject HowTo explain at length how to create a new class (class struct, object struct, private struct, various macros, conventions). Taken together these facilities allow for OOP. Yet there seems to be no tutorial on how to use them consistently.
This answer assumes you are working with C. Other (usually object-oriented) languages have special bindings built to make working with GObject seem more natural.
If you've worked with GTK+, you already have done much of that list.
GObject methods are not members themselves (there is a vtable of sorts but it's only used for assigning virtual method implementations in a derived class when the class is first created). Instead, all methods in GObject are just plain functions, usually(?) prefixed by a method name prefix, and with the this pointer as the first argument.
For example, the C++ method
namespace Lib { // short for Library; to demonstrate GObject's idiomatic naming conventions
class Foo {
public:
void Bar(int z);
};
}
would be a plain function in the global namespace declared as
void lib_foo_bar(LibFoo *foo, int z);
and you would call it directly, just like any other C function.
Class derivation in GObject occurs by having the full data structure of the parent class as the first member of the derived class's data structure. For various reasons pertaining to rarely-discussed clauses in the C standard (and possibly the System V ABI and implementation of gcc, clang, and even the Microsoft C compilers), this means that a pointer to an object of the derived class is equivalent to a pointer to the parent class!
So if LibBaz derives from LibFoo, all you would need to say is
LibFoo *foobaz = (LibFoo *) baz;
and the same applies in reverse:
LibBaz *bazfoo = (LibBaz *) foo;
(This latter approach is what GTK+ uses for GtkWidget; I don't know if other GObject libraries do the same thing.)
Idiomatic GObject declarations include a bunch of macros that make the type conversions more terse while at the same time adding runtime type safety checks. Our LibFoo class would have the following macros:
#define LIB_TYPE_FOO (lib_foo_get_type())
#define LIB_FOO(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), LIB_TYPE_FOO, LibFoo))
With this, we would instead say
LibFoo *foobaz = LIB_FOO(baz);
LibBaz *bazfoo = LIB_BAZ(foo);
and if either baz or foo isn't the correct type for the conversion, a warning will be logged to standard error, which you can break at and investigate using a debugger.
(The lib_foo_get_type() function (and LIB_TYPE_FOO neatness macro) is important: it returns a numeric ID that maps to the type of LibFoo for future reference. If LibFoo doesn't have such a mapping, it will create the mapping, registering the type and creating the virtual method mappings.)
A similar macro allows type checking:
#define LIB_IS_FOO(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), LIB_TYPE_FOO))
which is a simple expression that can be used in an if statement.
So what about calling parent class methods? Well, if we put all of the above together, we have the answer:
lib_foo_parent_method(LIB_FOO(aLibBazInstance), params);
The same applies to virtual methods. Virtual methods are implemented using the GObject approximation to vtables and are transparent to the end programmer. All you will do is
lib_foo_virtual_method(LIB_FOO(whatever), params);
(If you actually build the derived class itself, the how of virtual methods becomes important.)
There are no static methods in GObject, because methods aren't tied to a class as closely as they are in real object-oriented languages. Just create a top-level method in your library:
void lib_something_common(params);
Finally, all of the above applies to interfaces. Interfaces work the exact same way to the end user; they use the same
void lib_iface_method(LibIface *iface, params);
approach to method calling, the same casting rules, and the same LIB_IFACE() and LIB_IS_IFACE() helper macros.
Hopefully that helps! Any further explanation would have to tread into explaining how to create a GObject, which I tried to keep outside the scope of this answer for simplicity's sake, but is a useful thing to know anyway.

Supporting multiple instances of a plugin DLL with global data

Context: I converted a legacy standalone engine into a plugin component for a composition tool. Technically, this means that I compiled the engine code base to a C DLL which I invoke from a .NET wrapper using P/Invoke; the wrapper implements an interface defined by the composition tool. This works quite well, but now I receive the request to load multiple instances of the engine, for different projects. Since the engine keeps the project data in a set of global variables, and since the DLL with the engine code base is loaded only once, loading multiple projects means that the project data is overwritten.
I can see a number of solutions, but they all have some disadvantages:
You can create multiple DLLs with the same code, which are seen as different DLLs by Windows, so their code is not shared. Probably this already works if you have multiple copies of the engine DLL with different names. However, the engine is invoked from the wrapper using DllImport attributes and I think the name of the engine DLL needs to be known when compiling the wrapper. Obviously, if I have to compile different versions of the wrapper for each project, this is quite cumbersome.
The engine could run as a separate process. This means that the wrapper would launch a separate process for the engine when it loads a project, and it would use some form of IPC to communicate with this process. While this is a relatively clean solution, it requires some effort to get working, I don't now which IPC technology would be best to set-up this kind of construction. There may also be a significant overhead of the communication: the engine needs to frequently exchange arrays of floating-point numbers.
The engine could be adapted to support multiple projects. This means that the global variables should be put into a project structure, and every reference to the globals should be converted to a corresponding reference that is relative to a particular project. There are about 20-30 global variables, but as you can imagine, these global variables are referenced from all over the code base, so this conversion would need to be done in some automatic manner. A related problem is that you should be able to reference the "current" project structure in all places, but passing this along as an extra argument in each and every function signature is also cumbersome. Does there exist a technique (in C) to consider the current call stack and find the nearest enclosing instance of a relevant data value there?
Can the stackoverflow community give some advice on these (or other) solutions?
Put the whole darn thing inside a C++ class, then references to variables will automatically find the instance variable.
You can make a global pointer to the active instance. This should probably be thread-local (see __declspec(thread)).
Add extern "C" wrapper functions that delegate to the corresponding member function on the active instance. Provide functions to create new instance, teardown existing instance, and set the active instance.
OpenGL uses this paradigm to great effect (see wglMakeCurrent), finding its state data without actually having to pass a state pointer to every function.
Although I received a lot of answers that suggested to go for solution 3, and although I agree it's a better solution conceptually, I think there was no way to realize that solution practically and reliably under my constraints.
Instead, what I actually implemented was a variation of solution #1. Although the DLL name in DLLImport needs to be a compile-time constant, this question explains how to do it dynamically.
If my code before looked like this:
using System.Runtime.InteropServices;
class DotNetAccess {
[DllImport("mylib.dll", EntryPoint="GetVersion")]
private static extern int _getVersion();
public int GetVersion()
{
return _getVersion();
//May include error handling
}
}
It now looks like this:
using System.IO;
using System.ComponentModel;
using System.Runtime.InteropServices;
using Assembly = System.Reflection.Assembly;
class DotNetAccess: IDisposable {
[DllImport("kernel32.dll", EntryPoint="LoadLibrary", SetLastError=true)]
private static extern IntPtr _loadLibrary(string name);
[DllImport("kernel32.dll", EntryPoint = "FreeLibrary", SetLastError = true)]
private static extern bool _freeLibrary(IntPtr hModule);
[DllImport("kernel32.dll", EntryPoint="GetProcAddress", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
private static extern IntPtr _getProcAddress(IntPtr hModule, string name);
private static IntPtr LoadLibrary(string name)
{
IntPtr dllHandle = _loadLibrary(name);
if (dllHandle == IntPtr.Zero)
throw new Win32Exception();
return dllHandle;
}
private static void FreeLibrary(IntPtr hModule)
{
if (!_freeLibrary(hModule))
throw new Win32Exception();
}
private static D GetProcEntryDelegate<D>(IntPtr hModule, string name)
where D: class
{
IntPtr addr = _getProcAddress(hModule, name);
if (addr == IntPtr.Zero)
throw new Win32Exception();
return Marshal.GetDelegateForFunctionPointer(addr, typeof(D)) as D;
}
private string dllPath;
private IntPtr dllHandle;
public DotNetAccess()
{
string dllDir = Path.GetDirectoryName(Assembly.GetCallingAssembly().Location);
string origDllPath = Path.Combine(dllDir, "mylib.dll");
if (!File.Exists(origDllPath))
throw new Exception("MyLib DLL not found");
string myDllPath = Path.Combine(dllDir, String.Format("mylib-{0}.dll", GetHashCode()));
File.Copy(origDllPath, myDllPath);
dllPath = myDllPath;
dllHandle = LoadLibrary(dllPath);
_getVersion = GetProcEntryDelegate<_getVersionDelegate>(dllHandle, "GetVersion");
}
public void Dispose()
{
if (dllHandle != IntPtr.Zero)
{
FreeLibrary(dllHandle);
dllHandle = IntPtr.Zero;
}
if (dllPath != null)
{
File.Delete(dllPath);
dllPath = null;
}
}
private delegate int _getVersionDelegate();
private readonly _getVersionDelegate _getVersion;
public int GetVersion()
{
return _getVersion();
//May include error handling
}
}
Phew.
This may seem extremely complex if you see the two versions next to each other, but once you've set up the infrastructure, it is a very systematic change. And more importantly, it localizes the modification in my DotNetAccess layer, which means that I don't have to do modifications scattered all over a very large code base that is not my own.
In my opinion, solution 3 is the way to go.
The disadvantage that you have to touch every call to the DLL should apply to the other solutions, too... without the lack of scalability and uglyness of the multiple-DLL approach and the unnecessary overhead of IPC.
Solution 3 IS the way to go.
Imagine, that current object oriented programming languages work similar to your 3rd solution, but only implicitly pass the pointer to the structure that contains the data of "this".
Passing around "some kind of context thing" is not cumbersome, but it is just how things work! ;-)
Use approach #3. Since the code is in C, an easy way to deal with the globals that are spread everywhere is to define a macro for each global that has the same name as the global variable, but the macro expands to something like getSession()->theGlobal where getSession() returns a pinter to a "session-specific" structure that holds all the data for your globals. getSession() would fish the right data structure out of a global map of data structures somehow, perhaps using thread-local storage, or based on process ID, etc.
Actually solution 3 is easier than it sounds. All other solutions are kind of patch and will break with time.
Create a .net class which will encapsulate all access to the legacy code. Make it IDisposable.
Change all the global variables to reside in a class named 'Context'
Have all the C++ interfaces get the context object and pass it around as the first argument. This is probably the longest stage and you can avoid it using the "thread-local-storage" method suggested by someone else, but I would vote against that solution: if your library has any working threads which it runs, the "thread-local-storage" solution will break. Just add the context object where it is needed.
Use the context object to access all global data.
Have the context object created from .net ctor (by p/invoking a new create_context function) and deleted by the .net Dispose() method.
Enjoy.
Some thoughts on suggested solution #2 (and a bit on #1 and #3).
Some sort of IPC layer might introduce lagging. It depends on the actual engine how bad that is. If the engine is a rendering engine and it is called, say, 60 times a second the overhead might be too much. But, if not, a named pipe might be quick enough and easy to create using WCF.
Are you entirely sure you will need EXACTLY the same engine multiple times or are you in danger of changing requirements that might lead to a scenario that forces your toward loading multiple versions at the same time? If so, option #2 might be a better way than option #3 as it would allow this easier.
If the IPC layer is not slowing things down too much, this architecture might allow you to distribute the engines over other PC's. This might enable you to use more hardware than you previously planned for. You could even think about hosting the engine in the Azure cloud.

Resources