Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC.

Similar documents
Short Notes of CS201

CS201 - Introduction to Programming Glossary By

Tokens, Expressions and Control Structures

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

INTRODUCTION 1 AND REVIEW

Pointers, Dynamic Data, and Reference Types

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

W3101: Programming Languages C++ Ramana Isukapalli

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC.

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

Instantiation of Template class

Ch. 12: Operator Overloading

Variables. Data Types.

LEXICAL 2 CONVENTIONS

CS201- Introduction to Programming Current Quizzes

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

IS0020 Program Design and Software Tools Midterm, Fall, 2004

And Even More and More C++ Fundamentals of Computer Science

COEN244: Class & function templates

CS201 Some Important Definitions

A Fast Review of C Essentials Part I

Introduction to C++ Systems Programming

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Object Oriented Design

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

KLiC C++ Programming. (KLiC Certificate in C++ Programming)

Introduction to C++ Friends, Nesting, Static Members, and Templates Topic #7

CS201 Latest Solved MCQs

SFU CMPT Topic: Class Templates


CS3157: Advanced Programming. Outline

COMP322 - Introduction to C++


KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming


STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Example : class Student { int rollno; float marks; public: student( ) //Constructor { rollno=0; marks=0.0; } //other public members };

C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

CS304 Object Oriented Programming Final Term

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

More C++ : Vectors, Classes, Inheritance, Templates

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

Introduction to C++ with content from

Ch02. True/False Indicate whether the statement is true or false.

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Fundamental Concepts and Definitions

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Computer System and programming in C

ADTs & Classes. An introduction

Programming 2. Object Oriented Programming. Daniel POP

Object Oriented Programming. Solved MCQs - Part 2

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

l Operators such as =, +, <, can be defined to l The function names are operator followed by the l Otherwise they are like normal member functions:

2 ADT Programming User-defined abstract data types

Input And Output of C++

C++ Important Questions with Answers

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

QUIZ. What is wrong with this code that uses default arguments?

MaanavaN.Com CS1203 OBJECT ORIENTED PROGRAMMING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

Chapter 15 - C++ As A "Better C"

Exam 3 Chapters 7 & 9

+2 Volume II OBJECT TECHNOLOGY OBJECTIVE QUESTIONS R.Sreenivasan SanThome HSS, Chennai-4. Chapter -1

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

CS 247: Software Engineering Principles. ADT Design

III. Classes (Chap. 3)

CHAPTER 4 FUNCTIONS. 4.1 Introduction

C++ Programming: Polymorphism

Introduction to Programming Using Java (98-388)

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

The New C Standard (Excerpted material)

Cpt S 122 Data Structures. Templates

public : int min, hour ; T( ) //here constructor is defined inside the class definition, as line function. { sec = min = hour = 0 ; }

Constants, References

Introduction Of Classes ( OOPS )

Friends and Overloaded Operators

Computer Systems Principles. C Pointers

CSI33 Data Structures

Lecture 18 Tao Wang 1

Assignment 1: grid. Due November 20, 11:59 PM Introduction

Friends and Overloaded Operators

Object-Oriented Principles and Practice / C++

CS 162, Lecture 25: Exam II Review. 30 May 2018

C++ (Non for C Programmer) (BT307) 40 Hours

History C++ Design Goals. How successful? Significant constraints. Overview of C++

Inheritance, and Polymorphism.

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CPSC 427: Object-Oriented Programming

A Taxonomy of Expression Value Categories

CSCI-1200 Data Structures Fall 2017 Lecture 25 C++ Inheritance and Polymorphism

Transcription:

hapter 1 INTRODUTION SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN.

++ Programming: Advanced Objectives You will learn: Anonymous class types. Nested class declarations. Incomplete declarations. Pointers to class members and member objects. onversion of pointers to classes. Friend functions and declarations. Templates. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page i

++ Programming: Advanced 1 Anonymous lass Types An anonymous class is declared without an identifier. This is useful when a class name is replaced with a typedef name. typedef struct unsigned x; unsigned y; } POINT; In some code, the use of typedef in conjunction with anonymous structures is prevalent. Anonymous classes are also useful for referencing to a class member to appear as though it were not contained in a separate class. struct PTValue POINT ptloc; union int ivalue; long lvalue; PTValue ptv; ivalue can be accessed using the object member-selection operator (.) as follows: int i = ptv.ivalue; Anonymous classes have the following restrictions: annot have a constructor or destructor. annot be passed as arguments to functions unless type checking is defeated using ellipses. annot be returned as return values from functions. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 1

