Search This Blog

Thursday, October 29, 2009

C++, Why Base Class Can Behaves Like Derived Class

Base* b = new Derived (assuming b contains at least one virtual function)

How can a derived pointer be stored as a base pointer to enable polymorphism?
1. b only contains the part of base, PLUS
2. a virtual pointer !
3. now we have three cases:
-- now we can call a function on b, if the function NOT part of b but IN the subclass, the call WILL fail. because right now, the b pointer does not contain the address space of derive class. This is why we have to "down cast"(dynamic_cast) to a derive pointer, to actually call the function that's only define in the derived class.
-- but if we call a function on b, if the function is part of b, if it is NOT virtual, of course it will invoke the function directly on pointer b.
-- but if we call a function on b, if the function is part of b, if it IS virtual, the virtual pointer is used, and indirectly goes to the virtual table to call the function in the table.

with the c++ object model in mind:
1. A rectangle is a shape, but not (always) vice versa. D is B, for public inheritance.
That's why if we want to uses a D only interface, a dynamic_cast check is necessary
Factory Method: get rid of dynamic cast by defined the virtual interface in B, and use D to
generate the proper information by overwriting the base class interface.
2. A container(Shape) is NOT a container(rectangle). The size of the pointer is different.
If you use a shape's pointer to iterate a rectangle's pointer, you are asking for trouble.
p. 907, Programming, P&D

Reference:
C++ object model, 27, 127, 129

No comments: