Você está na página 1de 165

C++

By: Rajmal Menariya

v1.1

MODULE - 1
INTRODUCTION TO C++

v1.1

OBJECTIVES
To learn about : What is C++. Application of C++ Program development and execution A simple C++ program

v1.1

WHAT IS C++
C++ is an object-oriented language. Initially named C with classes, C++ was developed by Bjarne Stroustrup at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early eighties. C++ is an extension of C with a major addition of the class construct feature of Simula67. C++ is a superset of C. The three most important facilities that C++ adds on to C are classes, function overloading and operator overloading. The features enable us to create abstract data types, inherit properties from existing data types and support polymorphism, thus making C++ a truly object oriented language.

v1.1

APPLICATIONS OF C++
C++ is a versatile language for handling large programs. It is suitable for virtually any programming task including development of editors, compilers, databases, communication systems and any complex real-life systems. Since C++ allows us to create hierarchy-related objects, we can build special object-oriented libraries, which can be used later by many programmers. C++ programs are easily maintainable and expandable.

v1.1

PROGRAM DEVELOPMENT AND EXECUTION


Develop the program (source code). Select the suitable file name under which youll like to store the program. This is the source code file. Compile the source code. The file containing the translated code is called object code file. If errors debug them. Link the object code with other library code that is required for execution. The resulting code is executable code. If errors debug them. Run the executable code. If errors debug them.

v1.1

A SIMPLE C++ PROGRAM


#include <iostream.h> // Header file main( ) { cout << Hello World; // C++ statement } // End of example. The C++ program is a collection of functions. The example contains only one function main( ). The usual execution begins with main( ). C++ is a free form language.

v1.1

INVOKING AND USING TURBO C++


Naming your program Saving your program

Compiling and linking


Running your program

v1.1

QUERIES

v1.1

MODULE - 2

C++ PROGRAMMING BASICS

10

v1.1

OBJECTIVES
To learn about : Tokens Basic Program Construction Output using cout Comments Variables Constants Expressions Operators
v1.1

11

TOKENS
The smallest individual unit in a program is known as token. C++ has the following tokens:
Keywords. Identifiers. Constants. Strings. Operators.

A C++ program is written using these tokens, whitespaces and the syntax of the language.

12

v1.1

FUNCTIONS
Typical functions are called, or invoked, during the course of your program. A program is executed line by line in the order it appears in your source code, until a function is reached. Then the program branches off to execute the function. When the function finishes, it returns control to the line of code immediately following the call to the function. Functions either return a value or they return void, meaning they return nothing. The function main ( )

13

v1.1

STATEMENTS
In C++ a statement controls the sequence of execution, evaluates an expression, or does nothing (the null statement). All C++ statements end with a semicolon, even the null statement, which is just the semicolon and nothing else. Any place you can put a single statement, you can put a compound statement, also called a block. A block begins with an opening brace ({) and ends with a closing brace (}). Although every statement in the block must end with a semicolon, the block itself does not end with a semicolon.

14

v1.1

WHITE SPACES
Whitespace (tabs, spaces, and newlines) is generally ignored in statements. The assignment statement x = a + b; could be written as x =a + b; Whitespace can be used to make your programs more readable and easier to maintain, or it can be used to create horrific and indecipherable code.

15

v1.1

OUTPUT USING cout

To print a value to the screen, write the word cout, followed by the insertion operator (<<), which you create by typing the less-than character (<) twice. Even though this is two characters, C++ treats it as one.
Follow the insertion character with your data.

16

v1.1

