25
Inheritance and Inheritance and Composition Composition Reusing the code and Reusing the code and functionality functionality Unit - 04 Unit - 04

Inheritance and Composition Reusing the code and functionality Unit - 04

Embed Size (px)

Citation preview

Page 1: Inheritance and Composition Reusing the code and functionality Unit - 04

Inheritance and Inheritance and CompositionComposition

Reusing the code and Reusing the code and functionalityfunctionality

Unit - 04Unit - 04

Page 2: Inheritance and Composition Reusing the code and functionality Unit - 04

Unit IntroductionUnit Introduction

This unit covers composition and This unit covers composition and inheritanceinheritance

Page 3: Inheritance and Composition Reusing the code and functionality Unit - 04

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

Page 4: Inheritance and Composition Reusing the code and functionality Unit - 04

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)

Page 5: Inheritance and Composition Reusing the code and functionality Unit - 04

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;

Page 6: Inheritance and Composition Reusing the code and functionality Unit - 04

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

}}

Page 7: Inheritance and Composition Reusing the code and functionality Unit - 04

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

Page 8: Inheritance and Composition Reusing the code and functionality Unit - 04

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() {}

};};

Page 9: Inheritance and Composition Reusing the code and functionality Unit - 04

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

Page 10: Inheritance and Composition Reusing the code and functionality Unit - 04

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

}}

Page 11: Inheritance and Composition Reusing the code and functionality Unit - 04

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

}}

};};

Page 12: Inheritance and Composition Reusing the code and functionality Unit - 04

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

}}

};};

Page 13: Inheritance and Composition Reusing the code and functionality Unit - 04

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

Page 14: Inheritance and Composition Reusing the code and functionality Unit - 04

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

};};

Page 15: Inheritance and Composition Reusing the code and functionality Unit - 04

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

}}

Page 16: Inheritance and Composition Reusing the code and functionality Unit - 04

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

Page 17: Inheritance and Composition Reusing the code and functionality Unit - 04

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

Page 18: Inheritance and Composition Reusing the code and functionality Unit - 04

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

Page 19: Inheritance and Composition Reusing the code and functionality Unit - 04

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

}}

Page 20: Inheritance and Composition Reusing the code and functionality Unit - 04

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) );

}}

Page 21: Inheritance and Composition Reusing the code and functionality Unit - 04

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()

}}

}}

Page 22: Inheritance and Composition Reusing the code and functionality Unit - 04

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

Page 23: Inheritance and Composition Reusing the code and functionality Unit - 04

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

}}

Page 24: Inheritance and Composition Reusing the code and functionality Unit - 04

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)

Page 25: Inheritance and Composition Reusing the code and functionality Unit - 04

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