what is the difference in the 2?

class Log 
{ 
private: 
// no members attributes
public: 
       void createLog( ); 
}; 
 
int main() 
{ 
 
Log log1; 
log1.createLog(); 
 
}
class Log 
{ 
private: // no members 
public: 
       static void createLog( ); 
}; 
 
 
int main() 
{ 
Log::createLog(); 
}

im asking is there any additional overhead for the first case? i dont see how u can instantiate an object without any member variables :(

Edited 5 Years Ago by lochnessmonster: n/a

im asking is there any additional overhead for the first case? i dont see how u can instantiate an object without any member variables :(

Both classes will produce objects with this pointers. The this pointer is just a pointer to the member data. In the case where the class contains no member data, the implementation will instantiate a token about of memory and point this at that.

Edited 5 Years Ago by gerard4143: n/a

>>is there any additional overhead for the first case?
Yes, of course. In the first case, you needlessly create an instance of the Log class. And then, when you call the member function, the this pointer is implicitly passed as a first "hidden" parameter to the function, so that's a small additional overhead. In the second case, neither of those things happen and thus, it would be more efficient (not to mention that if createLog() does not need a Log object to work on, then, it is, semantically, more appropriate for createLog() to be a static function).

an object with no members, what will it's *this point to in memory if it has no member variables/attributes?

Edited 5 Years Ago by lochnessmonster: n/a

>>an object with no members, what will it's *this point to in memory if it has no member variables/attributes?

The standard requires that even empty classes should have a non-zero size. So, it does point to some amount of allocated memory, it's just that that memory is meaningless (i.e. just a placeholder for the object). And the this pointer has to be passed to a non-static member function, whether the class is empty or not.

Try compiling code similar to case 2 in java. You'll get a warning from compiler saying "static methods should be invoked on class instead of object".
As Mike pointed out the obvious overhead is the instantiation.

This article has been dead for over six months. Start a new discussion instead.