++ Programming: Advanced A class can be declared within the scope of another class. 2 Nested lass Declarations Nested classes are considered to be within the scope of the enclosing class and are available for use within that scope. In order to refer to a nested class from a scope other than its immediate enclosing scope, a fully qualified name must be used. This code declares nested classes: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class BufferedIO public: enum IOError None, Access, General // Declare nested class BufferedInput. class BufferedInput public: int read(); int good() return _inputerror == None; } private: IOError _inputerror; // Declare nested class BufferedOutput. class BufferedOutput // Member list BufferedIO::BufferedInput and BufferedIO::BufferedOutput are declared within BufferedIO. These class names are not visible outside the scope of class BufferedIO. However, an object of type BufferedIO does not contain any objects of types BufferedInput or BufferedOutput. Nested classes can directly use names, type names, names of static members, and enumerators only from the enclosing class. In order to use names of other class members, pointers, references, or object names must be used. In the BufferedIO example, the enumeration IOError can be accessed directly by member functions in the nested classes, BufferedIO::BufferedInput or BufferedIO::BufferedOutput, as shown in function good. Nested classes declare only types within class scope. They do not cause contained objects of the nested class to be created. The preceding example declared two nested classes; but did not declare any objects of these class types. Nesting a class within another class does not give special access privileges to member functions of the nested class. Similarly, member functions of the enclosing class have no special access to members of the nested class. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 2

++ Programming: Advanced 3 Incomplete Declarations An incomplete type is a type that describes an identifier, but lacks information needed to determine the size of the identifier. An "incomplete type" can be: A structure type whose members have not yet been specified. A union type whose members have not yet been specified. An array type whose dimension has not yet been specified. The void type is an incomplete type that cannot be completed. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 3

++ Programming: Advanced 3.1 Examples for reating and ompleting the Incomplete Type In order to complete an incomplete type, specify the missing information. The following examples demonstrate how to create and complete the incomplete types. In order to create an incomplete structure type, declare a structure type without specifying its members. The ps pointer points to an incomplete structure type called student. struct student *ps; In order to complete an incomplete structure type, declare the same structure type later in the same scope with its members specified. struct student int num; } /* student structure now completed */ In order to create an incomplete array type, declare an array type without specifying its repetition count. char a[]; /* a has incomplete type */ In order to complete an incomplete array type, declare the same name later in the same scope with its repetition count specified. char a[25]; /* a now has complete type */ SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 4

++ Programming: Advanced 4 Pointers to lass Members and Member Objects The use of pointers to class members enhances the type safety of the ++ language. Three new operators and constructs are used with pointers to members. Operator or onstruct Syntax Use ::* type::*ptr-name Declaration of pointer to member. The type specifies the class name, and ptr-name specifies the name of the pointer to member. Pointers to members can be initialized. MyType::*pMyType = &MyType::i;.* obj-name.*ptr-name Dereference a pointer to a member using an object or object reference. int j = Object.*pMyType; ->* obj-ptr->*ptr-name Dereference a pointer to a member using a pointer to an object. int j = pobject->*pmytype; SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 5

++ Programming: Advanced This code defines a class Testlass and the derived type pvalue, which points to the member ivar1: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 #include <iostream.h> // Define class Testlass. class Testlass public: int ivar1; Show() cout << ivar1 << "\n"; } // Define a derived type pvalue that points to ivar1 members of // objects of type Testlass. int Testlass::*pValue = &Testlass::iVar1; void main() Testlass Testlass; // Define an object of type Testlass. Testlass *ptestlass = &Testlass; // Define a pointer to that object. int i; Testlass.*pValue = 7777; // Assign to Testlass::iVar1 using.* operator. Testlass.Show(); i = ptestlass->*pvalue; // Dereference a pointer // using ->* operator. cout << i << "\n"; } The pointer to member pvalue is a new type derived from class Testlass. It is more strongly typed than a "plain" pointer to int because it points only to int members of class Aclass. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 6

++ Programming: Advanced Pointers to static members are plain pointers rather than pointers to class members. class StaticMemlass public: static int StaticMember; int StaticMemlass::StaticMember = 0; int *ptrstaticmember = &StaticMemlass::StaticMember; SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 7

