Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Slicing Problem CS240 Computer Science II. Some relationship between base and derived classes: data members Derived class inherits data members of.

Similar presentations


Presentation on theme: "The Slicing Problem CS240 Computer Science II. Some relationship between base and derived classes: data members Derived class inherits data members of."— Presentation transcript:

1 The Slicing Problem CS240 Computer Science II

2 Some relationship between base and derived classes: data members Derived class inherits data members of its base class (or classes in the case of multiple inheritance). Therefore, a derived class object contains data members of it base class. The reverse is not true, i.e., the base class object does not contain additional data members defined in the derived class.

3 Example Based class point contains int data members x and y, its derived class circle defined an additional int data member radius. Then point p;// object p contains x and y circle c;// object c contains x, y, and radius Obviously, c is a “larger” object for it contains an additional data member.

4 The “Slicing” problem In the context of inheritance: when a larger circle object c is copied to a smaller point object p by value in a function call, the extra data member radius is discarded or “sliced off”: a situation known as the slicing problem. With passing by reference or through a pointer, the slicing problem does not occur because the address of the larger object instead of the larger object itself is passed to the function.

5 Static binding: some observations Assuming that there is a print( ) function in both the point and circle classes. point p, *pPtr = &p; circle c, *cPtr = &c; p.print( );// print function defined in point class c.print( );// print function defined in circle class pPtr->print( );// print function defined in point class cPtr->print( );// print function defined in circle class pPtr = &c;// now pPtr points to a circle obj! pPtr->print( );// still print function defined in clircle // class! Why??? Because of static // binding! At compile time, the // compiler uses the point type (class) // to generate the code!

6 Dynamic binding through virtual functions The whole situation is quite different if print function is declared virtual in the class (implying print will be virtual in the derived class as well). The binding of a function with the calling object occurs at run time, and the print function defined in the class (ADT) of the calling object will be activated.


Download ppt "The Slicing Problem CS240 Computer Science II. Some relationship between base and derived classes: data members Derived class inherits data members of."

Similar presentations


Ads by Google