Skip to main content

Posts

Showing posts from June, 2014

Array parsing in C++

Array parsing in  C++ is always done by reference, and in std there's no concept of parsing by value. From a stakoverflow question I summarize this below. The array size information is lost here. void by_pointer(int *p, int size); void by_pointer(int p[], int size); void by_pointer(int p[7], int size);   // the 7 is ignored in this context! void by_reference(int (&a)[7]); // only arrays of size 7 can be passed here! template void by_reference(int (&a)[size]); void TestMethod(char cArray[], int size) {          const char* pTest = "test";     strncpy(cArray, pTest, size);     cArray[ size-1] = '\0';     }   Usage: char cMyArray[7] =  {a}; TestMethod(cMyAray, 7}  However this can be quite tricky to understand. Take the problem of dynamic resizing of an array. unsigned int iArrSize = 10; int *iArr = new int[iArrSize]; for (int i = 0; i < 100; i++) {         if (i >= iArrSize) {             int *arr3 = new int[iArrSize*2];            

C++ tips - I

Static members in .h and .cpp A static variable in C++ when defined in a global function belongs to the file scope. If a C++ static variable is defined as a member variable, regardless of how many objects we instantiate we only have one static variable across all of the instances. The static variable can be accessed via the instance or the class variable. If a static variable is defined as member in a class declared in a .h file, the initialization should be done as [variable_type] ClassName::[variable_name] = [value] A static function can only access static variables - makes sense huh?? A static function doesn't have the this pointer class_name::static_function() - usage Friend keyword