Object mode (1)---Object Lessons ---part 1

Agenda:

1.Layout Costs for Adding Encapsulation.

2.The C++ object Mode

3.difference beteen "struct" and "class"

4.An Object Distinction

/*****************************************************************************/

1.Layout Costs for Adding Encapsulation.

in laguage C, set a point3d,

1 //Point 3d
2 
3 float point3d_x;
4 float point3d_y;
5 float point3d_z;
6 
7 //size is sizeof(float)*3

normally, in 32-bit computer, it was 4*3=12 bytes;

 

And in C++:

 1 Class Point3d
 2 {
 3 public:
 4    Point3d(long x=0.0,long y=0.0,long z=0.0):_x(x),_y(y),_z(z)
 5     {        
 6     } 
 7 
 8    void x(){return _x};
 9    ...
10 
11 private:
12     long _x;
13     long _y;
14     long _z;
15 
16 };

Pint3d pointA;

What is sizeof(pointA)?

 1 template <class type>
 2 class Point3d {
 3 public:
 4   Point3d(type x=0,type y=0,type z=0):_x(x),_y(y),_z(z){};
 5   ~Point3d(){};
 6   type getx(){return _x;}//the member function is not in object
 7 
 8 private:
 9   type _x;
10   type _y;
11   type _z;
12 };

The test result is 12, in gcc 版本 4.4.6 (Ubuntu/Linaro 4.4.6-11ubuntu2)
So class is just like an lable, or a collection.

It can be see with compiler or coder, for memory, it was ignore.

But if we add virtual funtion?

 1 template <class type>
 2 class Point3d {
 3 public:
 4   Point3d(type x=0,type y=0,type z=0):_x(x),_y(y),_z(z){};
 5   virtual ~Point3d(){};
 6   type getx(){return _x;}
 7 
 8   virtual type getSum(){return (_x+_y+_z);}
 9 
10 private:
11   type _x;
12   type _y;
13   type _z;
14 };

The test result is 24.

So the object will add something with polymorphism.For only the object itself known the behavior with virtual function,

the compiler can't known.

2.The C++ object Mode

So, what is the real c++ object mode ? it depends compiler,but normally, it will like this.

 

1)static member/function has only one instance in whole system, so it wan't in one object mode, it will at golbal sysbals.

2)member function is only one instance, it also will be just :jump to;

3)there will be an vptr(virtual point ) point the Virtual table of this object. It is using for RTTI.

 

 

 

 

 

 

 

posted @ 2014-03-21 11:59  手机从业者  阅读(170)  评论(0)    收藏  举报