cpp

152
1 OOP’s and Basics of C++ Need of C++ During the late 1970s and early 1980s, ‘C’ became the Leading computer programming language, and it is still widely used today. Since ‘C’ is a successful and useful language, what is the need of C++? Throughout the history of programming, the increasing complexity of program has driven the need for better ways to mange that complexity. C++ is a response to that need. Approaches to programming have changed dramatically since the invention of the computer. For example, when computers were first invented, programming was done by manually toggling in the binary machine instructions by use of the front panel. As long as programs were just a few hundred instructions long, this approach worked. As programs grew, assembly language was invented so that a programmer could deal with larger, increasingly complex programs by using symbolic representations of the machine instructions, As programs continued to grow, high-level languages were introduced that gave the programmer more tools with capabilities to handle complexity. The first widespread language was, of course, FORTRAN. While FORTRAN was an impressive first step, it is hardly a language that encourages clear and easy-to-understand programs. The 1960s gave birth of structured programming. This is the method of programming championed by languages such as C. The use of structure languages enables programmers to write, for the first time, moderately complex programs fairly easily. However, even with structured programming methods, once a project reaches a certain size, its complexity exceeds what programmers can mange. By the early 1980s, many projects were pushing the structured approach past it limits. To solve this problem a new way to program was invented, called Object-Oriented–Programming (OOP). Object-oriented programming is discussed in detail later in this book, but here is a brief definition: OOP is a programming methodology that helps organize complex programs through the use of inheritance, encapsulation and polymorphism. In the final analysis, although ‘C’ is one of the world’s great programming languages, there is a limit to its ability to handle complexity. Once a program exceeds somewhere between 25,000 to 1,00,000 lines of coed, it becomes so complex that is the difficult to grasp as a totality. C++ allows this barrier to be broken, and helps programmer comprehend and mange larger programs. Bjarne Stroustrup invented C++ in 1979, while he was working at Bell Laboratories in Murray Hill, New Jersey. Stroustrup initially called the newly invented language as a “C with Classes”. However, in 1983, the name was changed to C++. C++ extends C by adding object-oriented features. Because c++ is built

Upload: nitince

Post on 16-Dec-2015

217 views

Category:

Documents


0 download

DESCRIPTION

C++ Book

