Reputation: 324
Say I have two classes A and B as shown:
class A {
void function1() {
cout<<"hello";
}
int member1;
public:
char member2;
};
class B : public A
{
int member3;
void function2() {
cout<<"Hello to you too";
}
public:
float member4;
};
Now, if I create an object of class B, what will be the size of the object? Will it be the same even if the inheritance from class A is private or protected?
Upvotes: 2
Views: 556
Reputation: 36597
sizeof
for all types in C++ (other than char
types, for which sizeof
yields 1
by definition) is implementation defined.
As a rule of thumb, you would not expect a derived class to be smaller than a base class. But the difference - if any - depends on the compiler, the alignment of members, how the compiler manages padding to ensure members of different sizes (and the class types) are aligned, etc etc.
I wouldn't normally expect access (public
, protected
, private
) to directly affect size of a class type. The compiler might choose to store the members in a different order depending on their access, or it might not. So the size may or may not change, but different compilers may do things differently. In principle, however, there is no need for the compiler to change the size of a class type simply because of changing the access of some member(s) or the inheritance.
Upvotes: 2
Reputation:
The private
, protected
or public
inheritance have nothing to do with size. They are only affecting visibility of base members to outside code.
Upvotes: 0
Reputation: 114461
It depends on the compiler as they've some degree of freedom in this.
My wild untested guess is that for example on a common x86 system A
should be as big as two integers (4 bytes) and B
as the same plus two other integers (8 bytes total).
The reason is that CPUs like aligned data so an int + char
class is going to be allocated as int + char + 3-byte-padding
to make an array of these classes to have all int
s aligned correctly to addresses that are a multiple of 4.
int
and float
are the same size on x86 so that's where the two extra int
s come from for B
.
Given that there are no virtual functions no other data is needed per instance as all dispatching is going to be decided at compile time.
Private/public/protected are just logical walls enforced at compile time and don't need any extra storage at run-time.
Upvotes: 0
Reputation: 5233
The size of the object of class B will be the size of an object of class A plus the amount of memory taken by the extra data members that class B adds. Methods do not count, so you can add as many methods as you want, without increasing the size of objects.
Upvotes: 0