INHERITANCE – PART 2
Constructors and Destructors under InheritanceInheritance
Multiple Inheritanceprivate and protected Inheritanceprivate and protected InheritanceCommon Programming Errors
CSC 330 OO Software Design 1
Wh t t b i h it d?What cannot be inherited?
f fNumber of member functions cannot be inherited:
C t tConstructorsDestructorsAssignment operators Assignment operators Friend functions
CSC 330 OO Software Design 2
Derived Class Constructors
A base class constructor is not inherited in a derived class
The base class constructor can be invoked by the constructor of the derived classThe constructor of a derived class begins by invokingthe constructor of the base class in the initializationsectionsection
CSC 330 OO Software Design 3
Example 4.5.1.p
class BC { // base classblipublic:BC( ) { x = y = -1; } // base constructor
protected:int get_( ) const { return x; }int get_y ( ) const { return y; }g _y ( ) { y; }
private:int x ;int y ;
} ;
class DC : public BC { // derived class public:public:
void write( ) const { cout << get_x( ) * get_y( ) << ‘\n'; }} ;
int main ( ) {DC dl; // dl.BC invokeddl write( ); // 1 written to standard output
CSC 330 OO Software Design 4
dl.write( ); // 1 written to standard output}
Parent Constructors and DestructorsWhen an object of a derived class (a subclass) is declared, then the parent’s default constructor is called before the required constructor of the derived class.If th t h t th th d t’ If the parent has a parent then the grandparent’s default is called followed by the parent’s default followed by the derived class constructor.In effect for an arbitrary number of parents the In effect, for an arbitrary number of parents, the parent default constructors are called in a top-down fashion.The same thing happens with the destructors The same thing happens with the destructors except it is down bottom-up (with the derived child class calling its own destructor first).
CSC 330 OO Software Design 5
E lExampleclass Person {class Person {public: public:
Person ( ) { }Person ( ) { }Person ( ) { }Person ( ) { }Person (string& s) { name =s; }Person (string& s) { name =s; }
private:private:string name;string name;
};}; Employee constructor invokes the b d f l
};};
class Employee: public Person {class Employee: public Person {public:public:
Employee ( ) : salary (0) { }Employee ( ) : salary (0) { }E l ( t i & d bl l)E l ( t i & d bl l)
Person constructor by default (implicitly) hereEmployee() : Person() automatically generatedEmployee (string& s, double sal)Employee (string& s, double sal)
: Person (s), salary (sal) { } : Person (s), salary (sal) { } private:private:
double salary;double salary;}}
automatically generated.
Employee constructors explicitly}} Employee constructors explicitlyinvokes a constructor of the Person class
CSC 330 OO Software Design 6
Employee e; <------ what happens here?
P t ?Parameters?A derived class will always invoke the yconstructor of the base class, as well as its own constructors. The base class constructor is always called first, followed by the constructor always called first, followed by the constructor of the derived class, and so on down the tree.
If th b t t t k t If the base constructor takes no parameters inheritance is implicit.
If it takes parameters these must be statedexplicitly in each derived class.
CSC 330 OO Software Design 7
Passing Parameters to the Base Class Constructorg
CSC 330 OO Software Design 8
Example 4.5.2.
class Animal {blipublic:
Animal() { species = "Animal”; }Animal( const char* s ) { species =s; }
private:string species;g p ;
} ;
class Primate: public Animal {public:
Primate ( ) : Animal( "Primate" ) { }Primate ( ) : Animal( Primate ) { }Primate( int n ) : Animal( "Primate" ) { heart_cham = n; }
private:int heart_cham;
} ;
Animal slug; // Animal( )Animal tweety( "canary" ) ; // Animal( const char* )Primate godzilla ; // Primate( )Primate human( 4 ); // Primate( int )
CSC 330 OO Software Design 9
Primate human( 4 ); // Primate( int )
Defa lt Initiali ationDefault Initialization
If d i d l t t d t i k b If a derived class constructor does not invoke a base class constructor explicitly, the base class default constructor will be used.If l B i d i d f l A d l CIf class B is derived from class A and class Cis derived from class B
When a object of class C is created The base class A's constructor is the first invokedClass B's constructor is invoked nextC's constructor completes executionp
CSC 330 OO Software Design 10
Example 4.5.3.Example 4.5.3.
class Animal {public:public:Animal( ) { species = “Animal” ; }
Animal( const char* s ) { species = s; }private:
string species;} } ;class Primate: public Animal {public:
Primate( ) : Animal( "Primate" ) { }Primate( int n ) : Animal( "Primate" )( ) ( )
{ heart_cham =n; }private:
int heart_cham;} ;class Human : public Primate {class Human : public Primate {public:
Human( ) : Primate( ) { }Human( int c ) : Primate( c ) { }
} ;
CSC 330 OO Software Design 11
Human jill; // Human( )Human fred( 4 ) ; // Human( int)
Derived Class Constructor Rules – Example 4.5.4.If a base class has constructors but not default constructor, then a derived class constructor must explicitly invoke some basic class constructor.
// BC has constructors but no// default constructor// default constructorclass BC { // base class
public:BC( int a ) { x = a; y = 999; }BC( int al, int a2 ) { x = al; y = a2; }private:int x;int y;} ;
// DC has a constructor (any constructor// DC has a constructor (any constructor// will do for the example)class DC : public BC derived classpublic:
// *** ERROR: DC( int ) must explicitly// i k BC t t// invoke a BC constructorDC( int n ) { z = n; }
private:int Z;
} ;
CSC 330 OO Software Design 12
} ;
Example 4.5.5.Example 4.5.5.
class BC { // base classclass BC { // base classpublic:
BC( ) { cout << "BC::BC( ) executes ... \n"; }private:
int x;} ;class DC : public BC { // derived classpublic:
DC( ) { cout << "DC::DC ( ) executes\n"; }private:private:
int y;} ;int main( ) {
DC d;// // . . .} ;
BC::BC( ) executes ….DC::DC( ) executes …
CSC 330 OO Software Design 13
( )
Fig. 4.5.3.// approach 1: have DC's constructor
li i l// approach 2: give BC a default
explicitly// invoke one of BC’s constructors
class BC { // base classpublic:
constructor
class BC { // base classpublic:public:
BC( int a ) { x = a; y = 999; }BC( int al, int a2 ) { x = al; y = a2; }
private:int
public:BC( ) { x = 1; y = 2; } // defaultBC( int a ) { x = a; y =
999; }BC( int al, int a2} { x = al; y = a2; }int x;
int y;} ;// DC's constructor explicitly invokes a// BC constructor in its initialization
}private:
int x;int y;
} ;// DC's constr ctor need not in oke a
//section
class DC : public BC { // derived classpublic:// ok: DC( int ) explicitly invokes BC(
int, int )
// DC's constructor need not invoke a BC
// constructor because BC how has a// default constructorclass DC : public BC { // derived class, )
DC( int n ) : BC( n, n + 1) { z = n; }
private:int z;
} ;
public:// ok: BC has a default constructorDC( int n ) { z = n; }
private:int z;
CSC 330 OO Software Design 14
} ; int z;} ;
Rules using DC as a class derived from BC
If DC has constructors but BC has no constructors, then the appropriate DC constructor executes automatically whenever a appropriate DC constructor executes automatically whenever a DC object is created.
If DC has no constructors but BC has constructors, then BC must have a default constructor so that BC’s default constructor can have a default constructor so that BC s default constructor can execute automatically whenever a DC object is created.
If DC has constructors and BC has a default constructor, then BC’s default constructor executes automatically whenever a DC yobject is created unless the appropriate DC constructor explicitly invokes, in its initialization, some other BC constructor.
If DC and BC have constructors but BC has no default h h DC li i l i k i constructor, then each DC constructor must explicitly invoke, in
its initialization section, a BC constructor, which then executes when a DC object is created.
CSC 330 OO Software Design 15
Example 4.5.6.Example 4.5.6.
class Team { // base classclass Team { // base classpublic:
Team( int len = 100 ) {names = new string[ maxno = len ] ; }
protected:string* names;int maxno;// …
} ;
class BaseballTeam : public Team { // derived classpublic:
BaseballTeam( const string s[ ], int si ) : Team( si ) {for ( int i = 0; i < si; i++ )names[ i ] s[ i ]names[ i ] = s[ i ];
}// …
} ;
CSC 330 OO Software Design 16
Destructors in Derived Classes
If th b l h ki d t t If the base class has a working destructor, defining the destructor for the defined class is relatively easy.
Wh th d t t f d i d l i ll d When the destructor for a derived class is called, the destructor for the base class is automatically called.Th d i d l d t t d l d l t The derived class destructor need only use delete on dynamic variables added in the derived class, and data they may point to.
CSC 330 OO Software Design 17
Destr ctors Seq enceDestructors Sequence
If l B i d i d f l A d l CIf class B is derived from class A and class Cis derived from class B…
When the destructor of an object of class C goes t f out of scopeThe destructor of class C is calledThen the destructor of class BThen the destructor of class A
Notice that destructors are called in the reverse order of constructor calls
CSC 330 OO Software Design 18
Destructors Under Inheritance - ExampleDestructors Under Inheritance Example
class BCpublic:public:
BC( ) { cout << “BC's constructor\n” ; }~BC( ) { cout << “BC's destructor\n"; }
} ;
l DC bli BC {class DC : public BC {public:
DC( ) : BC( ) { cout << "DC's constructor\n"; }~DC( ) { cout << “DC's destructor\n"; }
} ;} ;
int main ( ) {DC d; return 0;
} }
BC's constructor DC's constructor DC's destructor
CSC 330 OO Software Design 19
BC's destructor
Fig. 4.5.7. Destructors freeing storage allocated by constructors
class BC { // base classpublic:
BC( ) { sBC = new char[ 3 ]; cout << "BC allocates 3 bytes\n"; }~BC( ) { delete[ ] sBC; cout << "BC frees 3 bytes\n"; }
private: char* sBC;
} ;} ;
class DC : public BC { // derived classpublic:
DC( ) : BC( ) { sDC = new char[ 5 ] ; cout << "DC allocates 5 bytes\n"; }bytes\n"; }
~DC( ) { delete[ ] sDC; cout << "DC frees 5 bytes\n"; }private:
char* sDC;} ;
int main( ) {DC dl; return 0;
}
CSC 330 OO Software Design 20
}
Example
class Rect { // simple rectangle
public:Rect();Rect();~Rect();
// ignore rest of the focus so that we can focus on the // automatic chaining
private:private:int left, top; //upper-left cornerint width, height; //size
};l l {class Color {public:
Color();~Color();// . .
private:int data;
//color is stored compactly in an integer
CSC 330 OO Software Design 21
};
class Textbox : public Rect {
Example(cont)p {
// a text box is a rectangle public:
TextBox();~TextBox();TextBox();// . .
private:Color textColor; //color to draw text in composition//color to draw text in -compositionint frameThickness; char *text; // text to draw
};
Rect::Rect() {left = top = width = height = 0;cout << "in default constructor for: Rect \n";
}
Rect::~Rect(){cout << "in destructor for: Rect \n";
CSC 330 OO Software Design 22
}
Example(cont)
The default constructor and destructor for Color is much the same.
TextBox::TextBox() {
frameThickness = 0;t t 0text = 0;cout << "in default constructor for: TextBox\n";
}// b f ti f T tB// member functions for TextBox
Textbox::~TextBox() {
cout << "in destructor for: TextBox\n";cout << "in destructor for: TextBox\n";if (text != 0) free(text);}
CSC 330 OO Software Design 23
Example(cont)
main() {TextBox tbox; //instantiate TextBoxTextBox tbox; //instantiate TextBoxcout << ">> main() complete <<\n";
}
we get the result:
in default constructor for: Rect
in default constructor for: Color
in default constructor for: TextBox
>> main complete <<
in destructor for: TextBox
in destructor for: Color
in destructor for: Rect
CSC 330 OO Software Design 24