++ Programming: Advanced The type of the pointer is "pointer to int," not "pointer to StaticMemlass::int." Pointers to members can refer to member functions as well as member data. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // Declare a base class, A, with a virtual function, Identify. // (Note that in this context, struct is the same as class.) struct A virtual void Identify() = 0; // No definition for class A. // Declare a pointer to the Identify member function. void (A::*ptrIdentify)() = &A::Identify; // Declare class B derived from class A. struct B : public A void Identify(); // Define Identify functions for classe B void B::Identify() printf( "Identification is B::Identify\n" ); } void main() B BObject; // Declare objects of type B A *ptra; // Declare pointer to type A. ptra = &BObject; // Make ptra point to an object of type B. (ptra->*ptridentify)(); // all Identify function through pointer // to member ptridentify. } The output from this program is: Identification is B::Identify The function is called through a pointer to type A. However, because the function is a virtual function, the correct function for the object to which ptra refers is called. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 8

++ Programming: Advanced 4.1 Initializing Pointers to Member Objects A pointer to a const object can be initialized with a pointer to an object that is not const, but not vice versa. The following initialization is allowed: Window StandardWindow; const Window* pstandardwindow( &StandardWindow ); The pointer pstandardwindow is declared as a pointer to a const object. Although StandardWindow is not declared as const, the declaration is acceptable because it does not allow an object not declared as const access to a const object. The reverse of this is: const Window StandardWindow; Window* pstandardwindow( &StandardWindow ); The preceding code explicitly declares StandardWindow as a const object. Initializing the nonconstant pointer pstandardwindow with the address of StandardWindow generates an error because it allows access to the const object through the pointer. This serves to allow for the removal of the const attribute from the object. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 9

++ Programming: Advanced 5 onversion of Pointers to lasses There are two cases in which a pointer to a class can be converted to a pointer to a base class. ase 1: The first case is when the specified base class is accessible and the conversion is unambiguous. Whether a base class is accessible depends on the kind of inheritance used in derivation. onsider the following inheritance: This table lists the base-class accessibility for the situation illustrated in the figure. Type of Function Derivation onversion from B* to A* Legal? External function (not class-scoped) B member function (in B scope) member function (in scope) Private Protected Public Private Protected Public Private Protected Public No No Yes Yes Yes Yes No Yes Yes SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 10

++ Programming: Advanced ase 2: The second case in which a pointer to a class can be converted to a pointer to a base class is when an explicit type conversion is being used. The result of such a conversion is a pointer to the "subobject," the portion of the object that is completely described by the base class. The following code defines two classes, A and B, where B is derived from A. It then defines bobject, an object of type B, and two pointers (pa and pb) that point to the object. class A public: int Aomponent; int AMemberFunc(); class B : public A public: int Bomponent; int BMemberFunc(); B bobject; A *pa = &bobject; B *pb = &bobject; pa->amemberfunc(); pb->amemberfunc(); pa->bmemberfunc(); // OK in class A // OK: inherited from class A // Error: not in class A The pointer pa is of type A *, which can be interpreted as meaning "pointer to an object of type A." Members of bobject (such as Bomponent and BMemberFunc) are unique to type B and are therefore inaccessible through pa. The pa pointer allows access only to those characteristics (member functions and data) of the object that are defined in class A. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 11

++ Programming: Advanced 6 Friend Functions In some circumstances, it is more convenient to grant member-level access to functions that are not members of a class or to all functions in a separate class. With the friend keyword, programmers can designate: the specific functions. OR the classes whose functions can access not only public members but also protected and private members. Friend functions are not considered class members; they are normal external functions that are given special access privileges. Friends are not in the class's scope, and they are not called using the member-selection operators (. and - >) unless they are members of another class. This code illustrates a Point class and an overloaded operator, operator+. It primarily illustrates friends, not overloaded operators. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 #include <iostream.h> // Declare class Point. class Point public: // onstructors Point() _x = _y = 0; } Point( unsigned x, unsigned y ) _x = x; _y = y; } // Accessors unsigned x() return _x; } unsigned y() return _y; } void Print() cout << "Point(" << _x << ", " << _y << ")" << endl; } // Friend function declarations friend Point operator+( Point& pt, int noffset ); friend Point operator+( int noffset, Point& pt ); private: unsigned _x; unsigned _y; // Friend-function definitions // // Handle Point + int expression. Point operator+( Point& pt, int noffset ) SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 12