COMMENTS
Comments are simply text that is ignored by the compiler, but that may inform the reader of what you are doing at any particular point in your program. C++ comments come in two flavors: the double-slash (//) comment, and the slash-star (/*) comment. The double-slash comment, which tells the compiler to ignore everything that follows this comment, until the end of the line.The slash-star comment mark tells the compiler to ignore everything that follows until it finds a star-slash (*/) comment mark.

17

v1.1

typedef
It can become tedious, repetitious, and, most important, error-prone to keep writing unsigned short int. C++ enables you to create an alias for this phrase by using the keyword typedef, which stands for type definition.In effect, you are creating a synonym, and it is important to distinguish this from creating a new type. typedef is used by writing the keyword typedef, followed by the existing type and then the new name. For example typedef unsigned short int USHORT creates the new name USHORT that you can use anywhere you might have written unsigned short int.

18

v1.1

VARIABLES
In C++ a variable is a place to store information. A variable is a location in your computer's memory in which you can store a value and from which you can later retrieve that value. When you define a variable in C++, you must tell the compiler what kind of variable it is: an integer, a character, and so forth. This information tells the compiler how much room to set aside and what kind of value you want to store in your variable.

19

v1.1

FUNDAMENTAL VARIABLE TYPES


Type unsigned short int short int unsigned long int long int int (16 bit) int (32 bit) unsigned int (16 bit) unsigned int (32 bit) char float double Size 2 bytes 2 bytes 4 bytes 4 bytes 2 bytes 4 bytes 2 bytes 2 bytes 1 byte 4 bytes 8 bytes
v1.1

Range

20

DEFINING VARIABLES
You create or define a variable by stating its type, followed by one or more spaces, followed by the variable name and a semicolon. The variable name can be virtually any combination of letters, but cannot contain spaces. Legal variable names include x, J23qrsnf, and myAge. Good variable names tell you what the variables are for; using good names makes it easier to understand the flow of your program. The following statement defines an integer variable called myAge: int myAge;

21

v1.1

KEYWORDS
Some words are reserved by C++, and you may not use them as variable names. These are keywords used by the compiler to control your program. Keywords include if, while, for, and main. Keywords in C++ are: auto break case catch char class const continue default delete do double else enum extern float for friend goto if int long mutable new operator private protected public register return short signed sizeof static struct switch template this throw typedef union unsigned virtual void volatile while

22

v1.1

CONSTANTS
Like variables, constants are data storage locations. Unlike variables, and as the name implies, constants don't change. You must initialize a constant when you create it, and you cannot assign a new value later. A literal constant is a value typed directly into your program wherever it is needed. e.g. int myAge = 39; A symbolic constant is a constant that is represented by a name, just as a variable is represented. If your program has one integer variable named students and another named classes, you could compute how many students you have, given a known number of classes, if you knew there were 15 students per class: e.g. students = classes * 15;

23

v1.1

EXPRESSIONS
Anything that evaluates to a value is an expression in C++. An expression is said to return a value. Thus, 3+2; returns the value 5 and so is an expression. All expressions are statements. 3.2 // returns the value 3.2, expression

The expression x = a + b; not only adds a and b and assigns the result to x, but returns the value of that assignment (the value of x) as well. Thus, this statement is also an expression.

24

v1.1

OPERATORS
An operator is a symbol that causes the compiler to take an action. Operators act on operands, and in C++ all operands are expressions. In C++ there are several different categories of operators. Categories of operators are:
Assignment operators. Logical operators. Relational operators. Conditional(Ternary Operator)

25

v1.1

NEW OPERATORS
:: ::* ->* .* new delete endl setw Scope Resolution operator. Pointer-to-member declarator. Pointer to-member operator. Pointer to member operator. Memory allocation operator. Memory release operator. Line feed operator. Field width operator.

26

v1.1

QUERIES

27

v1.1

MODULE - 3

LOOPS AND DECISIONS

28

v1.1

OBJECTIVES
To learn about : Loops Decisions

29

v1.1

LOOPS
Loops cause a section of your program to be repeated a certain number of times. The repetition continues while a condition is true. When the condition becomes false the loop ends and the control passes to the statement following the loop. Various kinds of loops are
for loop while loop do-while loop

30

v1.1

for LOOP
A for loop performs initialization before the first iteration. Then it performs condition testing and, at the end of each iteration, some form of stepping. The form of the for loop is for(initialization ; expression; step) Statement Any of initialization, expression or step may be empty. The initialization code begins once at beginning. The expression is tested before each iteration. At the end of each iteration the step executes.

31

v1.1

while LOOP

The form of while loop is


while(expression) Statement The expression is evaluated once at the beginning of the loop and again before each further iteration of the statement.

32

v1.1

do-while LOOP
The form of do-while is do Statement while(expression) The do-while is different from while because the statement always executes at least once, even if the expression evaluates to false the first time. In a simple while statement if the conditional is false the first time the statement never executes.

33

v1.1

DECISIONS: if-else
The if-else statement executes in two forms if (expression) Statement if (expression) Statement else Statement The expression evaluates to either true or false. The statement means either a simple statement terminated by a semi colon or a compound statement, which is a group of simple statements enclosed in braces. The statement can be another if statement.

34

v1.1

switch STATEMENT
A switch statement selects from among pieces of code based on the value of an integral expression. Its form is switch (selector) { case integral-value1 : statement; break; () default : statement; break; } Selector is an expression that produces an integral value. The switch compares the result of selector to each integral-value. If it finds a match the corresponding statement execute. If no match is found the default statement executes.

35

v1.1

OTHER CONTROL STATEMENTS

break
continue goto

36

v1.1

QUERIES

37

v1.1

MODULE - 4

STRUCTURES AND UNIONS

38

v1.1

OBJECTIVES
To learn about : Structures Unions

39

v1.1

STRUCTURES
A structure is a collection of simple variables. They provide a method of packing data of different types. A structure is a convenient tool for handling a group of logically related data items. It is a user-defined data type with a template that serves to define its data properties. It has the following form: struct [tag] { member-list } [declarators]; [struct] tag declarators; The struct keyword defines a structure type and/or a variable of a structure type.

40

v1.1

LIMITATION OF C STRUCTURE
struct complex { float x; float y; }; struct complex c1,c2,c3; The complex numbers can be easily assigned values using the dot operator but we cannot attempt arithmetic operations on them c3 = c1 + c2; is illegal in C. Also, structures in donot permit data hiding. Structure members can be easily accessed anywhere by the functions.

41

v1.1

EXTENSIONS TO STRUCTURES
In C++ a structure can have both variables and functions as members. It can also declare some of its members as private so that they may not be accessed directly by external functions. In C++ structure names are stand-alone and can be used like any other type names. The keyword struct can be omitted in the declaration of structure variables. student st1; // This is an error in C.

42

v1.1

STRUCTURES AND CLASSES


The members of a struct are public by default, while in a class they default to private. struct and class are otherwise functionally equivalent.

43

v1.1

UNION
A union is a user-defined data type that can hold values of different types at different times. It is similar to a structure except that all of its members start at the same location in memory. A union variable can contain only one of its members at a time. The size of the union is at least the size of the largest member. It has the form: union [tag] { member-list } [declarators]; [union] tag declarators; The union keyword declares a union type and/or a variable of a union type.

44

v1.1

QUERIES

45

v1.1

MODULE - 5

FUNCTIONS IN C++

46

v1.1

OBJECTIVES
To learn about : Functions

47

v1.1

FUNCTIONS
A function groups a number of program statements into a unit and gives it a name. The unit can then be invoked from other parts of the program. The most important reason to use functions is to aid in the conceptual organization of the program. Another reason to use functions is to reduce the program size. This is because the functions code is stored in only one place in memory, even though the function is executed many times in the program.

48

v1.1

FUNCTION DECLARATION AND DEFINITION


Just as one cant use a variable without declaring it first, one cant use a function without telling the compiler what it is. The most common approach to declare a function is at the beginning of the program. Function declarations are also called prototypes. The function itself is referred to as the function definition. One can eliminate the function declaration if the function definition appears in the listing before the first call to the function.

49

v1.1

LIBRARY FUNCTIONS
ch = getche(); in our programs. Where are the declarations and definitions for these functions? The declarations of such functions are in the header file specified in the beginning of the program (conio.h for getche() ). The definition (compiled into executable code) is in a library file, CS.Lib (or a similar file). When we use a library function, we dont need to write the declaration or definition.

50

v1.1

PASSING AND RETURNING VALUES


Passing by value. Passing by reference. Passing structures by reference. Returning values from a function. Default arguments.

51

v1.1

INLINE FUNCTIONS
Functions save memory space because all the calls to the functions cause the same code to be executed, the function body need not be duplicated in the memory. When the compiler sees a function call, it generates a jump the function. At the end of the function, it jumps back to the instruction following the function call. This may save memory space, but it takes some extra time. To save execution time in short functions, you may elect to put the code in the function body directly inline with the code in the calling program. Thus each time a functions called the code is inserted into the calling program instead of making different jumps to the function each time.

52

v1.1

QUERIES

53

v1.1

MODULE - 6

CLASSES AND OBJECTS

54

v1.1

OBJECTIVES
To learn about : Classes Objects Friend functions

55

v1.1

CLASSES
A class is a way to bind data and its associated functions together. It allows the data (and functions) to be hidden, if necessary from external use. When defining a class we are creating abstract data type that can be treated like any other built-in data type. A class specification has two parts:
Class declaration Class function definitions

The class declaration describes the type and scope of its members. The class function definitions describe how the class functions are implemented.

56

v1.1

class class_name { private: variable declaration; function declaration; public: variable declaration; function declaration; }; The class declaration is very similar to that of struct declaration. The keyword class specifies that what follows is an abstract data type class_name. The body of the class is enclosed

57

v1.1

CREATING OBJECTS
Once a class has been declared, we can create variables of that type by using the class name like any other built-in type variables. Item x; // memory for x is created. In C++ class variables are known as objects. class Item { } a, b, c;

58

v1.1

FRIEND FUNCTIONS
There could be situations where two classes would want to share a function. In such situations, C++ allows the common function to be made friendly with both the classes thereby allowing the function to have access to the private data of these two classes. Such a function need not be the member of any of these classes. class ABC { public: friend void xyz(void); //declaration };

59

v1.1

CHARACTERISTICS OF A FRIEND FUNCTION


It is not in the scope of the class to which it has been declared as a friend. Since it is not in the scope of the class, it cannot be called using the object of that class. Unlike member functions it cannot access the member names directly and has to use an object name and dot membership operator with each member name. It can be declared in either public or private part of the class, without effecting its meaning. Usually, it has the objects as arguments.

60

v1.1

POINTERS TO MEMBERS
It is possible to take the address of a member of a class and assign it to a pointer. The address of a member can be obtained by applying the & to a fully qualified class member name. A class member pointer can be declared using the operator ::* with the class name. The dereferencing operator ->* is used to access a member when we use pointer to both the member and the object. The dereferencing operator .* is used when object itself is used with member pointer.

61

v1.1

QUERIES

62

v1.1

MODULE - 7

CONSTRUCTORS AND DESTRUCTORS

63

v1.1

OBJECTIVES
To learn about : The need of constructors and destructors. Constructors. Destructors.

64

v1.1

WHAT IS THE NEED ?


One of the aims of C++ is to create user-defined data types such as class, which behave very similar to built-in data types. This means that we should be able to initialize a class type variable much the same way as initialization of ordinary variable.

Also, when the variable in the built in type goes out of scope it should be destroyed.

65

v1.1

CONSTRUCTORS
C++ provides a special member function called the constructor, which enables an object to initialize itself when it is created. This is known as automatic initialization of objects. It is special because its name is same as the class name. The constructor is invoked whenever an object of is associated class is created. It is called constructor because it constructs the values of data members of its class.

66

v1.1

class Integer { int m,n; public: Integer :: Integer (void) // Constructor defined { m=0; n=0; } }; There is no need to write any statement to invoke the constructor function, it is called itself. A constructor that accepts no parameters is called default constructor. If no constructor is defined the compiler supplies a default constructor.

67

v1.1

SPECIAL CHARACTERISTICS
They should be declared in the public section. They are invoked when the objects are created. They don't have return types and hence don't return anything. They cannot be inherited, though a derived class can call the base class constructor. They can have default arguments. Constructors cannot be virtual. We cannot refer to their address. An object with a constructor or destructor cannot be used as a member of a union. They make implicit calls to the operators new and delete when memory allocation is required.

68

v1.1

PARAMETRIZED CONSTRUCTORS
It is sometimes necessary to initialize various data elements of different objects with different values when they are created. C++ permits us to achieve this objective by passing arguments to the constructor function when they are created. The constructors that can take arguments are called parameterized constructors. We must pass the initial values as arguments to the constructor when an object is declared. By calling the constructor explicitly Integer int 1 = Integer (0,100); // explicit call By calling the constructor implicitly Integer int 1(0,100); // implicit call

69

v1.1

COPY CONSTRUCTOR
A copy constructor is used to declare and initialize an object from another object. Integer i2 (i1); Suppose Integer is a class, i2 would define the object and at the same time initialize it to the values of i1. This can also be done as Integer i2 = i1;

The process of invoking through the copy constructor is called copy initialization..

70

v1.1

DESTRUCTOR
A destructor as the name implies, is used to destroy the objects that have been created by a constructor. Like constructor, the destructor is a member function whose name is the same as the class name but is preceded by a tilde. ~Integer( ) {} A destructor never takes any argument nor does it return any value. It will be invoke implicitly by the compiler upon exit from the program to clean up the storage that is no longer accessible.

71

v1.1

QUERIES

72

v1.1

MODULE - 8

ARRAYS

73

v1.1

OBJECTIVES
To learn about : Array fundamentals. Array elements. Fence post errors. Initializing an array. Array of objects. Multidimensional arrays. More on arrays.

74

v1.1

ARRAY FUNDAMENTALS
An array is a collection of data storage locations, each of which holds the same type of data. Each storage location is called an element of the array. You declare an array by writing the type, followed by the array name and the subscript. The subscript is the number of elements in the array, surrounded by square brackets. For example, long LongArray[25]; declares an array of 25 long integers, named LongArray. When the compiler sees this declaration, it sets aside enough memory to hold all 25 elements. Because each long integer requires 4 bytes, this declaration sets aside 100 contiguous bytes of memory

75

v1.1

ARRAY ELEMENTS
You access each of the array elements by referring to an offset from the array name. Array elements are counted from zero. Therefore, the first array element is arrayName[0]. When you write a value to an element in an array, the compiler computes where to store the value based on the size of each element and the subscript. Suppose that you ask to write over the value at LongArray[5], which is the sixth element. The compiler multiplies the offset (5) by the size of each element--in this case, 4. It then moves that many bytes (20) from the beginning of the array and writes the new value at that location.

76

v1.1

FENCE POST ERRORS


It is so common to write to one past the end of an array that this bug has its own name. It is called a fence post error. This refers to the problem in counting how many fence posts you need for a 10-foot fence if you need one post for every foot.

Most people answer 10, but of course you need 11.This sort of "off by one" counting can be the bane of any programmer's life.

77

v1.1

INITIALIZING AN ARRAY
You can initialize a simple array of built-in types, such as integers and characters, when you first declare the array. After the array name, you put an equal sign (=) and a list of comma-separated values enclosed in braces. For example, int IntegerArray[5] = { 10, 20, 30, 40, 50 };

78

v1.1

ARRAY OF OBJECTS
Any object, whether built-in or user-defined, can be stored in an array. When you declare the array, you tell the compiler the type of object to store and the number of objects for which to allocate room. The compiler knows how much room is needed for each object based on the class declaration. The class must have a default constructor that takes no arguments so that the objects can be created when the array is defined. Accessing member data in an array of objects is a two-step process. You identify the member of the array by using the index operator ([ ]), and then you add the member operator (.) to access the particular member variable.

79

v1.1

MULTIDIMENSIONAL ARRAYS

It is possible to have arrays of more than one dimension. Each dimension is represented as a subscript in the array. Therefore, a two-dimensional array has two subscripts; a three-dimensional array has three subscripts; and so on. Arrays can have any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions. A good example of a two-dimensional array is a chess board. One dimension represents the eight rows; the other dimension represents the eight columns.

80

v1.1

MORE ON ARRAYS

Arrays and pointers. Arrays and strings. Linked list and other data structures.

81

v1.1

QUERIES

82

v1.1

MODULE - 9

OPERATOR OVERLOADING

83

v1.1

OBJECTIVES
To learn about : What is operator overloading. Defining operator overloading. Steps for operator overloading. Overloading unary and binary operators. Rules for operator overloading.

84

v1.1

WHAT IS OPERATOR OVERLOADING

C++ permits us to add to two variables of user-defined types with the same syntax that is applied to basic types. This means that C++ has the ability to provide the operators with a special meaning for a data type. The mechanism of giving such special meanings to an operator is known as operator overloading.

85

v1.1

Operator overloading provides a flexible option for the creation of new definitions for most of the C++ operators. We can overload all C++ operators except for the following
Class member access operator ( ., .* ). Scope resolution operator ( :: ). Size operator ( sizeof ). Conditional operator ( ?: ).

When an operator is overloaded its original meaning is not lost. Although the semantics of an operator can be extended, we cannot change its syntax, the grammatical rules that govern its use such as the number of operands, precedence and associativity.

86

v1.1

DEFINING OPERATOR OVERLOADING


To define an additional task to an operator, we must specify what it means in relation to the class to which the operator is applied. This is done with the help of a special function, called operator function, which describes the task. The general form of an operator function is: return-type classname :: operator op (arg-list) { Function body // task defined } Where, return-type is the type of value returned by the specified operation and op is the operator being overloaded.
v1.1

87

Operator functions must be either member function (non-static) or friend functions. A basic difference them is that a friend function will have only one argument for unary operators and two for binary operators, while a member function has no arguments for unary operators and only one for binary operator. This is because the operator used to invoke the member function is passed implicitly and therefore is available for member function. This is not the case with friend functions. Arguments may be passed by value or by reference.

88

v1.1

STEPS OF OPERATOR OVERLOADING


Create a class that defines the data type that is to be used in the overloading operation. Declare the operator function operator op( ) in the public part of the class. It may be either a member function or friend function. Define the operator function to implement the required operations.

89

v1.1

OVERLOADING UNARY AND BINARY OPERATOR

90

v1.1

RULES FOR OVERLOADING OPERATORS


Only existing operators can be overloaded. New operators cannot be created. The overloaded operator must have at least one operand that is of user defined type. We cannot change the basic meaning of an operator. That is, we cannot redefine the plus (+) operator to subtract one value from the other. Overloaded operators follow the syntax rules of the original operators. That cannot be overridden. There are some operators that cannot be overloaded. We cannot use friend functions to overload certain operators. However member functions can be used to overload them.

91

v1.1

Unary operators, overloaded by means of a member function, take no explicit arguments and return no explicit values. But, those overloaded by means of a friend function take one reference argument. Binary operators overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit arguments. When using binary operators overloaded through a member function, the left hand operator must be an object of the relevant class. Binary arithmetic operators such as +, -, * and / must explicitly return a value. They must not attempt to change their own arguments.

92

v1.1

QUERIES

93

v1.1

MODULE - 10

INHERITANCE

94

v1.1

OBJECTIVES
To learn about : Inheritance
Single Inheritance Multiple Inheritance Hierarchical Inheritance Hybrid Inheritance

Virtual base class Abstract base class Constructors in derived classes Nesting of classes
v1.1

95

INHERITANCE
Reusability is an important concept of Object Oriented Programming (OOP). It is always better to reuse something rather than trying to reinvent the wheel. The mechanism of deriving new class from an old one is called inheritance (or derivation). The old class is referred to as base class and the new one is called derived class. The derived class inherits some or all of the traits of the base class. A class can also inherit properties from more than one class or from more than one level.
v1.1

96

DEFINING DERIVED CLASSES


A derived class is defined by specifying its relationship with the base class in addition to its own details. Class derived-class-name : visibility-mode baseclass-name { // Members of derived class }

97

v1.1

SINGLE INHERITANCE
In single inheritance, a common form of inheritance, classes have only one base class.
PrintedDocument

Book

PaperbackBook

98

v1.1

MULTIPLE INHERITANCE
A class can inherit the attributes of two or more classes. This is known as multiple inheritance. Multiple inheritance allows us to combine the features of several existing classes as starting point for defining new classes. It is like a child inheriting the physical features of one parent and the intelligence of the other. class D : visibility B1, visibility B2 { // Body of D };

99

v1.1

HIERARCHICAL INHERITANCE

The base class will include all features that are common to the subclasses. A subclass can be constructed by inheriting the features of the base class.

10

v1.1

Students

Arts

Engineering

Medical

Mech.

Elec...

Comp.

10

v1.1

HYBRID INHERITANCE
There could be situations where we need to apply two or more types of inheritance to design a program. For instance, take the case of processing the student results. Assume weightage is to be given to sports before finalising the result. The weightage for sports is stored in a separate class called sports.

10

v1.1

Student

Test
Sports

Result

10

v1.1

VIRTUAL BASE CLASS


Consider a situation where all three kinds of inheritance, namely, multilevel, multiple and hierarchical inheritance are involved. This is illustrated in the figure. The child has two direct base classes parent1 and parent2 which themselves have a common base class grandparent. The child inherits the traits of the grandparent via two different paths. It can also inherit directly. The grandparent is sometimes referred to as indirect base class.

10

v1.1

Grandparent

Parent 1

Parent 1

Child

10

v1.1

ABSTRACT CLASS
An abstract class is one that is not used to create objects. An abstract class is designed only to act as a base class (to be inherited by other classes). It is a design concept in program development and provides a base upon which other classes may be built.

10

v1.1

CONSTRUCTOR IN DERIVED CLASSES


The general form is as shown
Derived-constructor (Arglist1, Arglist2ArglistN, ArglistD) : Base1 (Arglist1),

Base2 (Arglist2), BaseN (ArglistN) { // Body of derived constructor }

10

v1.1

NESTING OF CLASSES

C++ supports yet another way of inheriting properties of one class into another. This approach takes a view that an object can be a collection of many other objects. That is a class can contain objects of other classes as its members.

10

v1.1

QUERIES

10

v1.1

MODULE -11

POINTERS, VIRTUAL FUNCTIONS AND POLYMORPHISM

11

v1.1

OBJECTIVES
To learn about : Pointers Polymorphism Virtual functions

11

v1.1

WHY USE POINTERS

Accessing array elements. Passing arguments to a function when the function needs to modify the original arguments. Passing arrays and strings to function. Obtaining memory from the system. Creating data structures such as linked lists.

11

v1.1

ADDRESSES AND POINTERS


There are a few key concepts behind pointers. The first key concept: Every byte in the computer memory has an address. Addresses are numbers just as they are for house or street. The program when it is loaded into memory occupies a certain range of these addresses. This means that every variable and every function in your program starts at a particular address.

11

v1.1

ADDRESS OF OPERATOR(&)
The address occupied by a variable can be found out by using the address of operator ( & ). #include <iostream.h> main() { int var1 = 100; int var2 = 100; cout << &var1; cout << &var2; }

11

v1.1

POINTER VARIABLES
A variable that holds an address value is called a pointer variable. What is the data type of pointer variables? Its not the same as the variable whose address is being stored; a pointer to an int is not type int. int* ptr; The asterisk means pointer to. Thus the statement defines ptr as pointer to int. This is another way of saying that this variable can hold the address of integer variables.

11

v1.1

ACCESSING THE VALUE OF THE VARIABLE POINTED TO


#include <iostream.h> main() { int var1 = 100; int* ptr; // Pointer to an integer ptr = &var1; // Assigns the address of var1 to ptr cout << *ptr; // Prints the contents of the address pointed to by ptr }

11

v1.1

When the asterisk is used in front of a variable name as it is in *ptr expression it is called indirection operator. It means the value of the variable pointed to by. Thus, *ptr represents the value of the variable pointed to by ptr. Indirection is also referred to as dereferencing. int v; int* p; p = &v; v = 3; // Direct Addressing, assigns 3 to v *p = 5; // Indirect Addressing, assigns 5 to v

11

v1.1

POINTER TO A VOID
Consider a machine that uses a 32-bit word, Its addressing may be designed to use 32-bit boundaries, so along fits nicely in a single word and the ordinary address works nicely as a pointer. However a char might be implemented in 8 bits on such a machine which means that 4 characters would fit in a word. That means the char pointer would require some additional information to locate a particular byte inside a word. Thus the char pointer will be of a different size than the long pointer.

11

v1.1

If one always knows how big a pointer is, you can pass the address of any type to a function, and the function can perform proper typecasting based on some other piece of information. C++ invented the void pointer for this purpose. A void pointer means a pointer to any type of data.

11

v1.1

POINTER CONSTANTS AND POINTER VARIABLES


Can we use the increment operator instead of the statement *(v+1), *(v++)? The answer is no and the reason is that you cant increment a constant. The expression v is the address where the system has chosen to place your array and it will stay there until the program terminates, v is a constant. While you cant increment an address you can increment the pointer that holds the address.

12

v1.1

POLYMORPHISM
Polymorphism as the name suggests means one name, multiple forms. Function overloading and Operator overloading are implementations of polymorphism. The overloaded member functions are selected for invoking by matching arguments both type and number. The information is known to the compiler at the compile time and therefore is able to select the appropriate function for particular calls at compile time. This is called early binding or static binding or static linking. Also known as compile time polymorphism.

12

v1.1

The compiler defers the decision to run-time. Appropriate member function is selected only at runtime. This is known as run-time polymorphism. C++ supports a mechanism called virtual function to achieve run-time polymorphism. At run-time it is known what class objects are under construction, the appropriate version of the function is called. Since the function is linked with the class much later after the compilation, this process is termed as late binding. It is also called dynamic binding because the selection of the function is done dynamically at runtime.

12

v1.1

POINTER TO OBJECT
A pointer can point to an object created by class. Consider the following statement: Item x; Where Item is the class and x is its instance. Similarly we can define a pointer it_ptr of type Item. Item it_ptr; Object pointers are useful in creating objects at runtime. We can also use object pointer to access the public members of an object.

12

v1.1

this POINTER
C++ uses a unique keyword called this to represent an object that invokes a member function. this is a pointer that points to the object for which this function was called. For instance, the function A.max( ) will set the pointer this to the address of the object A. The starting address is same as the address of the variable in the class structure. The unique pointer is automatically passed to the member function when it is called. The pointer this acts as an implicit argument to all member functions.

12

v1.1

POINTERS TO DERIVED CLASSES


We can use pointers not only to the base objects but also to the objects of the derived class. Pointers to the objects of the base class are type compatible with pointers of the derived class. Therefore a single pointer variable can be made to point to objects belonging to different classes.

12

v1.1

VIRTUAL FUNCTIONS
An essential requirement of polymorphism is the ability to refer to objects without any regard to their classes. This necessitates the use of single pointer variable to refer to objects of different classes. Here we use the pointer to the base class to refer to all derived objects. This is achieved using virtual functions. When we use the same function name in both the base and the derived classes, the function in base class is declared as virtual using the keyword virtual preceding its normal declaration. Thus, by making the base pointer to point to different objects, we can execute different versions of the virtual function

12

v1.1

RULES FOR VIRTUAL FUNCTIONS


The virtual functions must be members of the same class. They cannot be static members. They are accessed by using object pointers. A virtual function can be a friend of another class. A virtual function in the base class must be defined even if it is not used. The prototypes of base class version of a virtual function and the entire derived class version must be identical. If two functions with the same names have different prototype, C++ consider them as overloaded functions, and the virtual function mechanism is ignored.

12

v1.1

We cannot have virtual constructors but we can have virtual destructors. While a base pointer can point to any type of the derived object, the reverse is not true. That is we cannot use a pointer to a derived class to access an object of the base type. When a base pointer points to a derived class, incrementing or decrementing it will not make it point to the object of the derived class. It is incremented or decremented only to its base type. Therefore, we should not use this method to move the pointer to the next object.

12

v1.1

If a virtual function is derived in the base class, it need not necessarily be redefined in the base class. In such cases, calls will invoke the base function.

12

v1.1

PURE VIRTUAL FUNCTIONS


It is a normal practice to declare a function virtual inside the base class and redefine it in the derived class. The function inside the base class is seldom used for performing any task. It only serves as a placeholder. Such functions are called do-nothing functions. A donothing function may be defined as follows.

virtual void display( ) = 0;

13

v1.1

Such functions are called pure virtual functions. A pure virtual function is a function declared in a base class that has no definition relative to the base class. In such cases, the compiler requires each derived class to either define the function or redeclare it as a pure virtual function. A class containing pure virtual functions cannot be used to declare any objects of its own. Such classes are called Abstract Base Classes (ABC). The main objective of the ABC is to provide some traits to the derived classes and to create a base pointer required for achieving run-time polymorphism.

13

v1.1

QUERIES

13

v1.1

MODULE -12

MANAGING CONSOLE I/O OPERATIONS

13

v1.1

OBJECTIVES
To learn about : Stream Stream Classes Formatting the output.

13

v1.1

INTRODUCTION
C++ uses the concept of stream and stream classes to implement I/O operations with the console and disk files. The I/O system is designed to work with a wide variety of devices including terminals, disks and tape drives. Although each device is very different the I/O system supplies an interface known as stream, that is independent of the device being accessed.

13

v1.1

STREAMS
A stream is sequence of bytes. It acts as a source from which the input data can be taken and acts as a destination to which output data can be sent. The source stream is called the input stream and the destination stream is called output stream. The data in the input stream can come from the keyboard or any other storage device. Similarly the data in the output stream can go to the screen or any other storage device.

13

v1.1

STREAM CLASSES
ios (General input/output stream class)
Contains basic facilities that are used by all other input and output classes. It also contains a pointer to a buffer object (streambuf object). Declares constants and functions that are necessary for handling input and output operations.

istream (input stream)


Inherits the properties of ios. Declares input functions such as get(), getline() and read() Contains overloaded extraction operator >>.

13

v1.1

ostream (output stream)


Inherits the properties of ios. Declares output functions such as put(), write(). Contains overloaded insertion operator <<.

iostream (input/output stream)


Inherits the properties of ios, istream and ostream through multiple inheritance and thus contains all the input and output functions.

streambuf
Provides the interface to physical devices through buffers. It acts as a base for filebuf class used in files.

13

v1.1

FORMATTING THE OUTPUT


C++ supports a number of features that could be used for formatting the output. These feature include:
Ios class functions and flags Manipulators User-defined output functions

13

v1.1

QUERIES

14

v1.1

MODULE -13

WORKING WITH FILES

14

v1.1

OBJECTIVES
To learn about : Classes for file streams Various file operations Binary vs. Text files Command line processing

14

v1.1

INTRODUCTION
Streams provide a uniform way of dealing with data coming from the keyboard or the hard disk and going out to the screen or hard disk. To open and close files, you create ifstream and ofstream objects. the particular objects used to read from or write to files are called ofstream objects. These are derived from the iostream objects you've been using so far.

14

v1.1

CLASSES FOR FILE STREAMS


Class filebuf Contents Its purpose is to set the file buffers to read and write Provides operations common to file streams. Provides input operations Provides output operations Provides support for simultaneous Input and output operations
v1.1

fstreambase
ifstream ofstream fstream

14

VARIOUS FILE OPERATIONS

14

v1.1

BINARY VERSUS TEXT FILES


Some operating systems, such as DOS, distinguish between text files and binary files. Text files store everything as text (as you might have guessed), so large numbers such as 54,325 are stored as a string of numerals (`5', `4', `,', `3', `2', `5'). This can be inefficient, but has the advantage that the text can be read using simple programs such as the DOS program type. To help the file system distinguish between text and binary files, C++ provides the ios::binary flag. On many systems, this flag is ignored because all data is stored in binary format.

14

v1.1

Binary files can store not only integers and strings, but entire data structures. You can write all the data at one time by using the write() method of fstream. If you use write(), you can recover the data using read()

14

v1.1

COMMAND LINE PROCESSING


Many operating systems, such as DOS and UNIX, enable the user to pass parameters to your program when the program starts. These are called command-line options, and are typically separated by spaces on the command line. For example: SomeProgram Param1 Param2 Param3 These parameters are not passed to main() directly. Instead, every program's main() function is passed two parameters.

14

v1.1

The first is an integer count of the number of arguments on the command line. The program name itself is counted, so every program has at least one parameter. The second parameter passed to main() is an array of pointers to character strings. Because an array name is a constant pointer to the first element of the array, you can declare this argument to be a pointer to a pointer to char, a pointer to an array of char, or an array of arrays of char. Typically, the first argument is called argc (argument count), but you may call it anything you like. The second argument is often called argv (argument vector), but again this is just a convention.

14

v1.1

QUERIES

15

v1.1

MODULE -14

TEMPLATES & EXCEPTIONS

15

v1.1

OBJECTIVES
To learn about : Templates Use of templates Advantages of templates Templates vs. macros. Templates vs.. void pointers Exception handling

15

v1.1

INTRODUCTION
Templates provide direct support for generic programming that is, programming using types as parameters. A template can be used to create family of classes and functions. Exception handling provides a mechanism to identify and manage certain disastrous conditions during the execution of the program.

15

v1.1

TEMPALTES
Templates are mechanisms for generating functions and classes based on type parameters (templates are sometimes called "parameterized types"). By using templates, you can design a single class that operates on data of many types, instead of having to create a separate class for each type.

15

v1.1

USE OF TEMPLATES
Create a type-safe collection class (for example, a stack) that can operate on data of any type. Add extra type checking for functions that would otherwise take void pointers. Encapsulate groups of operator overrides to modify type behavior (such as smart pointers).

15

v1.1

ADVANTAGES OF TEMPLATES
Templates are easier to write. You create only one generic version of your class or function instead of manually creating specializations. Templates can be easier to understand, since they can provide a straightforward way of abstracting type information. Templates are type-safe. Because the types that templates act upon are known at compile time, the compiler can perform type checking before errors occur.

15

v1.1

TEMPLATES VS. MACROS


In many ways, templates work like preprocessor macros, replacing the templated variable with the given type. Here are some problems with the macro:
There is no way for the compiler to verify that the macro parameters are of compatible types. The macro is expanded without any special type checking. The i and j parameters are evaluated twice. If either parameter has a post incremented variable, the increment is performed two times.

Because the preprocessor expands macros, compiler error messages will refer to the expanded macro, rather than the macro definition itself. Also, the macro will show up in expanded form during debugging.

15

v1.1

TEMPLATES VS. VOID POINTERS


Many functions that are now implemented with void pointers can be implemented with templates. Void pointers are often used to allow functions to operate on data of an unknown type. When using void pointers, the compiler cannot distinguish types, so it cannot perform type checking or type-specific behavior such as using type-specific operators, operator overloading, or constructors and destructors.

15

v1.1

With templates, you can create functions and classes that operate on typed data. The type looks abstracted in the template definition. However, at compile time the compiler creates a separate version of the function for each specified type. This enables the compiler to treat class and function templates as if they acted on specific types. Templates can also improve coding clarity, because you don't need to create special cases for complex types such as structures.

15

v1.1

EXCEPTION HANDLING
The C++ language provides built-in support for handling anomalous situations, known as "exceptions," which may occur during the execution of your program. With C++ exception handling, your program can communicate unexpected events to a higher execution context that is better able to recover from such abnormal events. These exceptions are handled by code that is outside the normal flow of control. In C++, the process of raising an exception is called "throwing" an exception.

16

v1.1

A designated exception handler then "catches" the thrown exception. Exceptions are of two kinds, namely, synchronous exceptions and asynchronous exceptions. Errors such as out of range index and overflow are synchronous exceptions. The exceptions that are caused by events that are beyond the control of the program are asynchronous exceptions.

16

v1.1

SYNTAX OF EXCEPTION HANDLING CODE

16

v1.1

GENERAL MECHANISM FOR ERROR HANDLING IS AS FOLLOWS:

Find the problem (Hit the exception) Inform that the error has occurred (Throw the exception) Receive the error information (Catch the exception) Take corrective actions (Handle the exception)

16

v1.1

STRIKING THING ABOUT EXCEPTIONS

One of the striking thing about C++ exceptions is that they allow you to return any type of object from a function regardless of what the function return type is.
The other fascinating feature of exceptions is that if youve constructed some of the objects in a block, and you hit an exception, the only destructors called are for the objects not all.

16

v1.1

QUERIES

16

v1.1

Você também pode gostar