TRANSCRIPT

  • 1OOPs and Basics of C++Need of C++

    During the late 1970s and early 1980s, C became the Leading computer programming language, and it isstill widely used today. Since C is a successful and useful language, what is the need of C++?

    Throughout the history of programming, the increasing complexity of program has driven the need forbetter ways to mange that complexity. C++ is a response to that need.

    Approaches to programming have changed dramatically since the invention of the computer. For example,when computers were first invented, programming was done by manually toggling in the binary machineinstructions by use of the front panel. As long as programs were just a few hundred instructions long, thisapproach worked. As programs grew, assembly language was invented so that a programmer could dealwith larger, increasingly complex programs by using symbolic representations of the machine instructions,As programs continued to grow, high-level languages were introduced that gave the programmer moretools with capabilities to handle complexity.

    The first widespread language was, of course, FORTRAN. While FORTRAN was an impressive firststep, it is hardly a language that encourages clear and easy-to-understand programs. The 1960s gavebirth of structured programming. This is the method of programming championed by languages such as C.The use of structure languages enables programmers to write, for the first time, moderately complexprograms fairly easily. However, even with structured programming methods, once a project reaches acertain size, its complexity exceeds what programmers can mange. By the early 1980s, many projectswere pushing the structured approach past it limits. To solve this problem a new way to program wasinvented, called Object-OrientedProgramming (OOP). Object-oriented programming is discussed indetail later in this book, but here is a brief definition: OOP is a programming methodology that helpsorganize complex programs through the use of inheritance, encapsulation and polymorphism.

    In the final analysis, although C is one of the worlds great programming languages, there is a limit to itsability to handle complexity. Once a program exceeds somewhere between 25,000 to 1,00,000 lines ofcoed, it becomes so complex that is the difficult to grasp as a totality. C++ allows this barrier to be broken,and helps programmer comprehend and mange larger programs.

    Bjarne Stroustrup invented C++ in 1979, while he was working at Bell Laboratories in Murray Hill, NewJersey. Stroustrup initially called the newly invented language as a C with Classes. However, in 1983,the name was changed to C++. C++ extends C by adding object-oriented features. Because c++ is built

  • 2upon the foundation of C, it includes all Cs features, attributes and benefits. This is a crucial reason forthe success of C++ as a language. The invention of C++ was not an attempt to create a completely newprogramming language. Instead, it was an enhancement to an already highly successful language C.

    R As Discussed above C++ is superset of C. Therefore, almost all C programs are also C++program.

    The Three OOP Principles

    All object-oriented programming languages provide mechanisms that help you implement the object-orientedmodel. They are encapsulation, inheritance, and polymorphism. Lets take a look at these concepts now.

    Encapsulation

    Encapsulation is the mechanism that binds code and the data. It manipulates and keeps both safe fromoutside interference and misuse. One way to think about encapsulation is a protective wrapper that preventsthe code and data from being arbitrarily accessed by other code defined outside the wrapper. Access tothe code and data inside the wrapper is tightly controlled through a well-defined interface. To relate this toreal world, consider the automatic transmission on an automobile. It encapsulates hundreds of bits ofinformation about your engine, such as how much you are accelerating, the pitch of the surface you areon, and the position of the shift lever. You, as the user, have only one method of affecting this complexencapsulation, by moving the gear-shift lever. You cant affect the transmission by using the turn signal orwindshield wipers, for example. Thus, the gear-shift lever is a well-defined (indeed, unique) interface tothe transmission. Further, what occurs inside the transmission does not affect objects outside thetransmission. For example, shifting gears does not turn on the headlights! Because an automatic transmissionis encapsulated, dozens of car manufactures can implement one in any way they please. However, fromthe drivers point of view, they all work the same. This same idea can be applied to programming. Thepower of encapsulated code is that everyone knows how to access it and thus can use it regardless of theimplementations details and without fear of unexpected side effects.

    Inheritance

    Inheritance is the process, which on object acquires the properties of another object. This is importantbecause it supports the concept of hierarchical classification. Inheritance is managed by hierarchicalapproach (that is top-down approach) For example, classification of dog, which is turn is part of themammal class, which is under the larger class animal. Without the use of hierarchies, each object wouldneed to define all of its characteristics explicitly. However, by use of inheritance, an object need onlydefine those qualities that make it unique within its class. It can inherit its general attributes from itsparent. Thus, its is the inheritance mechanism that makes its possible for one object to be a specificinstance of a more general case. Lets take a closer at this process.

    Most people naturally view the world as made up of objects that are related to each other in hierarchicalway, such as animals, mammals, and dogs. If you wanted to describe animals in an abstract way, youwould say they have some attributes, such as size, intelligence, and type of skeletal system. Animals alsohave certain behavioral aspects; they eat, breath, and sleep. This description of attributes and behavior isthe class definition for animals.

  • 3If you wanted to describe a more specific class of animals, such as mammals, they would have morespecific attributes, such as type of teeth, and mammary glands. This is known as subclass of animals,where animals are referred to as mammals super class.

    Since mammals are simply more precisely specified animals, they inherit all of the attributes from animals.A deeply inherited subclass inherits all of the attributes from each of its ancestors in the class hierarchy.

    Inheritance interacts with encapsulation as well. If a given class encapsulates some attributes, then anysubclass will have the same attributes plus any that it adds as part of its specialization. This is a keyconcept, which lets object-oriented programs grow in complexity linearly rather than geometrically. Anew subclass inherits all of the attributes of all of its ancestors. It does not have unpredictable interactionswith the majority of the rest of the code in the system.

    Polymorphism

    Polymorphism (From the Greek, meaning many forms) is a feature that allows one interface to be usedfor a general class of actions. The specific action is determined by the exact nature of the situation. Likemilk, is used to prepare Tea and one can make Coffee from it. Consider a stack. You might have aprogram that requires three types of stacks. One stack is use for integer value, one for float value andone for character. The algorithm that implements each stack is the same, even though the data beingstored differs. In non object-oriented programming , you would be required to create three differentsets of stack routines, with each set using different names. But in OOPs with the concept of polymorphism,you can specify a general set of stack routines that all share the same names.

    More generally, the concept of polymorphism is often expressed by the phrase one interface, multiplemethods. This means that is possible to design a generic interface to a group of related activities. Thishelps reduce complexity by allowing the same interface to be used to specify a general class of action.Its compiler job to select the specific action (that is method) as it applies to each situation. You need onlyremember and utilized the general interface.

    Extending the dog analogy, a dogs senesce of smell is polymorphic. If the dog smells a cat, it will barkand run after it. If it smells food, it will salivate and run to its bowl. The same sense of smell is at workin both situations. The difference is what is being smelled, that is, the type of data being operated upon bythe dogs nose!. This same general concept can be implemented in OOPs as it applies to methods.

    Application of C++

    C++ is very easy language for handling very large programs. While C++ is able to map the real-worldproblem properly, the C part of C++ gives the language the ability to get close to the machine-level details.C++ programs are easily maintainable and expandable. When a new feature needs to be implemented, itis very easy to add to the existing structure of object.

  • 4First C++ Program

    As early discussed (in C) the best way to learn a new programming language is writing a program init. Let us begin with a simple program, which prints Welcome to AZURE on the screen.

    Example

    /* First C++ Program */

    #include // include header file

    void main()

    { cout

  • 5Key in above program and save it at proper place with .cpp extension.

    To execute above program, Select Run option from Run menu or press Ctrl + F9 key combination.The Compilation and linking process will be displayed in the progress window.

    If there are any error(s) it will display all the respective error messages in message window other-wise you will get appropriate output.

    Explanation of First C++ Program

    Like C, The C++ program is a collection of functions. As C, when you run a C++ program,the first statement is executed will be the beginning of a function called main(). The program mayconsist more than one function, but execution of program is done from the function main(). Theword void preceding the function main() indicates that this particular function does not return anyvalue.

    As you aware that every function in C returns value and by default it returns integer value. It istrue for C++. In C we can ignore return statement but in C++ its not possible. If you writemain() without specifying void, program should ends with return statement; otherwise a warning oran error might occur.

    # include directive causes the preprocessor to add the contents of the mention header file in theprogram. iostream.h is responsible for the input and output for any program in C++. It containsdeclarations for the identifier cout and the operator

  • 6anyone reading the program, to understand whats going on. These are non-executable statementsi.e. the compiler ignores comments. Comments are not compulsory in a program but inclusion ofcomments in a program improves its readability. The comment used in C language ( /* */ ) forsingle and multi-line are also valid in C++. // (double slash) symbol introduced for comment inC++. A comment may start anywhere in the line and ends with end of lines. (There is no closingsymbol for //). It is also known as a single line comment.

    Output in C++

    In C++ cout is used to display string or value of variable on the screen. General form of cout is :

    cout

  • 7Data Types

    In any programming language data types allows a programmer to create variables for manipulatevarious data in program.

    C++ is a superset of C Language So, C++ supports all the data types (Basic & Derived) used inC Language with its modifier. Following table list out all the basic data types and modifier alongwith their size and range.

    Data Type Bytes Range

    integer (signed integer) 2 -32768 t0 32767unsigned integer 2 0 to 65535short integer 2 -32768 t0 32767short unsigned integer 2 0 to 65535long integer 4 -2147483648 to +2147483647long unsigned integer 4 0 to 4294967295float 4 -3.4e+38 to +3.4e+38double 8 -1.7e+308 to +1.7e+308long double 10 -3.4e+4932 to 1.1e4932character 1 -128 to 127unsigned character 1 0 to 255

    C++ introduce new user-defined data type called class (We will discussed it very soon in detailed)Variables

    Variables plays important role in programming language. Values can be assigned to variables, whichcan be changed during the execution of program.

    In C Language variables must be declared before it appears in an executable statement and all thevariable must be declared before any executable statement of C in program or function. Declara-tion of variable after an executable statement is invalid in C. In C++ declaration of variable canbe done anywhere within the program or function - as and when they are required.

    R Declaration and Initialization of the variable is same as C Language.Example

    #includevoid main(){

    cout

  • 8cout > with cin. It extracts the value from the keyboard andassigns it to the variable on its right. >> is also known as a get from operator. It belongs in thecategory of cascading operator.

    R Like C Language, there is no need of conversion character with cin while youaccept value from a user.

    ExampleAccept character, number and name from a user.

    #includevoid main(){ char c;

    int n;char nm[];cout> ccout> n;cout> nm;}

  • 9ExampleAccept Number from a user and print its square in formatted manner.

    #includevoid main(){

    int n,s;cout> n;s = n * n ;

    cout > n2;cout

  • 10

    Example

    Use of endl

    #include#includevoid main(){ clrscr(); cout

  • 11

    It is possible if we specify a specific width for all the number and force them to be printed rightjustified. This can be possible using setw manipulator. Following program illustrate use of setwmanipulator to get specific output.

    #include#includevoid main(){ clrscr(); int a=345, b=1234, c=89;

    cout

  • 12

    Simple form of If Statementif (expression){ Statement(s) block;}next statement

    Example

    Accept String from the user. If entered string is AZURE then print its motto.

    #include #include #include void main(){ clrscr();

    char st[20];cout > st;if (strcmp(st,"AZURE")==0)

    print("Carving the Career");}

    If Statement with else clause

    if (expression){ true block;}else{ false block;}

    Example

    Accept character from a user and find out whether it is Vowel or Not.

    #include #include #include void main(){ clrscr();

  • 13

    char ch,x;cout > ch;x = toupper(ch);if(x==A || x==E || x==I || x==O || x==U)

    cout =50 & < 65 D

  • 14

    # include void main(){ int rn,m1,m2,m3,tot; float avg; char nm[20],grd;

    rn=m1=m2=m3=tot=0; avg=0.0; clrscr(); cout > nm; cout > rn; cout > m1; cout > m2; cout > m3;

    tot = m1 + m2 + m3; avg = (float)tot / 3;

    if(avg >= 85) grd = A;

    else if(avg >= 75) grd = B;

    else if(avg >=65) grd = C;

    else if(avg >=50) grd = D;

    else grd = F;

    cout

  • 15

    -

    if (expression) statement

    else statement}else{ statement(s);}

    Example

    Accept Employee Name, Basic salary and Grade from the user and print its Net Salary usingfollowing calculation.

    Grade Basic Salary HRA D A PF

    A >=10000 15% 12% 12.5%>=5000 and grd;cout > bs;

    if(toupper(grd) == A){ if(bs >= 10000)

  • 16

    { hra = bs * 0.15;da = bs * 0.12;pf = bs * 0.125;

    } else { if(bs >= 5000)

    { hra = bs * 0.14; da = bs * 0.115; pf = bs * 0.125;}else{ hra = bs * 0.13; da = bs * 0.11; pf = bs * 0.12;}

    }}else{ if(toupper(grd) == B) { if(bs >= 10000) { hra = bs * 0.13;

    da = bs * 0.12; pf = bs * 0.12;

    } else {

    hra = bs * 0.12; da = bs * 0.11; pf = bs * 0.10;

    } } else { if(toupper(grd) == C) { if(bs >= 5000)

    { hra = bs * 0.12;da = bs * 0.11;pf = bs * 0.10;

    } else { hra = bs * 0.11;

    da = bs * 0.10;pf = 0.0;

    } } }}

  • 17

    net = bs + hra + da - pf;

    cout

  • 18

    cout > n1;cout > n2;cout > op;

    switch(op){ case + : tot = n1 + n2;

    break;

    case - : tot = n1 - n2; break;

    case * : tot = n1 * n2; break;

    case / : tot = n1 / n2; break;

    case % : tot = n1 % n2; break;

    default : flag = Y;}

    if (flag == Y)cout

  • 19

    ExampleWrite a necessary code to print following Series.1, 4, 27, 16, 125, 36, 343, 64, 729, 100

    # include # include # include void main(){ clrscr();

    for(int I=1;I

  • 20

    ExampleAccept number(s) from a user till user choice and print sum of entered number.

    # include # include void main(){ char ch = Y; clrscr(); int n = 0, s = 0;

    while(ch == Y || ch == y) { cout > n;s += n;

    cout > ch;

    } cout 0){ i = x % 10;

    x = x / 10;s+=(i*i*i);

    }

    if(s == n) cout

  • 21

    do..while Loopdo..while loop is used when iteration is based on condition As you aware, It is very similar to whileloop except the test occurs at the end of the loop body. So, these loop is executed at least once incase of wrong condition even.

    do{

    body of do..while loop}while(condition);

    Exampleprint the series a to z

    # include # include

    void main(){ char ch = a;

    do{ cout

  • 22

  • 23

    Functions in C++

    Like a C Language, In C++ functions provide modularity approach, which is small part of your mainprogram. A function is a self-contained program segment that carries out a specific, well-defined task.Functions can be written independent of system-dependent features, making programs more portable.Also, such programs are more readable and can be well documented. The same function can be calledfrom many points within a program, avoiding redundant code. A function may or may not take some datafrom the main program and may or may not returns value to the caller program. Caller program might bea main program or another function.

    Every C++ program has at least one function, main(). When your program starts, main() is calledautomatically. main() might call other functions, some of which might call still others

    C++ has added many new features to functions to make them more reliable and flexible. All thesechanges have been made to implement object-oriented concepts.

    Some New Features in C++ Functions are

    Function overloading Inline function Friend function Static function

    Prototype of the Function

    As we aware that prototype describes the function interface to the compiler by giving details such as thenumber and type of arguments and the type of return values. So, one can say prototype is nothing but it isa declaration of function. Function prototypes are listed at the beginning of the source file. In C languageprototype is a optional, but as you aware (being a good programmer..!) it is considered good practice touse prototype declarations for all functions that you call in the program. In C++ one cannot ignore prototypeof function like C. It is compulsory in C++. General form of function prototyping in calling program is asfollows:

    return_type function_name(argument_list);

    The argument_list contains the types and argument names. One can ignore argument_list, If functiondoes not receive any values from the caller programmer.

  • 24

    The return_type indicates the type of value return by the function. If one can ignore return_type then bydefault it will consider as integer.

    e.g.

    int sum(int a, int b);

    In a function prototype (function declaration) argument names are dummy variables so they are optional.Above example of function declaration is written as follows without argument name

    int sum(int , int);

    Function Definition

    The definition contains the actual code for the function. The function body is composed of the statementsthat make up the function, delimited by braces. It must have the same number of arguments with the sametypes in the same order and have the same return type as describe in its prototype.

    The return statement

    The return statement terminates the execution of the function and control is passed back to the callingprogram (function) with a specified value. There can be any number or return statements or none at all.If there is no return statement in a function, control passes back to the calling program when the closingbraces of the body part is encountered and it should be declared with void keyword.

    The return statement may or may not include a constant, variable or an expression as a returning value.The expression or variable or constant should be same type of function return_type. The general formaof return statement is

    return(expression);

    Calling The Function

    The function can be called (invoked) in a program as follows

    function_name(argument list if any);

    e.g.count(m,n); // Function Call

    The variable m and n are known as the actual parameters. Note that, the calling statement should notinclude type names in the arguments list.

    Suppose, if function return any value then it can be called as

    x = count(m,n); // Function Call

  • 25

    Here, x will receive the value return by the function.

    Example

    #include #include void line(); // function prototypemain(){

    line(); // function callcout

  • 26

    First lets check what happen if the variables are passed by value:

    Example

    Following example illustrate Call by Value

    #include void exchange(int, int);

    void main(){

    int a, b;a = 5;b = 7;cout

  • 27

    void exchange(int *, int *);

    void main(){ int a, b, *pa , *pb;

    pa=&a ; // storing the address of a in papb=&b ; // storing the address of b in pb

    a=15;b=20;

    cout

  • 28

    long myFunction (int x = 50);

    This prototype says, myFunction() returns a long and takes an integer parameter. If an argument is notsupplied, use the default value of 50.

    As you know parameter names are not required in function prototypes, this declaration could have beenwritten as

    long myFunction (int = 50);

    Declaring a default parameter does not change the function definition. The function prototype for thisfunction would be

    long myFunction (int x) orlong myFunction (int)

    If the calling function did not include a parameter, the compiler would fill x with the default value of 50.The name of the default parameter in the prototype need not be the same as the name in the functionheader; the default value is assigned by position, not name.Any or all of the functions parameters can be assigned default values. The one restriction is this: If anyof the parameters does not have a default value, no previous parameter may have a default value.

    If the function prototype looks likelong myFunction (int Param1, int Param2, int Param3);you can assign a default value to Param2 only if you have assigned a default value to Param3. You canassign a default value to Param1 only if you have assigned default values to both Param2 and Param3.

    #include

    int AreaCube(int length, int width = 25, int height = 1);

    int main(){ int length = 100; int width = 50; int height = 2; int area;

    area = AreaCube(length, width, height); cout

  • 29

    cout

  • 30

    // Function Prototype

    void line();void line(char);void line(char, int);

    void main(){cout

  • 31

    even though the function names are same.

    In the above example we have created different functions with the same name with the different numberof arguments but one can have same number of arguments but with the different data type. Thus compilercan also distinguish between overloaded functions with the same number of arguments, with differentdata types.

    ExampleFollowing example illustrate function overloading with the same number of arguments but differenttypes

    #include

    int Double(int);long Double(long);float Double(float);double Double(double);

    int main(){ int myInt = 6500; long myLong = 65000; float myFloat = 6.5F; double myDouble = 6.5e20;

    int doubledInt; long doubledLong; float doubledFloat; double doubledDouble;

    cout

  • 32

    return(0);}

    int Double(int original){ return 2 * original;}

    long Double(long original){ return 2 * original;}

    float Double(float original){ return 2 * original;}

    double Double(double original){ return 2 * original;}

    Output

    myInt: 6500myLong: 65000myFloat: 6.5myDouble: 6.5e+20

    DoubledInt: 13000DoubledLong: 130000DoubledFloat: 13DoubledDouble: 1.3e+21

    In the above example Double() function is overloaded with int, long, float, and double.The compiler examines the arguments and chooses which of the four Double() functions to call.Inline Functions

    When you define a function, normally the compiler creates just one set of instructions in memory. Whenyou call the function, execution of the program jumps to those instructions, and when the function return,execution jumps back to the next line in the calling function. If you call the function 10 times, your programjumps to the same set of instructions each time. This means there is only one copy of the function, not 10.

    There is some performance overhead in jumping in and out of functions. It turns out that some functionsare very small, just a line or two of code, and some efficiency can be gained if the program can avoid

  • 33

    making these jumps just to execute one or two instructions. When programmers speak of efficiency, theyusually mean speed: the program runs faster if the function call can be avoided.

    If a function is declared with the keyword inline, the compiler does not create a real function: it copies thecode from the inline function directly into the calling function. No jump is made; it is just as if you hadwritten the statements of the function right into the calling function.

    Note that inline functions can bring a heavy cost. If the function is called 10 times, the inline code is copiedinto the calling functions each of those 10 times. The tiny improvement in speed you might achieve is morethan swamped by the increase in size of the executable program. Even the speed increase might beillusory. First, todays optimizing compilers do a terrific job on their own, and there is almost never a biggain from declaring a function inline. More important, the increased size brings its own performance cost.

    Whats the rule of thumb? If you have a small function, one or two statements, it is a candidate for inline.When in doubt, though, leave it out. Following program demonstrates use of an inline function.

    #include

    inline int Double(int);int main(){

    int target;

    cout > target;cout

  • 34

    In the above program Double() is declared to be an inline function taking an int parameter and returningan int. The declaration is just like any other prototype except that the keyword inline is preceded justbefore the return type.

    When above code is executed, this will compiles into code that is the same as if you had written thefollowing:

    target = 2 * target; everywhere you enteredtarget = Double(target);

    By the time your program executes, the instructions are already in place, compiled into the OBJ file. Thissaves a jump in the execution of the code, at the cost of a larger program.

    R Inline is a hint to the compiler that you would like the function to be inlined. The compileris free to ignore the inline process request and make it as a normal function call.

  • 35

    Classes and ObjectsAs we discuss earlier C++ was initially known as a C with the Classes. So, Classes is the most importantfeature of the C++. A Class is a one kind of user-defined data type used in C++. It is an extended versionof C Structure.

    As you are aware that C offers programmer to define use-defined data type using structure. It is usedto group logically related data items of different data types. In structure data hiding is not possible so, allthe member variables of structure is accessible within their scope.

    R C++ supports all the feature of structures defined in C.

    Declaration of Class

    A Class is a collection of variables-often of different types-combined with a set of related functions. Ithides data from its external use.

    General form of a class declaration is:

    class class_name{ private :

    variable declaration;function declaration;

    public :variable declaration;function declaration;

    };

    The Class declaration is similar to a structure declaration. Its declaration starts with keyword class,followed by the class name. Like a structure, the body of the class is delimited by braces and terminatedby a semicolon.

    The class body contains the declaration of variables and functions. These functions and variables arecollectively called members of the class. The variables in the class are referred as the member variablesor data members. The functions in the class typically manipulate the member variables are referred as

  • 36

    member functions or methods of the class.

    The keywords private and public are known as access specifier. It followed by a colon. The feature ofdata hiding is implemented using access specifier. Private members can be accessed only within functionsof the class itself. Public members can be accessed through any object of the class. All members of aclass-variables and functions-are private by default i.e. if you are declared members without accessspecifier, by default it will consider as a private member.

    The term private means that the data is covered within a class, so that it is not accessed accidentally byfunctions or manipulating statements outside the class. That means the data declared under category ofprivate can only be used or accessed by the member functions of the class. This kind of data is hiddenfrom the outer world so it will be safe from the accidental manipulation.

    Usually the data members within a class is declared as private and the functions are public. However,there is no rule that data must be private and functions public. One can declare members under anycategory of access specifier.

    class Number{ private :

    int n; public :

    void getdata(){ cout > n ;}

    void viewdata(){ cout

  • 37

    Above statement will declared n1 object of the Class Number.

    When we create an object of the class, the necessary memory space is allocated to that object.

    We can declared more than one object of class in a single statement like :

    Number n1,n2;

    As shown above each object of class is having separate copies of member variable in it.

    Difference between Class and Object

    You never pet the definition of a cat; you pet individual cats. You draw a difference between the idea ofa cat, and the particular cat that right now moving all over in your room.

    In the same way, C++ differentiates between the class Cat, which is the idea of a cat, and each individualcat - object. Thus, pussy is an object of type Cat.

    Accessing Members

    Public member

    Public data member can be accessed from outside the class using the objects. It can also access fromanother member function of same class. Members of a class can be access by an object of that classusing dot(.) operator.

    Calling a public members of the class

    Data member : Object.data_name;Function member : Object_name.function_name(list of parameters);

    For example,

    ob.var // access of member variableob.func(a,b); // access of member function

    n

    n1

    n

    n1

    n

    n2

  • 38

    Private member

    Private data member of a class can be accessed only through the member functions of that class and notdirectly by the object using dot(.) operator.

    class temp{ private:

    int num1 ;void showData(); //prototype of function

    public:int num2;void getData(); // prototype of function

    };

    void main(){

    temp t; // define object of temp classt.num1=5; // error , num1 is privatet.num2=9 // OK, num2 is public

    t.showData(); // error , showData() is private.t.getData() // OK, getData() is public

    }

    In the above example, num2 and getData() are public member of the class so, we can access them out ofclass using object. num1 and showData() are private member of class so, we cannot access them out ofthe class.

    ExampleCreate a class called Number, having one member variable to store number. Using one member functionaccepts the value of member variable and display entered value using another member function.

    # include # include # include

    class Number{ private :

    int n; public :

    void getData(){ cout > n ;}

  • 39

    void viewData(){ cout

  • 40

    t1.getTime();t1.viewTime();

    }

    Array of Object

    As a normal variable array one can create an array of the object.

    Example

    Create a Class called Student. Create a member to perform following tasks.a) To Accept data of rollno, name and marks of three subjects from the user for 5 Students.b) To Calculate the Result.c) To print the result with Grade as per follows :

    Avg Grade>=85 A>=75 & < 85 B>=65 & < 75 C>=50 & < 65 D nm; cout > rn; cout > m1; cout > m2; cout

  • 41

    cin >> m3;}

    void resultCalculation(){

    tot = m1 + m2 + m3; avg = (float)tot / 3;

    if(avg >= 85)grd = A;

    else if(avg >= 75)grd = B;

    else if(avg >=65)grd = C; else if(avg >=50)grd = D; else

    grd = F;}

    void printResult(){

    cout

  • 42

    {

    int x = 5;

    { Block1 int x = 10; Block2

    }}

    Declaration of x refers to to two different memory locations containing different values. Variable xdeclared in block2 cannot refer to the variable x declared in the first block and vice versa.

    R Declaration of the same variable in inner block hides a declaration of the same variable inan outer block.

    Global version of variable is not accessible within the inner block, if inner block contains same name localvariable in it. To overcome the problem C++, introduce new operator called the scope resolution operator( :: ).

    # include # include # include

    int I=5;void main(){

    clrscr();cout

  • 43

    Till now we have seen that we have defined function (body of the function) within the class. Some timesdue to more number of functions class becomes longer. To overcome the problem one can defined functionoutside of the class using Scope Resolution Operation ( :: ), only declaration is done within the class. Thiswill increase the readability of the class.The General form of a member function definition outside of the class

    return_type class_name :: function_name(arguments){

    function body}

    ExampleCreate a class called Series to print odd or even number series depends value passed. If number is oddthen print odd number series till that number and same for even number.

    # include # include # include

    class Series{ public :

    void printSeries(int);};

    void Series :: printSeries(int n){

    if ((n % 2) == 0){

    for(int I=1;I

  • 44

    void main(){

    clrscr();Series s1;s1.printSeries(12);cout

  • 45

    cout

  • 46

    Double dbl(){

    Double dd;

    dd.a = a * 2;dd.b = b * 2;

    return dd;}

    };

    void main(){

    Double d1,d2;d1.setData(10,20);d2.setData(0,0);

    cout

  • 47

    Constructor and Destructor

    In C++, initialization of the member variable is not possible at the time of the declaration within a Class.Initialization ensures that variable having such meaningful value in it rather than junk value.

    Example

    # include # include # include

    class test{ public :

    int I,J;

    public :

    void viewData(){ cout

  • 48

    Constructor

    To overcome the above problem one has to define variable and then assign a value to it later in theprogram using assignment operator as shown in above example.

    Other way when you create an object of the class, it can initialize itself, without the need of separatestatement in the program. Automatic Initialization of object is possible using a special member functioncalled a Constructor.

    Constructor is a one kind of special member function of class with no return type, not even void. Itsname is same as the class name. It is called automatically when we create an instance (object) of theclass. It should be declared under category of public access specifier.

    When your class is having constructor, it is guaranteed that when you create an object of class it will callconstructor and execute all the statement written as a body of the constructor.

    Example

    # include # include # include

    class test{

    int I,J;

    public :test() // Constructor{ I = 10; J = 10;}void viewData(){ cout

  • 49

    Example

    # include

    int I = 0; //Global Variable

    class test{ public :

    test() //Constructor{

    I++;cout

  • 50

    public :Series(){ start=1; end=10; step=1;

    }

    Series(int s, int e){ start = s; end = e; step = 1;}

    Series(int s, int e, int st){ start = s; end = e; step = st;}

    void printSeries(){ int I = start;

    cout

  • 51

    The default value of argument y is 5 then the statement:

    Test t1(10);

    Assigns the value 10 to x and 5 to y (by default). While,

    Test t2(10,7);

    Assigns the value 10 to x and 7 to y. The actual parameter when specified, overrides the default value.

    Copy Constructor

    Such time it is required to copies all the value of one object to another object of same class. For that werequire to copy each member of a one object to another object separately. In C++ one object of the anyclass may be copied to another object of the same class, either through assignment or argument association.This is known as Copy Constructor.

    The copy constructor is called every time a copy of an object is made. All copy constructors take oneparameter, a reference to an object of the same class.

    class Test{

    -

    public :Test(Test &t) // Copy Constructor-

    -

    };

    The copy constructor simply copies each member variable from the object passed as a parameter to themember variables of the new object.

    class Test{

    int i;

    public :Test(Test &t){ i = t.i;}

    };

    As per above discussion, a copy constructor is used to declare and initialize an object from another object.This can be happened using

  • 52

    Test t2(t1); orTest t2 = t1;

    Above statement will create new object t2 and at the same time initialize value of t1.

    Test t2 = t1; statement is also known as copy-initialization.

    Remember the statementt2=t1 ;

    will not invoke the copy constructor. But it simply assigns values of all the member variables of t1 objectto t2.

    Following example illustrate use of copy constructor.

    # include class Test{

    int i;int j;

    public :

    Test() { } //Constructor

    Test(Test &t) // Copy Constructor{ cout

  • 53

    t1.setData(10,20);cout

  • 54

    pointer_variable = new data_type

    Here pointer_variable is a pointer of type data_type. The new operator allocates sufficient memory tohold a data object of type data_type and returns the address of the object.e.g.

    int *p = new int;

    declare object p. new will allocate necessary to store integer variable in it. (i.e. 2 bytes)

    *p = 10

    will assign 10 to above created object p.One can combine above to separate statement in a single statement using :

    int *p = new int(10);One can allocate memory to array and another user-defined data types like structure and class using newoperator.General form to create single-dimensional array is

    pointer_variable = new data_type[size];

    Here, size specifies number of elements in the array.

    The delete operator does the reverse of new operator. It de-allocates the memory. When data object isnot required in the program we can destroy it using delete operator and release the occupied memory bythe object to reuse it. The General form to delete the object is :

    delete pointer_variable;

    To release memory of dynamically allocated array following statement is used.delete [] pointer_variable;

    Following program illustrate the use of the new and delete operators:

    #includeint main(){

    char *name;name = new char[31]; //Allocates 31 bytescout

  • 55

    Note the use of the delete operator:delete []name;

    The preceding statement indicates that all the bytes allocated by the new char[] statement are de-allocated.

    if you write:delete name;

    then only the first byte is de-allocated, and the rest of the bytes are wasted. Some compilers may evengive an application error.

    Destructor

    Some times variable is not required after its scope. In such case it is good practice to released unwantedvariables memory. It is possible using Destructor.

    Destructor is a one kind of special member function of the class. Its name is same as class namepreceding with tilde (~) sign. A destructor never takes any argument nor returns any value. It is calledautomatically when your object moves out of scope. It should be declared under category of public accessspecifier. One cannot overload the Destructor.

    It will be invoked implicitly by the compiler upon exit from the program or block as the case may be.Generally it is used to clean up the storage that is no longer required. It is good practice to declaredestructors in a program since it releases memory space for future use.

    Example

    # include # include

    class Test{ public :

    char msg[20];

    Test(char m[]) // Constructor{ strcpy(msg,m);

    cout

  • 56

    {cout

  • 57

    {static int sta;int normal;

    public:void setData(int i){

    normal=i;sta++;

    }

    void display(){cout

  • 58

    First notice that, following statement in the program used for define static data member. i n ttemp :: sta;

    Note that variable sta is initialized to zero when the objects are created.When sta is incremented the datais read into object. Here three objects (t1,t2,t3) read variable Three times, the variable sta is incrementedthree times. Because there is only one copy of sta shared by all the three objects.

    Following figure shows how the objects use static variable.

    Sharing of a static data member

    While defining a static variable, some initial value can also be assigned to the variable. For instance, thefollowing definition gives sta the initial value 9.

    int temp :: sta = 9;

    Static Member Functions

    We can also have static member functions. A member functions that is declared static has the followingproperties.

    A static function can have access to only static member ( functions or variables ) declared in thesame class.

    A static member function can be called using the class name as follows. Here you need not tocreate a object, to call the member function of the class

    class-name :: function-name; // instead of its objects

    Example

    #includeclass temp{

    int sim;

  • 59

    static int sta;

    public:

    void setData(){

    sim=sta++;}

    void showSimple(){

    cout

  • 60

    Simple member = 1 Static member =2

    Friend Function

    Till now, we are not able to access private member outside the class. But we can access private memberoutside the class using friend functions.

    Imagine that you want a function to operate on objects of two different classes. Perhaps the function willtake objects of the two classes as arguments and operate on their private data. In this situation theresnothing like a friend function.

    To make an outside function friendly to a class, we have to simply declare this function as a friend ofthe class as shown below:-

    class XYZ{

    ..

    ..

    public:

    friend void fr(); // declaration};

    void fr(){

    // Definition of friend function}

    The function declaration should be preceded by the keyword friend. The function is defined elsewhere inthe program like a normal function.

    R A friend function, although not a member function, has full access rights to the privatemembers of the class.

    Some Special characteristics of friend function

    It is not in the scope of the class in which it has been declared as friend. (i.e. It is not a memberfunction of the class)

    Since it is not in the scope of the class, it cannot be called using the object of that class. It caninvoke like a normal function without the help of any object.

    Unlike member function, it cannot access the member names directly and has to use an object

  • 61

    name and dot membership operator with each member name. It can be declared either in the public or the private part of a class without affecting its meaning. Usually, it has the objects as arguments.

    Following program illustrates the use of a friend function.

    Example

    #includeclass circle{

    int r;

    public:void setRadius()

    { r=9;}

    friend float Area(circle c);// Friend of circle};

    float Area(circle c){

    return 3.14*c.r*c.r;}

    main(){

    circle c;c.setRadius();cout

  • 62

    Example

    #include

    class second;

    class first{

    int id;public:

    void getId(){

    coutid;

    }

    void getResult(second);

    };

    class second{

    int marks;public:

    void getMarks(){

    coutmarks;

    }

    friend void first :: getResult(second);

    };

    void first :: getResult(second s){

    cout

  • 63

    f.getId();s.getMarks();

    cout

  • 64

    class beta{

    int data;public:

    void setBeta(){

    data=6;}int sum(alpha a){

    return data+a.data1;}

    };

    main(){

    alpha a;beta b;a.setAlpha();b.setBeta();cout

  • 65

    public:void setFirst(){

    x=7;}

    friend int max(first,second);};

    class second{

    int y;public:void setSecond(){

    y=5;}

    friend int max(first,second);

    };

    int max(first f,second s){

    if(f.x > s.y)eturn f.x;

    lseeturn s.y;

    }

    main(){

    first f;second s;

    f.setFirst();s.setSecond();

    cout

  • 66

  • 67

    Operator Overloading

    A = B + C;

    Generally above statement used with basic data types. Suppose A,B and C are an object of any user-defined class than above statement will generate error. But one can make above statement correct usingoperator overloading when A,B and C are an object.

    Operator overloading is one form of important feature of C++ language called as Polymorphism. As youaware polymorphism means many form. So, operator can be overloaded to perform different operationson different data types in different contexts.

    In C++, operator overloading creates new definitions for operator and you can change them to do whateveryou want. The mechanism of giving such special meanings to an operator is known as operatoroverloading.

    Operator overloading occurs with special function of C++, called operator function. The General form ofan operator function is

    return_type operator op(argument_list){

    function body}

    where, return_type indicates value return by the operator function. op is the any valid operator, which wewant to overload. operator is reserve word.

    Operator function must be a member function of class and declared in the category of public accessspicifier. It has a no argument for unary operators and one argument for binary operator.

    Unary Operator Overloading

    As we aware that ++, and (unary) operator are categorized in the group of unary operator. Unaryoperator operates on one operand. So, when it is applied with variable it is restricted to change the valueof only one variable. But when it is used with object it can be change more than one variables value. Now,lets look how to overload this operator so that it can be applied to an object in much the same as is applied

  • 68

    with variable.

    Following Example illustrate use of Unary Operator Overloading.

    #include

    class Test{ int i,j;

    public :void setData(int x,int y)

    { i = x; j = y; }

    void viewData() { cout

  • 69

    Example

    Create a Time class, which is used to display time in a proper format. Time class also having memberfunctions to get and set time. In these class Overload increment operator so that it will increase time by 1second.

    # include class Time{ int hh,mm,ss;

    public : void viewTime(); void setTime(int,int,int); void getTime() { cout hh; cout > mm; cout > ss; }

    void operator ++() { if(ss < 59) { ss++; } else {

    if(mm < 59) { ss = 0; mm++; } else { if(hh < 23) { ss = mm = 0; hh++; } else { ss = mm = hh = 0; } } } }};

    void Time :: viewTime()

  • 70

    { cout

  • 71

    } Test operator ++() { int a = i * 2; int b = j / 2;

    Test temp ;temp.setData(a,b) ;return temp;

    }};

    void main(){

    int a,b;cout > a;cout b;

    Test t1,t2;t1.setData(a,b);t2.setData(0,0);

    cout

  • 72

    class Test{ int i,j; public :

    void setData(int x,int y){ i = x; j = y;}

    void viewData() { cout

  • 73

    Return Value with Binary Operator Overloading.

    Example

    #include

    class Test{ int i,j;

    public :void setData(int x,int y){ i = x; j = y;}

    void viewData() { cout

  • 74

    class Test{ public :

    int i,j;

    void setData(int x,int y){ i = x; j = y;}

    void viewData() { cout

  • 75

    Returning Object with Binary Operator Overloading.

    Example

    #include

    class Test{ public :

    int i,j;void setData(int x,int y)

    { i = x; j = y;}

    void viewData() { cout

  • 76

    t1.viewData();cout

  • 77

    hh = hh + b;

    if(hh > 23) { c = hh % 24; hh = c; } } } }};void main(){ Time t1; t1.hh = 23; t1.mm = 55; t1.ss = 39; t1.viewTime(); t1 + 500; //500 Seconds added to Time object. t1.viewTime();}

  • 78

  • 79

    Inheritance

    Inheritance is a most powerful feature of OOP. Inheritance is the process by which one object acquiresthe properties of another object. It is always nice if we could reuse something that already exist ratherthan trying to create the same all over again. It would not only save time and money but also reducefrustration and increase reliability.

    This is important because it supports the concept of hierarchical classification. Consider dog, it is part ofmammal class, which is under the largest class animal. Without the use of hierarchies, each object wouldneed to define all of its characteristics explicitly. However, by use of inheritance, an object need onlydefine those qualities that make it unique within its class. It can inherit its general attributes from itsparent.

    As per above discussion, In C++ one can create new class from an existing class. In such case new classis known as a derived class while existing class is know as base class. Derived class inherits partial or allthe properties of its base class and may (Derived class) have another add-ons properties.

    Inheritance has important advantages. It permits code reusability. Once a base class is written andtested, it need not be touched again. As per requirement programmer can be utilized it. Using inheritanceconcept, A Programmer can use a class created by another programmer and using inheritance it can addsome more functionality as per requirement.

    Creation of Derived Class

    One can create derived class with the relationship of their base class as per follows.

    class derived_class_name : access_specifier base_class_name{ -

    -

    -

    };

    where, access_specifier may be either private or public. It is optional. If we have not mentioned anyaccess_specifier, by default it is private.

  • 80

    e.g.class ABC : public XYZ{ -

    -

    };

    class ABC : public XYZpronounced as class ABC is publically derived from class XYZ.

    According to following figure Base class is having two properties and two methods. This class can workindividually. Derived Class is inheriting property and method of Base Class, so derive class is havingsame property as Base Class plus it is also having its own property and method.

    Example

    #includeclass Emp{ public :

    int empno;char name[20];

    void getData(){

    coutempno;

  • 81

    coutname;

    }void putData()

    {cout

  • 82

    class temp{ protected :

    int num1 ;void showData(); //prototype of function

    public:int num2;void getData(); // prototype of function

    };

    void main(){

    temp t; // define object of temp classt.num1=5; // error , num1 is privatet.num2=9 // OK, num2 is public

    t.showData(); // error , showData() is protected.t.getData() // OK, getData() is public

    }

    In the above example, num2 and getData() are public member of the class so, we can access them out ofclass using object. num1 and showData() are protected member of class so, we cannot access them outof the class.

    Access Specifier in Derivation

    When your derived class is publically inherited from base class, Private members are not inherited. public members of base class remains public in derived class. protected members of base class remains protected in derived class.

    When your derived class is privately inherited from base class, No inheritance made of private members. public members of base class becomes private in derived class. protected members of base class becomes private in derived class.

    When your derived class is protectedly inherited from base class, No inheritance made of private members. public members of base class becomes protected in derived class. protected members of base class remains protected in derived class.

    As you aware, public members of a class can be accessed by its own object using a dot operator.protected and private member of a class cannot accessible by its own object, but it can be accessible by

  • 83

    another members of that class.Example

    # include

    class A{ int a; public :

    int b; protected :

    int c;};

    class B : public A{ int d;};

    In above example class B is publically inherited from class A. So, class B consist member variable b asa public and c as a protected of class A.

    Example

    # include

    class A{ int a; public :

    int b; protected :

    int c;};

    class B : private A{ int d;};

    In above example class B is privately inherited from class A. So, class B consist member variable b andc of class A as a private in it.

    Example

    # include

    class A

  • 84

    { int a; public :

    int b; protected :

    int c;};

    class B : protected A{ int d;};

    In above example class B is protectedly inherited from class A. So, class B consist member variable band c of class A as a protected in it.

    Overriding Member Functions

    You can use member functions in a derived class that have the same name as those in the base class is knownas Overriding. You might want to do this so that calls in your program work the same way for objects of bothbase and derived classes. Here is an example of class Employee which is having method called getData() andputData(). Manager Class is derived from Employee class and having the same name of methods getData()and putData() as of Base Class.

    Example:

    class Employee{

    public:int empno;char name[10];

    void getData(){

    coutempno;coutname;

    }

    void putData(){

    cout

  • 85

    class Manager : public Employee{

    private:int sal;

    public:void getData(){

    Employee::getData();//To use method of base classcoutsal;

    }void putData()

    {Employee::putData();//Valid Statement Public Methodcout

  • 86

    derived class B is known as Intermediate Base Class since it provides a link for the inheritance between Aand C.

    A derived class with multilevel inheritance is declared as follows:

    class base{ . };class derive1 : access_specifier base_class{ . };class derive2 : access_specifier base_class

    (which is derived class of some another base class){ . };

    This process can be extended to any number of levels.

    Following Example illustrate the concept of multilevel inheritance.

    class Employee{ public :

    int emp_no;char emp_nm[20];

    void getEmployee(){ coutemp_no;coutemp_nm;

    }

    void viewEmployee(){ cout

  • 87

    cin>>sal;}

    void viewSalary(){

    cout

  • 88

    Multiple Inheritance

    C++ language is the ability to inherit methods and variables from two or more parent classes when building anew class. This is called multiple inheritance.

    The class A and class B is a Base Class for the class C. So, derived class C is having all the characteristic ofBase Class A and B. Multiple Inheritance allows us to combine the features of several existing classes.

    The syntax of a derived class with multiple base classes is as follows:

    class derive_class : access_specifier base_class1,access_specifier base_class2 ...

    {

    };

    Example

    class A // Base Class A{

    protected:int a;

    public:void getA(int x)

    {a=x;}

    };

  • 89

    class B // Base Class B{

    protected:int b;

    public:void getB(int x)

    {b=x;}

    };

    class C : public A, public B // C is Derived from A and B{ int c; public:

    void getC(int x){c=x;}

    void Disp(){

    cout

  • 90

    should be avoided using virtual base class.

    Virtual Base Class

    The duplication of inherited members due to multiple parents can be avoided by making the common base class(ancestor class) as virtual base class while declaring the direct or intermediate base classes as shown below:

    class A //Grandparent{

    .

    .

    };

    class B1 : virtual public A //Parent1{

    .

    .

    };

    class B2 : virtual public A //Parent2{

    .

    .

    };

    class C : public B1, public B2 //child{

    . //only one copy of A will be inherited..

    };

    When a class is made a virtual base class, C++ takes necessary care to see that only one copy of that class isinherited, regardless of how many inheritance paths exist between the virtual class and a derived class.

    R The keywords virtual and public may be used in either order.

    Example

    # include class Cricketer{ protected :

    char nm[25];char team[20];

  • 91

    void getName(){ coutnm;coutteam;

    }};

    class Bowler : virtual public Cricketer{ protected :

    int wicket; public :

    void getWicket(){

    coutwicket;

    }};

    class Batsman : public virtual Cricketer{ protected :

    int runs; public :

    void getRuns(){

    cout> runs;

    }};

    class All_Rounder : public Bowler, public Batsman{ public :

    void getDetails(){

    getName(); getWicket(); getRuns();

    }void viewDetails()

    {cout

  • 92

    cout

  • 93

    OutputHello from Class AHello from Class B

    In case of multiple inheritance, constructor is executed in order of base class used in declaration of derivedclass.

    Example

    # include # include

    class A{ public :

    A(){ cout

  • 94

    Example

    # include # include

    class A{ public :

    A(){ cout

  • 95

    Hello from Class CHello from Class D

    However, if any base class contains a constructor with one or more arguments with default constructor and onewant to execute a constructor with parameter from a derived class then it is mandatory for the derived class tohave a constructor and pass the arguments to the base class constructors.

    # include # include

    class A{ public :

    A(){ cout

  • 96

  • 97

    PointersNeed of Pointers

    Suppose you are writing a program that accepts from a user the scores of the students in a class. The programcalculates the average score and displays a sorted list of all the scores. You will need to store the scores ofstudents in an array. Assuming there are fifty students in a class, you can create an integer array, as givenbelow:

    int scores[50];

    You will compile the program containing the above statement and give it (or sell it!) to all the schools. Howeverthere is a problem every school has a different number of students per class. You may think of followingsolutions:

    Write a different program for each school. There are a hundreds of them! Locate the school with the highest number of students and define an array containing this number of

    elements. For example:

    int scores[80];

    The program will now allocate 80 * 2 = 160 bytes of memory. But, what if there are only five students perclass? The remaining bytes would be wasted. What if numbers of students are increase from eighty to hundred?You would rewrite, recompile and redistribute the modified program to every school.

    The way to solve this problem is through the allocation of the required memory at the time of execution. This isknown as dynamic allocation of memory. This can only be achieved with the help of a special type of variable,a pointer variable, also called pointer. A pointer is a variable that stores the memory address of anothervariable, rather than its stored value.

    Most of the programming languages use pointer variables. However, some languages like Java hide their usefrom the programmer.

    Use of Pointer

    Here are some common uses:

    Accessing array elements Passing arguments to a function when the function needs to modify the original argument

  • 98

    Passing arrays and strings to functions Obtaining memory from the system In database programs, where the number of records to be stored is unknown at the tome of designing

    the database. Heavily used in any software like an operating system, which interacts directly with the hardware.

    Advantages of using the pointer

    The various advantages of using the pointers are:

    Pointers allow direct access to individual bytes in the memory. Thus, data in the memory is accessedfaster than through ordinary variables. This speeds up the execution of program

    Pointers allow direct access to the output devices like the monitor. This speeds up program that aregraphic-intensive.

    Pointes allow the program to allocate memory dynamically, only when required, with the help of newoperator. They also allow the program to free the memory when it is no longer required. This is donewith the help of delete operator. You have already seen it in past.

    Pointer Variable

    The ideas behind pointers are not complicated. Heres the first key concept: every byte in the computersmemory has an address (location number). Addresses are numbers, just as they are for houses on a street.The numbers start from 0 and go up from there1, 2, 3, and so on. If you have 640k of memory, the highestaddress is 6,55,359; for 1 MB of memory, it is 10,48,575.

    Consider the following definition and initialization of a character variable:

    char var3 = B;

    The above definition will reserve a byte in memory (char variables needs only one byte), name the byte asvar3, and place the character B in that byte. You may represent the variable, var3, int the memory as:

    1000 address of the variable

    B value of the variable

    var3 Name of the variable

    To obtain the address of a variable, the & (address of) operator must be used before the variable name.

    The following program displays the address of a character variable, var3:

    #includeint main(){

  • 99

    char var3=B; cout

  • 100

    The next program shows the syntax for pointer variables:#includevoid main(){

    int var1 = 5;int var2 = 10;

    //following statement print address of variablescout

  • 101

    p1++; //points next variable after a (i.e. b)p1; //points previous variable

    the following operations cannot be performed on a pointer; they result in a compilation error:

    Addition of two pointers Multiplication of two pointers Division of a pointer by a number

    Pointers and Arrays

    As you have seen previously, an array is a collection of elements of a single data type stored in adjacentmemory locations. The name of an array is resolved by the compiler to yield the base address (address of theelement number [0] of the array). The base address of an array cannot be changed because it is a constantvalue.

    If an Integer variable occupies two bytes of memory, then each element of an integer array would also occupytwo bytes. Assume that a pointer is assigned the address of the starting element of the array.

    Consider the following program:

    #include

    int main(){

    int numarr[] = {10, 20, 30, 40};

    int *ptr= numarr;cout

  • 102

    Pointers to Objects

    Pointers, as seen earlier, can be made to point to objects as well. The usage of pointer with classes is exactly likethat of its usage with structures. As with Structures the Arrow operator (->) can be used to access membersof the class.

    Like Student st; declare st as a object of class Student. We can define a pointer object of class Student asper follows.

    Student *pst;

    Object pointers are useful in creating objects a t run time.

    #include

    class Student{

    private:int rn;char nm[20];

    public:void getData(){

    cout > rn;cout > nm;

    }

    void viewData(){

    cout

  • 103

    When we create an object of our class, the member functions of class can access using dot operator, whilearrow operator is used for object to pointer to access the member functions or variables.

    In above example pointer pst is initialized with the address of st object.

    new operator is also used to create pointer object as follows.

    Student *ptr_st = new Student;

    Above statement allocates necessary memory space for the data members in the object and assigns the addressof the memory space to ptr_st.

    We can create an array of objects using pointers as per follows.

    Student *ptr = new Student[10];

    Create memory space for an array of 10 object of Student and point to the first object.

    Example :

    #include

    class box{ int length; int width;public: box(void); //Constructor void set(int new_length, int new_width); int get_area(void);};

    box::box(void) //Constructor implementation{ length = 8; width = 8;}

    void box::set(int new_length, int new_width){ length = new_length; width = new_width;}

  • 104

    int box::get_area(void){ return (length * width);}

    int main(){

    box small, medium, large;box *point; //A pointer to a boxsmall.set(5, 7);large.set(15, 20);

    point = new box; cout

  • 105

    B b1;D d1;ptr = &d1;

    However, pointer can sometimes problematic with inheritance. When base class pointer points to derived classobject, it can access only those members of base class, which is inherited. It cannot access any member ofderived class. The following example illustrates problem occurs with inheritance.

    #include #include

    class B{ public:

    int b;

    void show(){ cout

  • 106

    bptr->show();}

    Output

    Base Classb : 5Base Classb : 5Base Classb : 10

    In Inheritance, when pointer of base class points to derived class object and member of derived class having thesame name as the members of base class, then any reference to that member by pointer will always access thebase class member.

    #include #include

    class B{ public:

    void show(){ cout

  • 107

    clrscr();B *bptr;B b1;

    D1 d1;D2 d2;

    bptr=&b1;bptr->show();

    bptr=&d1;bptr->show();

    bptr=&d2;bptr->show();

    }

    Output:

    Hello from Base ClassHello from Base ClassHello from Base Class

    Above example contains a base class called B. Two other classes D1 and D2 are derived from this baseclass.

    In the function main() we have declared a pointer to the base class and two object of derived class D1 and D2respectively. Pointer to base class is assigned with the address of both the derived class object.

    When we assign the address of the derive class to the pointer of the base class, the function from the base classis executed. Because objects of derived classes are type-compatible with pointers of base class. So, compilerignores the contents of the pointer and chooses the function from the same class as that of the pointer.

    This problem is solved using virtual function.

    Virtual Functions

    Virtual means existing in effect but not in realty. A virtual function is one that does not really exist but neverthelessappears real to some parts of a program. Late binding is implemented by the use of the virtual keyword withinthe class hierarchy. A function is declared as virtual in the base class, and in each subclass, a function with thesame name is coded. When such functions are invoked using a base class reference or a pointer, the actualfunction invoked depends on the type of the object, which is referenced.

    Syntax

    virtual ();

  • 108

    Example

    #include #include class B{ public:

    virtual void show(){ cout

  • 109

    Output:

    Hello from Base ClassHello from Derived Class1Hello from Derived Class2

    Example

    #includeclass Person{protected:

    char name[20];char city[15];

    public:virtual void accept(){

    cout name;

    cout city;

    }virtual void display()

    {cout

  • 110

    }};class Dealer : public Person{private:

    int price;public:

    virtual void accept(){

    Person::accept();cout > price;

    }virtual void display(){

    Person::display();Cout

  • 111

    class D1 : public B{ public :

    void show(){ cout

  • 112

    class Derv1 : public Base //derived class 1{

    public :void show( )

    { cout show( );

    }

    Now the virtual function is declared as

    virtual void show() = 0; //pure virtual function

    The equals sign here has nothing to do with assignment; the value 0 is not assigned to anything. The =0 syntaxis simply how we tell the compiler that a function will be pure that is, have no body.

    You might wonder, if we can remove the body of the virtual show( ) function in the base class, why we cantremove the function altogether. That would be even cleaner, but it doesnt work. Without a function show( ) inthe base class, statements like

    bptr -> show( );

    Would not be valid, because the pointers bptr must point to members of class Base.

    Abstract Classes

    An abstract class often defined as one that will not be used to create any objects, but exists only to act as a baseclass of other classes. Ellis and Stroustrup tighten up this definition by requiring that, to be called abstract, a classmust contain at least one pure virtual function.

  • 113

    File Handling in C++

    In C++, Input and Output system is designed in such way to work with all kind of devices includingterminals, disks and tape drives. C++ I/O system provides a common interface to handle I/O operations.This interface is independent from actual device although each device is different. This interface isknown as stream.

    A stream is a sequence of bytes; act either as a source from which the input data can be obtained or as adestination to which the output data can be sent. So, A Stream is a source or destination for a collectionor a flow of data.

    There are two kinds of streams:

    Output streams : Allow you to write or store charactersInput streams : Allow you to read or fetch characters

    The input and output capabilities of C++ streams are derived from the fact that each stream is associatedwith a particular class. For example, the input streams are associated with the istream class and theoutput streams are associated with the ostream class. Each class contains its own data members, functions,and definitions for dealing with the data in a particular stream.

    The figure below shows the hierarchy of the stream class library.

    Stream Class Hierarchy

    The ios class is a base class of the stream class hierarchy. It defines the basic format for input/put anderror control procedures. The istream and ostream are derived from it.

    ios

    istream ostream

    iostream

  • 114

    The istream (input stream) class is used to define the format in which data is received from the keyboard(standard input device).

    The ostream (output stream) class is used to define the format in which data is displayed on the VDU(standard output device).

    The iostream (inout and output stream) class is derived from the istream and ostream classes throughmultiple inheritance. Therefore, it inherits both the input and output attributes.

    File Class Hierarchy

    C++ provides File stream classes that are used to access disk files. The figure given below shows thestream class hierarchy that provides file input and out capabilities.

    The three class deals with file input and output are:

    fstream : Is derived from iostream and is used for both file input and outputifstream : Is derived from istream and is used for file input (reading)ofstream : Is derived from ostream and is used for file output (writing)

    The I/O System of C++ handles file operations, which are very much similar to the console input andoutput operations. It uses file streams as an interface between the programs and the files. Input streamextracts (or reads) data from the file and the output stream inserts (or writes) data to the file.

    All above classes, designed to manage the disk files, are declared in fstream.h and therefore we mustinclude this file in any program that uses files.

    Types of Files

    The files in C++ can be differentiate based on its storage. One can store file in text form or one can storefile in binary form. In a text-based file, the information is stored in the same format as it is displayed on

    ios

    istream ostream

    iostream

    ifstream ofstream fstream

  • 115

    the screen. The files using binary input and output save data in actual representation of the data type.

    Opening and Closing a file

    If we want to use a disk file, we need to decide the following things about the file and its intended use : Suitable name for the file Data type and structure Purpose Opening method

    The file name is a string of characters that make up a valid filename for the operating system. It containstwo parts, a primary name with optional secondary name.

    As stated earlier, for opening a file, we must first creat a file stream and then link it to the filename. A filestream can be defined using the classes ifstream, ofstream and fstream that are contained in the headerfile fstream.h. The class to be used depends upon purpose, whether we want to read data from the fileor write data to it.

    A file can be opened in two ways : Using the constructor function of the class. Using member function open() of the class.

    Opening files using constructor

    As we aware constructor is used to initialize an object while it is being created. Here, a filename is usedto initialize the file stream object.

    To, create an output file using class ofstream

    ofstream ofile(student); //output only (Writing Purpose)

    Above statement will creates ofile object of ofstream that manges the output stream. This statement alsoopens the file student and attaches it to the output stream ofile.

    Similarly, the following statement declares ifile as an ifstream object and attaches it to the file data forreading.

    ifstream ifile(student); //input only (Reading Purpose)

    Let us first start of creation of file.

    Example

    # include

  • 116

    void main(){

    ofstream ofile(ABH.TXT); // Creates a file for output

    ofile

  • 117

    Open file with open() function

    you can open a file for writing as well as reading by using the open() function.

    Example

    ofstream ofile;ofile.open(data.dat); //Associates the stream to a File

    Here, an object named ofile of the ofstream class is created. The constructor of the ofstream class isinvoked with the value, data.dat. When the scope of the ofstream in a program is over, the destructor ofthe ofstream class is automatically called, and the file is closed.

    ofstream ofil;ofil.open(data.dat,ios::app); //Associates the stream to a File

    Here, first parameter for the open() function is the name of the disk file and the second parameter impliesthe way a file should be opened. ios::app indicates that the file should be opened in the append mode.

    Getting the Right Path

    If your input file is not stored in current working directory, you may need to use an operating system pathto locate it. For the DOS and Windows operating systems, which use \ to separate directory names, theescape sequence \\ (two backslashes) must be used to specify full path names. So the file name mayappear like this:

    ifstream inFile(C:\\myFolder\\mySubFolder\\myFile.dat);

    where \\ represents only one backslash. Omitting one \ from \\ is virtually guaranteed to result in notfinding the file.

    This problem dosent exists in Unix, Linux as the / character is used to separate directories, and so / canbe used as is.

    Open Mode Bits

    Each stream has a series of bits or flags associated with the operations. These bits are defined in the iosclass. The bits that are associated with the opening of files are called open mode bits. These bits representthe mode in which the file is opened. If the file is opened in the output mode, a particular mode is set on.Likewise, if the file is opened in the input mode, another bit is set on. Collectively, these bits state themethod in which the file is to be opened. The following statement opens a file in the input and outputmodes:

    fstream fil(data.dat,ios::in | ios::out);

  • 118

    in and out bits means that the object, fil, has to be opened for both writing and reading. The pipe ( | ) is thebitwise OR operator. When the program encounters this statement, these two bits are set ON in the bitstream and, therefore, allow the file to be opened in either input or output mode.

    The following table shows the file opening modes:

    Mode Explanationapp Starts reading or writing at the endin Opens for readingout Opens for writingate Seeks the end-of-filetrunc Truncates a file if it exists

    Reading and Writing File Character by Character

    The put() and get() functions, which are member functions of ostream and istream respectively are usedto output and input a single character at a time.

    .put();.get();

    Example

    # include # include

    void main(){ char st[]=AZURE Research Team;

    ofstream ofile(test.txt); for(int I=0; I

  • 119

    # include # include

    void main(){ char st[]=AZURE Research Team;

    fstream fl(test.txt, ios::out);

    for(int I=0; I

  • 120

    It expects two parameters:

    The address of the object that contains the data to be written to the file

    The size of the object that is to be written to the file

    The following program accepts one set of data and writes it to a file using the write() function.

    #include

    class bill{ char cust_nm[30]; float bill_amt;

    public :void getData(){ cout

  • 121

    put pointer specifies the location in the file where the next write operations will occur. i.e., from whichpoint in the file next record will be written.

    The seekp() function moves the put pointer to an absolute address within the file or to a certain number ofbytes from a particular position.

    The seekp() function takes two arguments:

    The number of bytes after which the pointer is to be positioned. The reference in the file to which the put pointer has to be positioned

    Exampleofstream ofil;ofil.seekp(10,ios::beg);

    the above code positions the put pointer 10 bytes from the beginning of the file.

    There are three reference points defined in the ios class:

    ios::beg Beginning of the fileios::cur Current position of the file pointerios::end End of the file

    The tellp() Function

    The tellp() function returns the current position of the put pointer. It returns exactly at what position putpointer is located whether it at the end of file or at the beginning or some where in the between. It is usefulas you come to know from where next write action will be performed.

    Exampleint position;ofstream ofil;

    ofil.seekp(0,ios::end);position = ofil.tellp();if(position == 0){

    cout

  • 122

    This function is called with two arguments. These are: The address of the variable into which the data hasto be read and the size of the variable

    Syntax

    read((char *) addr, int size);

    The following program illustrates the use of the read() function to read one record from a file.

    #include

    int main(){

    bill billobj;ifstream ifile(billfile.dat);ifile.read((char *)&billobj,sizeof(billobj));billobj.showdata(); //displays the data on the screenreturn 0;

    }

    There are other ways of reading from a file. The get() member function to the ifstream class reads astring, one character at a time, from a file.

    The ifstream class also provides the >> operator to read from a file.

    The seekg() Function

    Similar to the C++ output system, the input system also manages an integer value associated with a file.That is the get pointer, which specifies the location in the file, where the next read operations is to occur.The seekg() functions moves the get pointer to an absolute address within the file or to a certain numberof bytes from a particular position.The seekg() member function takes two arguments:

    The number of bytes after which the pointer is to be positioned. The reference in the file to which the get pointer has to be positioned.

    ifstream ifil;ifil.seekg(0,ios::end);

    the above code positions the get pointer at the end of the file.

    The tellg() Function

    The tellg() function returns the current position of the get pointer. It is used to verify that from whichlocation data will be extracted from the file and which number of record will be fetched from the file whennext read task is performed. It is also used to determine size of the file.

  • 123

    ExampleThis program finds the number or records in the file data.txt

    #include class student{private:

    int id;char name[20];char course[10];char centre[20];char city[15];

    public:

    void getdata(){

    cout id;cout name;cout course;cout centre;cout city;

    }

    void showdata(){

    cout

  • 124

    {cout

  • 125

    cout>city;

    }};

    int main(){

    Customer cobj;fstream file;char reply = Y;file.open(customer.dat,ios::out|ios::app);while(reply == Y || reply == y){

    cout

  • 126

    {coutid;coutname;cout>city;

    }void printdata(){

    cout

  • 127

    cout

  • 128

    case 2:{

    cobj1.modifyrec();break;

    }case 3:{

    cobj1.viewrec();break;

    }case 4:{

    exit(0);break;

    }default :{

    cout

  • 129

    Review Questions

    1) What are the differences between the function prototype and the function definition?2) Do the names of parameters have to agree in the prototype, definition, and call to the function?3) If a function doesnt return a value, how do you declare the function?4) If you dont declare a return value, what type of return value is assumed?5) What is polymorphism?6) What is function overloading?7) What is the use of inline function?8) What operators can/cannot be overloaded?9) Can I create a operator ** for to-the-powerof operations?10) Is it OK to convert a pointer from a derived class to its base class?11) Why cant my derived class access private : things from my base class?12) Explain the terms Static binding and Dynamic binding of member functions with examples.13) False is default value of Boolean variable . It is True/False.14) Can I make friend variable in c++ program. It is True/False.15) Refer following code. X variable is pubic . it is True/Flase.

    class simple{

    int x; };

    16) Runtime Polymorphism is possible in c++.17) Exception Handling is possible in c++.It is True/False.18) Can I make function in C++ macro. It is True/False.19) Following c++ keyword is True/False.

    Float20) Give the range of int variable.

    0 to 2560 to 255128 to 127128 to 128

    21) Following code is True/False.int *x;char s=&x;

  • 130

    22) Following two code ( 1 and 2 ) are same or not.sizeof(x)sizeof(int)

    23) Following expression is True/False.9+float(x)

    24) What does the following program segment displayfile.seekg(0,ios::end);cout

  • 131

    case 10:cout

  • 132

    return ( 3.14 * R * R );}float diameter(){

    return ( 2 * 3.14 * R );}

    }

    30) What are the advantages of function prototypes in C++?31) Describe the different styles of writing prototypes.32) What do you meant by overloading of a function? When do we use this concept?33) What is the difference between public , protected,private members of a class ?34) What can be the possible reason for declaring a member function as private?35) What is the basic difference between structures and classes in C++?36) When do we need to use default arguments in a function?37) How many types of function ? Exaplain.38) What is class ?39) What is object?40) What do you mean by static variable?41) What is a friend function?42) When is a friend function complusory? Give the example.43) Find out the pure virtual function.

    a. virtual void display=0;b. virtual void display()=0;c. virtual void display(){};d. all are wrong

    44) Give the advantages of destructors.45) Give the properties of the constructor.46) When I write a destructor, do I need to explicitly call the destructors for my member objects?47) What is a parameterized constructor?48) What is t