 2000 Deitel & Associates, Inc. All rights reserved. Chapter 21 - Standard C++ Language Additions Outline 21.1Introduction 21.2 bool Data Type 21.3 static_cast.

Slides:



Advertisements
Similar presentations
Chapter 19 - Inheritance Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved Multiple Inheritance Multiple inheritence –Derived class has several base classes –Powerful, but.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 18 - C++ Operator Overloading Outline 18.1Introduction.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 19 - Inheritance Outline 19.1Introduction 19.2Inheritance: Base Classes and Derived Classes 19.3Protected.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 18 - Operator Overloading Outline 18.1Introduction 18.2Fundamentals of Operator Overloading 18.3Restrictions.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 22 - C++ Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Inheritance Outline 9.1Introduction 9.2Inheritance: Base Classes and Derived Classes 9.3.
 2006 Pearson Education, Inc. All rights reserved Other Topics.
Basic Elements of C++ Chapter 2.
Review of C++ Programming Part II Sheng-Fang Huang.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
COMPUTER PROGRAMMING. Data Types “Hello world” program Does it do a useful work? Writing several lines of code. Compiling the program. Executing the program.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 19 - C++ Inheritance Outline 19.1Introduction.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction 15.2C A Simple Program: Adding Two Integers.
COMPUTER PROGRAMMING. variable What is variable? a portion of memory to store a determined value. Each variable needs an identifier that distinguishes.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 19 – Inheritance Part 2 Outline 19.8Direct Base Classes and Indirect Base Classes 19.9Using Constructors.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Variables and Data Types.  Variable: Portion of memory for storing a determined value.  Could be numerical, could be character or sequence of characters.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Inheritance Outline 9.1Introduction 9.2Inheritance: Base Classes and Derived Classes 9.3.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
1 Functions in C++ Default arguments Overloading Inlining Call-by-reference Scope of variables, static, extern namespace new and delete assert.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 25 December 1, 2009.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Inheritance and Composition Reusing the code and functionality Unit - 04.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
 2003 Prentice Hall, Inc. All rights reserved. 1 namespaces Program has identifiers in different scopes –Sometimes scopes overlap, lead to problems Namespace.
1 Advanced Topics in Functions Lecture Unitary Scope Resolution Operator Unary scope resolution operator ( :: )  Access global variable if.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 19 – Inheritance – Part 1 Outline 19.1Introduction 19.2Inheritance: Base Classes and Derived Classes.
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
 2000 Deitel & Associates, Inc. All rights reserved. 12.1Introduction Templates - easily create a large range of related functions or classes –function.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Chapter 18 - C++ Operator Overloading
