What determines the size of a class within an object when that class is being used as the object schematic's/type.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
usingnamespace std;
class test{
public:
int test1,test2,test3;
test(){test1=0;test2=0;test3=0;}
};
int main(){
test ob;int i;
cout<<sizeof(ob)<<endl;
cin>>i;
}
What is it within the class /data type test that determines the sizeof object ob?. Or a better question would be, what is the basic layout/blueprints of an object?.
I know that using public: to initialize variable is a horrible thing but it was just for the sake of the example.
Ps. If a variable is initialized in private, does that mean that the object will be affected by it(memory wise)?.
What? Public members are a feature for a reason. Saying "never" is stupid. There are good reason to use them.
Anyway, object size is slightly more complex than "count the numbers" due to alignment. Most (?) systems are aligned on a 4byte boundary. To enforce this, padding is added to align the member variables.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
struct myStruct {
int a; // 4bytes
char b; // 1byte + 3bytes padding
int c; // 4bytes
bool d; // 1byte + 3bytes padding
int e; // 4bytes
}
struct myStruct2 {
int a; // 4bytes
int c; // 4bytes
int e; // 4bytes
char b; // 1byte
bool d; // 1byte + 2bytes padding
}
An object of the first class will have a size of 20bytes. An object of the second class will be 16bytes in size.
This "packing" of variables can make significant differences. If you're going to have a million objects of a certain type, saving 4bytes per object is pretty neat.
Secondly, this also means you sometimes have "free space". I can add 2bytes of data to myStruct2 without increasing the size of the objects. That's a free short, or two chars, or two bools, ...
Congratulations, you've managed to get the exact same result in 40 more characters. What's the point of making something private if you're just going to provide accessors anyway?
Don't make something private "BECAUSE I MUST". Do so because it makes sense, or don't because it doesn't. Anyone who brings up a rule that begins with "never" or "always" deserves a kick in the groin.
Member functions do not contribute to the overall size of a class. However, a virtual table does. Member functions are merely functions that are associated with a class.
ui uiho wrote:
NEVER make variable public.
A class doesn't have to encapsulate its members. It doesn't break the rules of the class if data members are public. A class can be used to ensure that something is accomplished during construction/destruction.