Overhead of creating a new class

If I have a class defined as such:

class classWithInt
{
public:
    classWithInt();
...
private:
    int someInt;
...
}

and that someInt is the one and only one member variable in classWithInt, how much slower would it be to declare a new instance of this class than to just declare a new integer?

What about when you have, say 10 such integers in the class? 100?

Answers


With a compiler not written by drunk college students in the wee hours of the morning, the overhead is zero. At least until you start putting in virtual functions; then you must pay the cost for the virtual dispatch mechanism. Or if you have no data in the class, in which case the class is still required to take up some space (which in turn is because every object must have a unique address in memory).

Functions are not part of the data layout of the object. They are only a part of the mental concept of the object. The function is translated into code that takes an instance of the object as an additional parameter, and calls to the member function are correspondingly translated to pass the object.

The number of data members doesn't matter. Compare apples to apples; if you have a class with 10 ints in it, then it takes up the same space that 10 ints would.

Allocating things on the stack is effectively free, no matter what they are. The compiler adds up the size of all the local variables and adjusts the stack pointer all at once to make space for them. Allocating space in memory costs, but the cost will probably depend more on the number of allocations than the amount of space allocated.


Need Your Help

How to run a task in Python after 60 second but only one time

python wxpython python-2.7

I have a task in Python and i run this task for first time and i want after 60 second run the same task but only one last time.

error C4335 when compile C++ project VS2012

c++ visual-studio-2012 compiler-errors

I have a C project that i am able to compile and run successfully, however when i add another include like #include <vector> even without actually using the vector type i am getting the follo...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.