Struct size vs. Class size in memory

J

Jaco Naude

Hi

I am working with big matrices filled with complex values. I
considered to use the std complex.h class to represent the complex
numbers, but in the end I wrote my own small struct to store the
complex numbers. I created a separate header file with all the
functions related to complex numbers which operate on complexValue
structs.

This struct is below:

struct complexValue {
complexValue(qreal i = 0, qreal q = 0) :
real(i),
imag(q) { }
//! Copy constructor.
complexValue(const complexValue& other) {
real = other.real;
imag = other.imag;
}
qreal real;
qreal imag;
};

My reasoning behind this was that big matrices using my struct will be
much smaller than big matrices with a std::complex object instance for
each value. My reasoning behind the seperate header file with the
complex math operations is that the memory needed for each math
operation will not be included in each object instance.

I tried to verify this using the following:

complex<double> testStd(0.1,0.1);
complexValue testOwn(0.1,0.1);
int stdSize = sizeof(testStd);
int ownSize = sizeof(testOwn);

The result is that stdSize = ownSize = 16.

Am I missing something or is the compiler too clever for me?

Thanks in advance,
Jaco
 
I

Ian Collins

Jaco Naude wrote:

My reasoning behind this was that big matrices using my struct will be
much smaller than big matrices with a std::complex object instance for
each value. My reasoning behind the seperate header file with the
complex math operations is that the memory needed for each math
operation will not be included in each object instance.

What memory? the size of an instance of a class or struct without
virtual methods is the size of its data members plus any padding
required for alignment.
I tried to verify this using the following:

complex<double> testStd(0.1,0.1);
complexValue testOwn(0.1,0.1);
int stdSize = sizeof(testStd);
int ownSize = sizeof(testOwn);

The result is that stdSize = ownSize = 16.

Am I missing something or is the compiler too clever for me?

I think you were assuming the code space for class methods was part of
the size of an instance of the class.
 
J

Jaco Naude

Jaco Naude wrote:



What memory?  the size of an instance of a class or struct without
virtual methods is the size of its data members plus any padding
required for alignment.





I think you were assuming the code space for class methods was part of
the size of an instance of the class.

You are correct, I was not sure how this works. Thanks for the
explanation...
Cheers
Jaco
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top