Date post: | 21-Jan-2016 |
Category: |
Documents |
Upload: | juliet-woods |
View: | 212 times |
Download: | 0 times |
Inheritance and Inheritance and CompositionComposition
Reusing the code and Reusing the code and functionalityfunctionality
Unit - 04Unit - 04
Unit IntroductionUnit Introduction
This unit covers composition and This unit covers composition and inheritanceinheritance
Unit ObjectivesUnit Objectives
After covering this unit you will understand…After covering this unit you will understand… CompositionComposition InheritanceInheritance Inheritance & constructor call sequenceInheritance & constructor call sequence Multiple inheritanceMultiple inheritance Upcasting & inheritanceUpcasting & inheritance C++ casting operatorsC++ casting operators Different types of InheritanceDifferent types of Inheritance Inheritance vs. compositionInheritance vs. composition
Composition Composition (Aggregation)(Aggregation)
Creating and using objects of other Creating and using objects of other class within a different classclass within a different class
Also known as embedded object (or Also known as embedded object (or sub-object)sub-object)
Example: CompositionExample: Compositionclass X class X
{{
private:private:
int m_Data; int m_Data; // data member// data member
public:public:
X() {} X() {} // default constructor// default constructor
SetX (int k) SetX (int k) // member function// member function
{{
m_Data = k;m_Data = k;
}}
};};
class Y class Y
{{
private:private:
int m_Data;int m_Data;
Example: Composition Example: Composition (contd.)(contd.)
public:public:
X x; X x; // composition// composition
Y() {} Y() {} //default constructor//default constructor
};};
void main() void main()
{{
Y y; Y y; // creating object of class Y// creating object of class Y
y.x.SetX(20); y.x.SetX(20); // Access/sets the embedded object// Access/sets the embedded object
}}
InheritanceInheritance
Parent class is called the Parent class is called the basebase class class The class which inherits the base The class which inherits the base
class is called the class is called the derivedderived class; and class; and has all the features of the base class, has all the features of the base class, plus its own featuresplus its own features
Example: InheritanceExample: Inheritanceclass X class X
{{
int m_Data;int m_Data;
public:public:
X() {}X() {}
};};
class Y : public X class Y : public X // class Y publicly inherits class X// class Y publicly inherits class X
{{
int m_Data;int m_Data;
public:public:
Y() {}Y() {}
};};
Constructor and Constructor and InheritanceInheritance
The constructor and destructor calls The constructor and destructor calls are automatic for the base class, in are automatic for the base class, in case the derived class object is createdcase the derived class object is created
The order of base and derived class The order of base and derived class constructors and destructors are:constructors and destructors are: base constructorbase constructor derived constructorderived constructor derived destructorderived destructor base destructorbase destructor
Multiple InheritanceMultiple Inheritance
There could be two or more base class There could be two or more base class for a derived classfor a derived class
It can cause ambiguity and is not It can cause ambiguity and is not recommended in normal casesrecommended in normal cases
There are ways to have single There are ways to have single inheritance used instead of multiple inheritance used instead of multiple inheritance to achieve the goalinheritance to achieve the goal
class Z : public X, public Y class Z : public X, public Y
{{
// class definition// class definition
}}
Example: Multiple Example: Multiple InheritanceInheritance
class Aclass A
{{
public:public:
void SomeFunction(void) void SomeFunction(void)
{{
// function code// function code
}}
};};
class Bclass B
{{
public:public:
void SomeFunction(void) void SomeFunction(void)
{{
// function code// function code
}}
};};
Example: Multiple Inheritance Example: Multiple Inheritance (contd.)(contd.)
class C : public A, public Bclass C : public A, public B
{{
public:public:
void MyFunction(void)void MyFunction(void)
{{
SomeFunction(); SomeFunction(); // Ambiguous as the compiler// Ambiguous as the compiler // does not know whether to // does not know whether to //choose SomeFunction() of A or B//choose SomeFunction() of A or B
}}
};};
Upcasting and Upcasting and DowncastingDowncasting
Casting from derived to base class is Casting from derived to base class is known as Upcasting (implicit)known as Upcasting (implicit)
Upcasting lose the derived class Upcasting lose the derived class propertiesproperties
Casting from base to derived class is Casting from base to derived class is known as Downcastingknown as Downcasting
Downcasting makes derived class’s Downcasting makes derived class’s properties availableproperties available
Example: Upcasting and Example: Upcasting and DowncastingDowncastingclass Person class Person
{{
private:private:
int Age;int Age;
char* Name;char* Name;
char Gender;char Gender;
public:public:
// accessor methods for member variables// accessor methods for member variables
};};
class Employee : public Personclass Employee : public Person
{{
private:private:
char* Department;char* Department;
int EmployeeCode;int EmployeeCode;
public:public:
// accessor methods for member variables// accessor methods for member variables
};};
Example: Upcasting and Downcasting Example: Upcasting and Downcasting (contd.)(contd.)
void main()void main()
{{
Person* pPerson = new Employee();Person* pPerson = new Employee(); // upcast, implicit// upcast, implicit
pPerson->GetName();pPerson->GetName(); // fine// fine
pPerson->GetDepartment();pPerson->GetDepartment(); // error// error
Employee* pEmployee = (Employee*)pPerson;Employee* pEmployee = (Employee*)pPerson; // downcast// downcast
pEmployee->GetDepartment();pEmployee->GetDepartment(); // fine now// fine now
}}
C++ Casting OperatorsC++ Casting Operators
Replace the traditional, parenthetic Replace the traditional, parenthetic casting techniquecasting technique
ExplicitExplicit Self documentingSelf documenting Signal a type conversionSignal a type conversion Less risk of illegal cast and data Less risk of illegal cast and data
corruptioncorruption
C++ Casting Operators C++ Casting Operators (contd.)(contd.) static_caststatic_cast
Compile-time castCompile-time cast Casting classes that provide static Casting classes that provide static
polymorphism (non-virtual classes)polymorphism (non-virtual classes) dynamic_castdynamic_cast
Run-time cast, to cast classes that provide Run-time cast, to cast classes that provide dynamic polymorphism (virtual classes)dynamic polymorphism (virtual classes)
const_castconst_cast To remove const-nessTo remove const-ness
reinterpret_castreinterpret_cast For conversion of unrelated typesFor conversion of unrelated types
Example: static_castExample: static_cast// Note that Base is not a virtual class// Note that Base is not a virtual class
class Base{class Base{
};};
class Derived : public Base {class Derived : public Base {
};};
void f(Base* pBase)void f(Base* pBase)
{{
Derived* pDerived = static_cast<Derived*>pBaseDerived* pDerived = static_cast<Derived*>pBase
}}
// Also,// Also,
enum fruit{apple=0, orange=1, banana=2};enum fruit{apple=0, orange=1, banana=2};
int x = 2;int x = 2;
fruit f1 = static_cast<fuit>(x); fruit f1 = static_cast<fuit>(x); // converts an int to enum// converts an int to enum
Example: dynamic_castExample: dynamic_cast// Note that Base is a virtual class// Note that Base is a virtual class
class Base{class Base{
virtual void f();virtual void f();
};};
class Derived : public Base {class Derived : public Base {
void f (){}void f (){}
};};
void f(Base* pBase)void f(Base* pBase)
{{
//Derived* pDerived = static_cast<Derived*>pBase //Derived* pDerived = static_cast<Derived*>pBase // error// error
// use dynamic_cast instead// use dynamic_cast instead
Derived* pDerived = dynamic_cast<Derived*>pBase Derived* pDerived = dynamic_cast<Derived*>pBase // fine// fine
}}
Example: const_castExample: const_castdouble f(double& d);double f(double& d); // f accepts reference to type double// f accepts reference to type double
void g(const double& d)void g(const double& d)
{{
// while calling f() the const-ness of d is removed// while calling f() the const-ness of d is removed
double val = f( const_cast<double&>(d) );double val = f( const_cast<double&>(d) );
}}
Example: Example: reinterpret_castreinterpret_cast
// a practical example could returns hash code based on an // a practical example could returns hash code based on an
// address// address
unsigned short Hash(void* p) unsigned short Hash(void* p)
{{
// reinterpret casting a pointer to integral value// reinterpret casting a pointer to integral value
unsigned int val = reinterpret_cast<unsigned int> (p);unsigned int val = reinterpret_cast<unsigned int> (p);
val = val & 16;val = val & 16; // hash code formula// hash code formula
return (unsigned short)val; return (unsigned short)val; // cast to the returned type// cast to the returned type
}}
void main()void main()
{{
int a[10];int a[10];
for (int i = 0; i < 10; i++)for (int i = 0; i < 10; i++)
{{
cout << Hash(a + i) << endl;cout << Hash(a + i) << endl; // using Hash()// using Hash()
}}
}}
Inheritance TypesInheritance Types
Inheritance has three types:Inheritance has three types: publicpublic privateprivate protectedprotected
The following chart gives the The following chart gives the accessibility details of the accessibility details of the inheritance types:inheritance types:Public Inheritance Protected Inheritance Private Inheritance
Private Variable Inaccessible Inaccessible InaccessibleProtected Variable Protected Protected PrivatePublic Variable Public Protected PrivatePrivate Function Inaccessible Inaccessible InaccessibleProtected Function Protected Protected PrivatePublic Function Public Protected Private
Inheritance Types Inheritance Types (contd.)(contd.)
Protected Function in the base class Protected Function in the base class is treated as Private Function in the is treated as Private Function in the child class (taking the example of child class (taking the example of the value in bold), when inherited the value in bold), when inherited using the private keywordusing the private keyword
class X : public Y, private Z, protected W class X : public Y, private Z, protected W
{{
// class definition// class definition
}}
Inheritance vs. Inheritance vs. CompositionComposition
Composition is generally used when Composition is generally used when you want the features of an existing you want the features of an existing class inside your new class, but not class inside your new class, but not its interfaceits interface
Use inheritance for Use inheritance for sub-typingsub-typing, , where you want your new type to where you want your new type to have exactly the same interface as have exactly the same interface as the existing type (plus any other the existing type (plus any other member functions you want to add)member functions you want to add)
Unit SummaryUnit Summary
In this unit you have covered …In this unit you have covered … CompositionComposition InheritanceInheritance Multiple inheritanceMultiple inheritance Upcasting & inheritanceUpcasting & inheritance C++ casting operatorsC++ casting operators Types of inheritanceTypes of inheritance Inheritance vs. compositionInheritance vs. composition