Base class conversion

How does the internal conversion between the derived and base class take place and how does the compiler know or does it save the size of the object?

For example, in the following:

class A
{
public:
 A():x(2){};
private:
 int x;
};

class B : public A
{
public:
 B():A(),y(5){};
private:
 int y;
};

class C : public B
{
public:
 C():B(),z(9){};
private:
 int z;
};

int main()
{
   C *CObj = new C;
   B *pB = static_cast<B*>(CObj);
   delete CObj;
}

Edit: Perhaps this was:

B BObj = static_cast<B>(*CObj);
+3
source share
5 answers

You do not have any "base to base" conversion in your code. What you have in your code is converting the pointer to the base one. (This conversion does not require any explicit translation, BTW)

B *pB = CObj; // no need for the cast

To perform pointer conversion, there is no need to know the size of the object. Thus, it is not clear where your link to "object size" comes from.

, . , . . , .

(, ) , . . , .. , , .

, , , , , . , .

+5

: static_cast; "" "-" "-".

. (.. , CObj pB , ). B C , . , ( new C).

- , vtables vptrs (http://en.wikipedia.org/wiki/Vtable).

+1

. , 10.3

", (1.8) "

, , , , . , Derived * Base * , , .

, , , . VTable VPTR, . " ", . , "", "", "" . , . " ". , "", .

+1

.
, , .
( ).

[ ]

( C).

?

, , .
( ), , ( ), ( , , ).

0

- C, .

, . , . C int [4]. , , .

-5

Source: https://habr.com/ru/post/1764351/


All Articles