C++ Lesson 1.
Asst.Prof.Dr. Tayfun ÖZGÜR
Chapter 1.2 Introduction to C++ Programming
Chapter 22 - C++ Templates
Introduction to C++ (Extensions to C)
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Operator Overloading; String and Array Objects
Basic Elements of C++.
Reserved Words.
Chapter 22 - Other Topics Outline 22.1 Introduction
Basic Elements of C++ Chapter 2.
Operator Overloading; String and Array Objects
Operator Overloading; String and Array Objects
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Operator Overloading.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 19 - Inheritance Outline 19.1 Introduction
Chapter 15 - C++ As A "Better C"
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 18 - Operator Overloading
Chapter 22 - C++ Templates
Chapter 22 - C++ Templates
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Presentation transcript:

 2000 Deitel & Associates, Inc. All rights reserved. Chapter 21 - Standard C++ Language Additions Outline 21.1Introduction 21.2 bool Data Type 21.3 static_cast Operator 21.4 const_cast Operator 21.5 reinterpret_cast Operator 21.6namespaces 21.7Run-Time Type Information (RTTI) 21.8Operator Keywords 21.9 explicit Constructors mutable Class Members 21.11Pointers to Class Members (.* and ->* ) 21.12Multiple Inheritance and virtual Base Classes

 2000 Deitel & Associates, Inc. All rights reserved. 21.1Introduction We shall cover standard C++ features –data type bool –cast operators –namespace s –run-time type information (RTTI) –operator keywords

 2000 Deitel & Associates, Inc. All rights reserved bool Data Type bool - can be false or true –preferable to 0 (false) and non-zero (true) outputting bool variables –numerical default ( 0 or 1 ) –stream manipulator boolalpha outputs string "true" or "false" Examples: cout << boolVariable cout << boolalpha << boolVariable

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Initialize bool variable an int. 2. Input a variable. 3. Print the bool value of the int. 3.1 Print the value of bool variable. 1// Fig. 21.1: fig21_01.cpp 2// Demonstrating data type bool. 3#include 4 5using std::cout; 6using std::endl; 7using std::cin; 8using std::boolalpha; 9 10int main() 11{ 12 bool boolean = false; 13 int x = 0; cout << "boolean is " << boolean 16 << "\nEnter an integer: "; 17 cin >> x; cout << "integer " << x << " is" 20 << ( x ? " nonzero " : " zero " ) 21 << "and interpreted as "; 22 boolean is 0 Enter an integer: 22

 2000 Deitel & Associates, Inc. All rights reserved. Outline 3.2 Print the string value of the bool variable. Program Output 23 if ( x ) 24 cout << "true\n"; 25 else 26 cout << "false\n"; boolean = true; 29 cout << "boolean is " << boolean; 30 cout << "\nboolean output with boolalpha manipulator is " 31 << boolalpha << boolean << endl; return 0; 34} boolean is 0 Enter an integer: 22 integer 22 is nonzero and interpreted as true boolean is 1 boolean output with boolalpha manipulator is true Notice how the output varies. boolean is 1 boolean output with boolalpha manipulator is true integer 22 is nonzero and interpreted as true

 2000 Deitel & Associates, Inc. All rights reserved static_cast Operator C++ has 4 separate, specific casts static_cast - conversion between types –type checking at compile time –standard conversions: void* to char*, int to float, etc. –base class pointers to derived class pointers Format: static_cast ( object to convert ) int z = 3; float x = static_cast (z);

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Define class BaseClass 1.1 Define member function 1.2 Define class DerivedClass 1.3 Define member function 1.4 Global function prototype (calls function f ) 2. Function calls 3. Output results 1// Fig. 21.2: fig21_02.cpp 2// Demonstrating the static_cast operator. 3#include 4 5using std::cout; 6using std::endl; 7 8class BaseClass { 9public: 10 void f( void ) const { cout << "BASE\n"; } 11}; 12 13class DerivedClass : public BaseClass { 14public: 15 void f( void ) const { cout << "DERIVED\n"; } 16}; 17 18void test( BaseClass * ); 19 20int main() 21{ 22 // use static_cast for a conversion 23 double d = 8.22; 24 int x = static_cast ( d ); cout << "d is " << d << "\nx is " << x << endl; BaseClass * basePtr = new DerivedClass; 29 test( basePtr ); // call test 30 delete basePtr; convert double to int d is 8.22 x is 8

 2000 Deitel & Associates, Inc. All rights reserved. Outline 3.1 Function definition Program Output return 0; 33} 34 35void test( BaseClass * basePtr ) 36{ 37 DerivedClass *derivedPtr; // cast base class pointer into derived class pointer 40 derivedPtr = static_cast ( basePtr ); 41 derivedPtr->f(); // invoke DerivedClass function f 42} d is 8.22 x is 8 DERIVED converts a base pointer to a derived pointer, and calls the derived function f

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Class definition 1.1 Initialize objects 2. Print 1// Fig. 21.2: fig21_02.cpp 2// Demonstrating the static_cast operator. 3#include 4 5using std::cout; 6using std::endl; 7 8class BaseClass { 9public: 10 void f( void ) const { cout << "BASE\n"; } 11}; 12 13class DerivedClass : public BaseClass { 14public: 15 void f( void ) const { cout << "DERIVED\n"; } 16}; 17 18void test( BaseClass * ); 19 20int main() 21{ 22 // use static_cast for a conversion 23 double d = 8.22; 24 int x = static_cast ( d ); cout << "d is " << d << "\nx is " << x << endl; BaseClass * basePtr = new DerivedClass; 29 test( basePtr ); // call test 30 delete basePtr; In const function print the this pointer is originally const ConstCastTest *. It is cast into type ConstCastTest *, and can then be modified.

 2000 Deitel & Associates, Inc. All rights reserved. Outline 3. Function definition Program Output return 0; 33} 34 35void test( BaseClass * basePtr ) 36{ 37 DerivedClass *derivedPtr; // cast base class pointer into derived class pointer 40 derivedPtr = static_cast ( basePtr ); 41 derivedPtr->f(); // invoke DerivedClass function f 42} d is 8.22 x is 8 DERIVED

 2000 Deitel & Associates, Inc. All rights reserved const_cast Operator const_cast - cast away const or volatile –cannot be used directly to cast away const -ness use pointers

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Define class ConstCastTest 1.1 Define member functions 1// Fig. 21.3: fig21_03.cpp 2// Demonstrating the const_cast operator. 3#include 4 5using std::cout; 6using std::endl; 7 8class ConstCastTest { 9public: 10 void setNumber( int ); 11 int getNumber() const; 12 void printNumber() const; 13private: 14 int number; 15}; 16 17void ConstCastTest::setNumber( int num ) { number = num; } 18 19int ConstCastTest::getNumber() const { return number; } 20 21void ConstCastTest::printNumber() const 22{ 23 cout << "\nNumber after modification: "; // the expression number-- would generate compile error

 2000 Deitel & Associates, Inc. All rights reserved. Outline 2. Create and initialize object 3. Modify and print object with a const function. Program Output 26 // undo const-ness to allow modification 27 const_cast ( this )->number--; cout << number << endl; 30} 31 32int main() 33{ 34 ConstCastTest x; 35 x.setNumber( 8 ); // set private data number to cout << "Initial value of number: " << x.getNumber(); x.printNumber(); 40 return 0; 41} Initial value of number: 8 Number after modification: 7 Casts the this pointer into type ConstCastTest *. This casts away the " const -ness" and allows number to be modified.

 2000 Deitel & Associates, Inc. All rights reserved reinterpret_cast Operator reinterpret_cast - for nonstandard casts –one pointer type to another pointer type, void* to int, etc. –cannot be used for standard casts ( int to double, etc.).

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Initialize variables and pointers 2. Cast a pointer to pointer of a different type 3. Output data Program Output 1// Fig. 21.4: fig21_04.cpp 2// Demonstrating the reinterpret_cast operator. 3#include 4 5using std::cout; 6using std::endl; 7 8int main() 9{9{ 10 int x = 120, *ptr = &x; cout ( ptr ) << endl; return 0; 15} x ptr (type int * ) cast to a pointer of type ( char * ). 120 is the ASCII character code for 'x'

 2000 Deitel & Associates, Inc. All rights reserved. 21.6namespaces variables with same name and different scopes can overlap –need to distinguish them a namespace defines a scope for local and global identifiers. –body delimited by braces {} –use ( :: ) to access namespace members: namespace_name :: member –or, a using statement must occur before name is used using namespace namespace_name; - members of the namespace do not need a prefix –not guaranteed to be unique –can be nested

 2000 Deitel & Associates, Inc. All rights reserved. 21.6namespaces (II) Unnamed namespaces –occupy global namespace –directly accessible –do not need namespace name –global variables are in global namespace accessible in all scopes

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Use std namespace 1.1 Declare global variable 1.2 Define namespace Example 1.3 Define namespace inner 1.4 Define unnamed namespace 2. Print variables 1// Fig. 21.5: fig21_05.cpp 2// Demonstrating namespaces. 3#include 4using namespace std; // use std namespace 5 6int myInt = 98; // global variable 7 8namespace Example { 9 const double PI = ; 10 const double E = ; 11 int myInt = 8; 12 void printValues(); namespace Inner { // nested namespace 15 enum Years { FISCAL1 = 1990, FISCAL2, FISCAL3 }; 16 } 17} 18 19namespace { // unnamed namespace 20 double d = 88.22; 21} 22 23int main() 24{ 25 // output value d of unnamed namespace 26 cout << "d = " << d; // output global variable 29 cout << "\n(global) myInt = " << myInt; Unnamed namespace members do not need qualifiers d = (global) myInt = 98

 2000 Deitel & Associates, Inc. All rights reserved. Outline 2. Print variables 3. Function definition 31 // output values of Example namespace 32 cout << "\nPI = " << Example::PI << "\nE = " 33 << Example::E << "\nmyInt = " 34 << Example::myInt << "\nFISCAL3 = " 35 << Example::Inner::FISCAL3 << endl; Example::printValues(); // invoke printValues function return 0; 40} 41 42void Example::printValues() 43{ 44 cout << "\nIn printValues:\n" << "myInt = " 45 << myInt << "\nPI = " << PI << "\nE = " 46 << E << "\nd = " << d << "\n(global) myInt = " 47 << ::myInt << "\nFISCAL3 = " 48 << Inner::FISCAL3 << endl; 49} PI = E = myInt = 8 FISCAL3 = 1992 In printValues: myInt = 8 PI = E = d = (global) myInt = 98 FISCAL3 = 1992 Function printValues is a member of Example and does not need a namespace qualifier.

 2000 Deitel & Associates, Inc. All rights reserved. Outline Program Output d = (global) myInt = 98 PI = E = myInt = 8 FISCAL3 = 1992 In printValues: myInt = 8 PI = E = d = (global) myInt = 98 FISCAL3 = 1992

 2000 Deitel & Associates, Inc. All rights reserved. 21.7Run-Time Type Information (RTTI) determines an object's type at run time typeid (in ) typeid( object ).name() - returns the name of the object as a C-style string dynamic_cast - for polymorphic programming –often used to downcast base-class pointer to derived-class pointer –used with virtual functions

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Define base and derived classes 1// Fig. 21.7: fig21_07.cpp 2// Demonstrating dynamic_cast. 3#include 4 5using std::cout; 6using std::endl; 7 8const double PI = ; 9 10class Shape { 11 public: 12 virtual double area() const { return 0.0; } 13}; 14 15class Circle : public Shape { 16public: 17 Circle( int r = 1 ) { radius = r; } virtual double area() const 20 { 21 return PI * radius * radius; 22 }; 23protected: 24 int radius; 25}; 26 27class Cylinder : public Circle { 28public: 29 Cylinder( int h = 1 ) { height = h; } virtual double area() const 32 { 33 return 2 * PI * radius * height +

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Function prototype 1.2 Declare objects 2. Function calls 3. Define function * Circle::area(); 35 } 36private: 37 int height; 38}; 39 40void outputShapeArea( const Shape * ); // prototype 41 42int main() 43{ 44 Circle circle; 45 Cylinder cylinder; 46 Shape *ptr = 0; outputShapeArea( &circle ); // output circle's area 49 outputShapeArea( &cylinder ); // output cylinder's area 50 outputShapeArea( ptr ); // attempt to output area 51 return 0; 52} 53 54void outputShapeArea( const Shape *shapePtr ) 55{ 56 const Circle *circlePtr; 57 const Cylinder *cylinderPtr; // cast Shape * to a Cylinder * 60 cylinderPtr = dynamic_cast ( shapePtr ); if ( cylinderPtr != 0 ) // if true, invoke area() 63 cout area(); 64 else { // shapePtr does not refer to a cylinder // cast shapePtr to a Circle * Notice how shapePtr is cast to various types. If it is not of the right type, the cast returns 0.

 2000 Deitel & Associates, Inc. All rights reserved. Outline 3. Define function. Program Output 67 circlePtr = dynamic_cast ( shapePtr ); if ( circlePtr != 0 ) // if true, invoke area() 70 cout area(); 71 else 72 cout << "Neither a Circle nor a Cylinder."; 73 } cout << endl; 76} Circle's area: Cylinder's area: Neither a Circle nor a Cylinder. Notice how shapePtr is cast to various types. If it is not of the right type, the cast returns 0.

 2000 Deitel & Associates, Inc. All rights reserved. 21.8Operator Keywords can use keywords in place of operators (such as !, &, ^, etc.). –use header (may vary with compiler)

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Load header 1.1 Initialize variables 2. Use operator keywords 3. Print results 1// Fig. 21.9: fig21_09.cpp 2// Demonstrating operator keywords. 3#include 4 5using std::cout; 6using std::endl; 7using std::boolalpha; 8 9#include 10 11int main() 12{ 13 int a = 8, b = 22; cout << boolalpha 16 << " a and b: " << ( a and b ) 17 << "\n a or b: " << ( a or b ) 18 << "\n not a: " << ( not a ) 19 << "\na not_eq b: " << ( a not_eq b ) 20 << "\na bitand b: " << ( a bitand b ) 21 << "\na bit_or b: " << ( a bitor b ) 22 << "\n a xor b: " << ( a xor b ) 23 << "\n compl a: " << ( compl a ) 24 << "\na and_eq b: " << ( a and_eq b ) 25 << "\n a or_eq b: " << ( a or_eq b ) 26 << "\na xor_eq b: " << ( a xor_eq b ) << endl; return 0; 29} Operator keywords can be used instead of the symbols

 2000 Deitel & Associates, Inc. All rights reserved. Outline Program Output a and b: true a or b: true not a: false a not_eq b: false a bitand b: 22 a bit_or b: 22 a xor b: 0 compl a: -23 a and_eq b: 22 a or_eq b: 30 a xor_eq b: 30

 2000 Deitel & Associates, Inc. All rights reserved explicit Constructors constructors with one argument can be used for implicit conversion –type received by constructor turned into an object –automatic conversion sometimes undesirable keyword explicit prevents implicit conversion –use before constructor prototype in class definition

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Define Array class 1.1 Define constructor 1.2 Define destructor 2. Create object 2.1 Print Array object 2.2 Print int 3. Function definition 1// Fig. 21.9: fig21_09.cpp 2// Demonstrating operator keywords. 3#include 4 5using std::cout; 6using std::endl; 7using std::boolalpha; 8 9#include 10 11int main() 12{ 13 int a = 8, b = 22; cout << boolalpha 16 << " a and b: " << ( a and b ) 17 << "\n a or b: " << ( a or b ) 18 << "\n not a: " << ( not a ) 19 << "\na not_eq b: " << ( a not_eq b ) 20 << "\na bitand b: " << ( a bitand b ) 21 << "\na bit_or b: " << ( a bitor b ) 22 << "\n a xor b: " << ( a xor b ) 23 << "\n compl a: " << ( compl a ) 24 << "\na and_eq b: " << ( a and_eq b ) 25 << "\n a or_eq b: " << ( a or_eq b ) 26 << "\na xor_eq b: " << ( a xor_eq b ) << endl; return 0; 29} 15 is not an Array object, but it is implicitly converted to an Array object using the conversion constructor. This new object is printed using outputArray. If the keyword explicit comes before the constructor, this program will issue a compiler error - outputArray cannot take an int.

 2000 Deitel & Associates, Inc. All rights reserved. Outline Program Output a and b: true a or b: true not a: false a not_eq b: false a bitand b: 22 a bit_or b: 22 a xor b: 0 compl a: -23 a and_eq b: 22 a or_eq b: 30 a xor_eq b: 30

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Class definition 1.1 Function prototype 1.2 Member variables Load header file 1// Fig 21.10: array2.h 2// Simple class Array (for integers) 3#ifndef ARRAY2_H 4#define ARRAY2_H 5 6#include 7 8using std::ostream; 9 10class Array { 11 friend ostream &operator<<( ostream &, const Array & ); 12public: 13 Array( int = 10 ); // default/conversion constructor 14 ~Array(); // destructor 15private: 16 int size; // size of the array 17 int *ptr; // pointer to first element of array 18}; 19 20#endif 21// Fig 21.10: array2.cpp 22// Member function definitions for class Array 23#include 24 25using std::cout; 26using std::ostream; 27 28#include 29#include "array2.h" 30

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Function definitions 31// Default constructor for class Array (default size 10) 32Array::Array( int arraySize ) 33{ 34 size = ( arraySize > 0 ? arraySize : 10 ); 35 cout << "Array constructor called for " 36 << size << " elements\n"; ptr = new int[ size ]; // create space for array 39 assert( ptr != 0 ); // terminate if memory not allocated for ( int i = 0; i < size; i++ ) 42 ptr[ i ] = 0; // initialize array 43} 44 45// Destructor for class Array 46Array::~Array() { delete [] ptr; } 47 48// Overloaded output operator for class Array 49ostream &operator<<( ostream &output, const Array &a ) 50{ 51 int i; for ( i = 0; i < a.size; i++ ) 54 output << a.ptr[ i ] << ' ' ; return output; // enables cout << x << y; 57}

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Load header 1.1 Initialize object 2. Print object 3. Function definition 58// Fig 21.10: fig21_10.cpp 59// Driver for simple class Array 60#include 61 62using std::cout; 63 64#include "array2.h" 65 66void outputArray( const Array & ); 67 68int main() 69{ 70 Array integers1( 7 ); outputArray( integers1 ); // output Array integers outputArray( 15 ); // convert 15 to an Array and output return 0; 77} 78 79void outputArray( const Array &arrayToOutput ) 80{ 81 cout << "The array received contains:\n" 82 << arrayToOutput << "\n\n"; 83} outputArray needs a parameter of type const Array &, so 15 is converted into an Array by the conversion constructor.

 2000 Deitel & Associates, Inc. All rights reserved. Outline Program Output Array constructor called for 7 elements The array received contains: Array constructor called for 15 elements The array received contains:

 2000 Deitel & Associates, Inc. All rights reserved mutable Class Members mutable data member –always modifiable, even in a const function or object –permanently allows a const data member to be modified const_cast : –used every time a const data member must be modified –reduces risk of accidentally modifying a const variable

 2000 Deitel & Associates, Inc. All rights reserved Pointers to Class Members (.* and ->* ) pointers to class members are different from normal pointers use.* and ->* instead of. and -> when accessing class members (functions and data)

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Class definition 1.1 Function prototypes 1.2 Initialize object 2. Function calls 1// Fig fig21_13.cpp 2// Demonstrating operators.* and ->* 3#include 4 5using std::cout; 6using std::endl; 7 8class Test { 9public: 10 void function() { cout << "function\n"; } 11 int value; 12}; 13 14void arrowStar( Test * ); 15void dotStar( Test * ); 16 17int main() 18{ 19 Test t; t.value = 8; 22 arrowStar( &t ); 23 dotStar( &t ); 24 return 0; 25}

 2000 Deitel & Associates, Inc. All rights reserved. Outline 3. Function definitions Program Output 26 27void arrowStar( Test *tPtr ) 28{ 29 void ( Test::*memPtr )() = &Test::function; 30 ( tPtr->*memPtr )(); // invoke function indirectly 31} 32 33void dotStar( Test *tPtr ) 34{ 35 int Test::*vPtr = &Test::value; 36 cout << ( *tPtr ).*vPtr << endl; // access value 37} function 8 arrowStar declares and initializes memPtr to point to a function in Test that takes no parameters and returns no value. &Test::function to get the offset into the class for member function function. Without Test::, memPtr is a standard pointer. dotStar declares and initializes vPtr to point to value. The.* operator is then used to access the member to which vPtr points.

 2000 Deitel & Associates, Inc. All rights reserved Multiple Inheritance and virtual Base Classes Ambiguities can result with multiple inheritance iostream could have duplicate subobjects (data from ios inherited into ostream and istream ). –Upcasting an iostream pointer to an ios object creates a problem. Two ios subobjects could exist: which one is used? –Ambiguous, results in syntax error (of course, iostream does not actually have this problem) ios ostream istream iostream

 2000 Deitel & Associates, Inc. All rights reserved Multiple Inheritance and virtual Base Classes (II) Use virtual base class inheritance –only one subobject of the base is inherited into the multiply derived class. Second Derived Class Base Class First Derived Class Multiply-Derived Class virtual inheritance

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1// Fig : fig21_15.cpp 2// Attempting to polymorphically call a function 3// multiply inherited from two base classes. 4#include 5 6using std::cout; 7using std::endl; 8 9class Base { 10public: 11 virtual void print() const = 0; // pure virtual 12}; 13 14class DerivedOne : public Base { 15public: 16 // override print function 17 void print() const { cout << "DerivedOne\n"; } 18}; 19 20class DerivedTwo : public Base { 21public: 22 // override print function 23 void print() const { cout << "DerivedTwo\n"; } 24}; 25 26class Multiple : public DerivedOne, public DerivedTwo { 27public: 28 // qualify which version of function print 29 void print() const { DerivedTwo::print(); } 30}; Define base class 1.1 Define non- virtual derived classes 1.2 Define multiply derived class

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.3 Create class objects 1.4 Create an array of base class pointers. 2. Initialize array elements Program Output 32int main() 33{ 34 Multiple both; // instantiate Multiple object 35 DerivedOne one; // instantiate DerivedOne object 36 DerivedTwo two; // instantiate DerivedTwo object Base *array[ 3 ]; 39 array[ 0 ] = &both; // ERROR--ambiguous 40 array[ 1 ] = &one; 41 array[ 2 ] = &two; // polymorphically invoke print 44 for ( int k = 0; k < 3; k++ ) 45 array[ k ] -> print(); return 0; 48} Compiling... Fig21_15.cpp fig21_15.cpp(39) : error C2594: '=' : ambiguous conversions from 'class Multiple *' to 'class Base *' The address of both is implicitly converted to a base class pointer. This is ambiguous because class Multiple has duplicate subobjects inherited from Base. If DerivedOne and DerivedTwo had used virtual inheritance, no errors would result and the objects will be printed.