Class footprint

D

D

Hello I'm learning C++ and having done some Asm and C.
I would like input on the following. If I understand what I'm
reading then Objects of a type of class gets a copy of it's class'
(including inherited classes) data members in memory for each
instance of an object.
But all the code, of objects of a type of class
(including inherited classes) is just one copy in memory to be
shared by all the Objects of that type of class.
Even with Virtual functions the same vtable is built and
shared between all objects of that type of class.
Right ? Wrong ? Please explain.
 
E

E. Robert Tisdale

D said:
Hello I'm learning C++ and having done some Assembler and C.
I would like input on the following.
If I understand what I'm reading,
then Objects of a type of class get a copy of it's class'
(including inherited classes)
[non static] data members in memory for each instance of an object.

A class is *not* an object. In Java,
an object with the same name as the class is always instantiated
when the class is defined but *not* in C++.
But all the code of objects of a type of class
(including inherited classes) is just one copy in memory
to be shared by all the Objects of that type of class.

Yes.
Objects, even Java objects, don't actually contain any functions.
Even with Virtual functions,
the same vtable is built and shared
[among] all objects of that type of class.
Right? Wrong? Please explain.
Right.

cat main.cc
#include <iostream>

class X {
private:
// representation
int I;
public:
~X(void);
};

class Y {
private:
// representation
int I;
public:
virtual
~Y(void);
};

int main(int argc, char* argv[]) {
std::cout << sizeof(X)
<< " = sizeof(X)" << std::endl;
std::cout << sizeof(Y)
<< " = sizeof(Y)" << std::endl;
return 0;
}
g++ -Wall -ansi -pedantic -o main main.cc
./main
4 = sizeof(X)
8 = sizeof(Y)

An object of type Y has a hidden data member
which is a reference (pointer)
to the virtual function table (vtable) for class Y.
 

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

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,920
Members
47,464
Latest member
Bobbylenly

Latest Threads

Top