Reputation: 339
Is the memory that is allocated to class instances not at all dependent on which member variables are initialized? Will I save memory by creating a new class with less variables if the instances don't use those variable?
For example:
class Animal{
public:
int NumberOfFeet;
int AverageWeight;
};
class Dogs - public Animal {
public:
char Breed;
};
int main(){
Animal Snake1;
};
Will I save memory by having two classes as above, rather than having one class with all three different properties?
Upvotes: 0
Views: 206
Reputation: 154
Class is just a wrapper, the size of class is equal to the sum of the size of all its members in common. An exception is that empty class should not have the size of zero.
For your questions:
Is the memory that is allocated to class instances not at all dependent on which member variables are initialized? Will I save memory by creating a new class with less variables if the instances don't use those variable?
No, the compiler will not know whether you use those variables or not. It just a garbage value if you do not use them, but it still a value.
Will I save memory by having two classes as above, rather than having one class with all three different properties?
No, class Dog is inherited from class Animal, thus it will have what Animal has, in this case are NumberOfFeet
and AverageWeight
and it owns members, in this case is Breed
. So the memory is not reduce just because you do not use those two NumberOfFeet
and AverageWeight
That is when your two classes depend on the other (Dog
depends on Animal
). If they are separated (no inheritance), the answer should be yes (since Dog
does not contain NumberOfFeet
and AverageWeight
).
Edited: not all the time the size of class equal to sum of its member variables.
Upvotes: 1
Reputation: 21
#include <iostream>
using namespace std;
class Animal{
public:
int NumberOfFeet;
int AverageWeight;
};
class Dogs : public Animal {
public:
char Breed;
};
class Combo{
int NumberOfFeet;
int AverageWeight;
char Breed;
};
int main(){
Combo combo1;
Animal Snake1;
Dogs dog1;
cout << "Size of combo1: " << sizeof (combo1) << endl;//Size of combo1: 12
cout << "Size of Snake1: " << sizeof (Snake1) << endl;//Size of Snake1: 8
cout <<"Size of dog1: " << sizeof (dog1) << endl;//Size of dog1: 12
};
It turned out having one class with all three different properties take less memory in this case at my Xcode IDE.
While it may show different size value depending on different operation system and different alignment setting.
According what I have known, every object should have a size, even though it belong to an empty class, the reason is that every object should have an address in memory so that it can be retrieved later on. If you doubt it, just write code to test it out.
Upvotes: 2