++ Programming: Advanced 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 Point pttemp = pt; // hange private members _x and _y directly. pttemp._x += noffset; pttemp._y += noffset; return pttemp; } // Handle int + Point expression. Point operator+( int noffset, Point& pt ) Point pttemp = pt; // hange private members _x and _y directly. pttemp._x += noffset; pttemp._y += noffset; return pttemp; } // Test overloaded operator. void main() Point pt( 10, 20 ); pt.print(); pt = pt + 3; // Point + int pt.print(); pt = 3 + pt; // int + Point pt.print(); } When the expression pt + 3 is encountered in the main function, the compiler determines whether an appropriate user-defined operator+ exists. In this case, the function operator+( Point pt, int noffset ) matches the operands, and a call to the function is issued. In the second case (the expression 3 + pt), the function operator+( Point pt, int noffset ) matches the supplied operands. Therefore, supplying these two forms of operator+ preserves the commutative properties of the + operator. A user-defined operator+ can be written as a member function, but it takes only one explicit argument: the value to be added to the object. As a result, the commutative properties of addition cannot be correctly implemented with member functions; they must use friend functions instead. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 13

++ Programming: Advanced 7 Friend Declarations If a friend function is declared that was not previously declared, that function is exported to the enclosing nonclass scope. Functions declared in a friend declaration are treated as if they had been declared using the extern keyword. Although functions with global scope can be declared as friends prior to their prototypes, member functions cannot be declared as friends before the appearance of their complete class declaration. This code shows why the fails occurs: class ForwardDeclared; class HasFriends friend int ForwardDeclared::IsAFriend(); // lass name is known. // Error. The preceding code enters the class name ForwardDeclared into scope, but the complete declaration -- specifically, the portion that declares the function IsAFriend -- is not known. Therefore, the friend declaration in class HasFriends generates an error. In order to declare two classes that are friends of one another, the entire second class must be specified as a friend of the first class. The reason for this restriction is that the compiler has sufficient information to declare individual friend functions only at the point where the second class is declared. Although the entire second class must be a friend to the first class, it is possible to select which functions in the first class will be friends of the second class. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 14

++ Programming: Advanced 8 Templates Templates are a mechanism for generating functions and classes based on type parameters. They are sometimes called "parameterized types. The utilization of templates makes it possible to design a single class that operates on data of many types, instead of having to create a separate class for each type. In order to create a type-safe function that returns the minimum of two parameters without using templates, it will be necessary to write a set of overloaded functions such as: // min for ints int min( int a, int b ) return ( a < b )? a : b; // min for longs long min( long a, long b ) return ( a < b )? a : b; // min for chars char min( char a, char b ) return ( a < b )? a : b; //etc... By using templates, this duplication can be reduced to a single templated function: template <class T> T min( T a, T b ) return ( a < b )? a : b; Templates can significantly reduce source code size and increase code flexibility without reducing type safety. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 15

++ Programming: Advanced 8.1 Function Templates lass templates define a family of related classes that are based on the parameters passed to the class upon instantiation. Function templates are similar to class templates, but define a family of functions. The template declaration specifies a set of parameterized classes or functions. Syntax: template-declaration: template < template-argument-list > declaration template-argument-list: template-argument template-argument-list, template-argument template-argument: type-argument argument-declaration type-argument: class identifier The declaration declares a function or a class. With function templates, each template-argument must appear at least once in the template-argument-list of the function being declared. The template-argument-list is a list of arguments used by the template function that specifies which parts of the following code will vary. template< class T, int i > class MyStack... In this case the template can receive a type (class T) and a constant parameter (int i). The template will use type T and the constant integer i upon construction. Within the body of the MyStack declaration, it will be necessary to refer to a T identifier. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 16

++ Programming: Advanced A template declaration itself does not generate code; it specifies a family of classes or functions, one or more of which will be generated when referenced by other code. Template declarations have global scope. This function template swaps two items: template< class T > void MySwap( T& a, T& b ) T c; c = a; a = b; b = c; } Although this function could be performed by a nontemplated function, using void printers, the template version is type-safe. onsider the following calls: int j = 10; int k = 18; String Hello = "Hello, Windows!"; MySwap( j, k ); //OK MySwap( j, Hello ); //error The second MySwap call triggers a compile-time error, since the compile cannot generate a MySwap function with parameters of different types. If void pointers were used, both function calls would compile correctly, but the function would not work properly at run time. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 17

++ Programming: Advanced 8.2 lass Templates Templates can be used for creating a family of classes that operate on a type. template <class T, int i> class Templass public: Templass( void ); ~Templass( void ); int MemberSet( T a, int b ); private: T Tarray[i]; int arraysize; The templated class uses two parameters, a type T and an int i. The T parameter can be passed any type, including structures and classes. The i parameter has to be passed an integer constant. Since i is a constant defined at compile time, a member array of size i can be defined using a standard automatic array declaration. Unlike function templates, all template parameters do not have to be used in the definition of a templated class. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (++ Prg: Adv - 9.7) h 1: Page 18