As mentioned earlier, Perl has no built-in facilities for data inheritance. By and large, this isn't a problem at all. Consider the following:
Let's look at a simple class hierarchy:
Because of the way Perl works, in many cases there is no requirement for any kind of data inheritance. Objects have the members they are assigned. Their class is irrelevant.
Data inheritance and complex constructors
When constructors become more complex, however, some form of data inheritance may be necessary. A good example is when subclass constructors add default values for some members. Let's consider a class hierarchy of objects representing shapes in a graphics windowcircles, rectangles, polygons, text, and so on. Generally, a hierarchy like this is derived from a single parent classwe will call ours Graphic . Suppose the Graphic constructor sets some default values for line width and color :
The Graphic class
Now, suppose we want to derive a class, Text , from Graphic . Our constructor for Text also will need to set some default values, but these will be peculiar to Text objects. We will have to write the constructor for Text objects so that it invokes the Graphic constructor. However, we also have to be careful to write it so that the constructed object gets the Text default values. It must also wind up blessed into class Text :
The Text class
The tricky part in this example is the way in which the Graphic constructor is called. SUPER::new $pkg () invokes the inherited constructor (see Item 50 for more information about SUPER ), but passes 'Text' , not 'Graphic' , as the constructor's class argument. You might be tempted to write a slightly simpler Text constructor, eschewing the fancy SUPER keyword:
The Text classthe wrong way
This does the right thing by calling the parent class constructor, but unfortunately , this Text constructor creates and returns Graphic objects. You will have to re-bless them into Text at the end of the constructor:
This is okay, but you'll be better off using SUPER . Among other things, using SUPER::new means that you do not have to modify the subclass constructor if the name of the parent class changes.