programming in c - srm · pdf fileprogramming in c. programming in c ... c is a programming...
TRANSCRIPT
PROGRAMMING IN C Introduction C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was designed and written by Dennis Ritchie. The C Character Set
The characters that can be used to form words, numbers and expressions depend upon the computer on which the program is run. The characters in C are grouped into the following categories:
1. Letters 2. Digits 3. Special characters 4. White spaces
The complete character set is given below
Letters • Uppercase A - Z • Lowercase a – z
Digits • All decimal digits 0 – 9
Special characters
, comma . period ; semicolon : colon ? question mark ‘ apostrophe “ quotation mark ! exclamation mark | vertical bar / slash \ backslash ~ tilde _ under score $ dollar sign % percent sign
# number sign & ampersand ^ caret * asterisk - minus sign + plus sign < opening angle bracket or less than sign > closing angle bracket or greater than sign ( left paranthesis ) right paranthesis [ left bracket ] right bracket { left brace } right brace
White spaces
• Blank space • Horizontal tab • Carriage return
© M. Anand 2
• New line
Identifiers and Keywords Identifiers are names that are given to various program elements,
such as variables, functions and arrays. The rules for identifiers are
1. Both uppercase and lowercase letters are permitted. 2. Digits 0 to 9. 3. They must begin with a letter. 4. Uppercase and lowercase letters are significant. 5. The underscore character (_) can also be included, and is
considered to be a letter. An identifier may also begin with an underscore.
6. The variable name should not be a keyword. 7. White space is not allowed.
The following names are valid identifiers X y12 sum_1 _temp names area
tax_rate TABLE Data Types C supports several different types of data, each of which may be represented differently within the computer’s memory. All C compilers support four fundamental data types,
• integer (int) • character (char) • floating point (float) • double-precision floating point (double)
The range of the basic four types are given below
PRIMARY DATA TYPES
Integral Type
Integer Character Signed Type Unsigned Type int unsigned int short int unsigned short int long int unsigned long int
singed char unsigned char
Floating Point Type
float double long double
© M. Anand 3
Data Type Range of values char -128 to 127 int -32,768 to 32,767 float 3.4e-38 to 3.4e+38 double 1.7e-308 to 1.7e+308
Integer Types Integers are whole numbers with a range of values supported by a particular machine. C has three classes of integer storage, namely short int, int, and long int, in both signed and unsigned forms. The following table shows all the allowed combinations of basic types and qualifiers and their size and range on a 16-bit machine. Floating Point Types Floating point (or real) numbers are stored in 32 bits, with 6 digits of precision. Floating point numbers are defined in C by the keyword float. When the accuracy provided by a float number is not sufficient, the type double can be used to define the number. A double data type number uses 64 bits giving a precision of 14 digits. Character Types A single character can be defined as a character (char) type data. Characters are usually stored in 8 bits of internal storage. The qualifier signed or unsigned may be explicitly applied to char. While unsigned chars have values between 0 to 255, signed chars have values from -128 to 127 Constants
Constants in C refer to fixed values that do not change during the execution of a program. There are four basic types of constants in C. Declarations A declaration associates a group of variables with a specific data type. All variables must be declared before using the variable in the program. The syntax of declaration statement is Data-type variable1,variable2,…,variableN; A declaration consists of a data type, followed by one or more variable names, ending with a semicolon. Example: int a,b,c; float pi,area,avg; char c; short int m1,m2,m3; long fact;
© M. Anand 4
unsigned x,y;
double root1,root2;
Initial values can be assigned to variables within a type declaration. To do so, the declaration must consist of a data type, followed by a variable name, an equal sign (=) and a constant of the appropriate type. Example: int a=10,b=20; char c=’*’; float sum=0.0; double factor=0,21023e-6; Input and Output Functions The printf() Function
The use of printf function for printing captions and numerical results. The printf function provides certain features that can be effectively exploited to control the alignment and spacing of print-outs on the terminals. The general for of printf statement is
printf(“control string”,arg1,arg2,…,arg-n);
control string consists of three types of items: 1. Characters that will be printed on the screen as they appear. 2. Format specifications that define the output format for display
of each item. 3. Escape sequence characters such as \n, \t, and \b.
The control string indicates how many arguments follow and what
their types are. The arguments arg1,arg2,…,arg-n are the variables whose values are formatted and printed according to the specifications of the control string. A simple format specification has the following form:
%w.p type-specifier where w specifies the total number of columns for the output value and p specifies the number of digits to the right of the decimal point or the number of characters to be printed from a string. Example:
printf(“Programming in C”); printf(“ “); printf(“\n”);
© M. Anand 5
printf(“%d”,x);
The scanf() Function The scanf function can be used to read formatted input. The general form of scanf is
The control string specifies the field format in which the data is to be entered and the arguments arg1,arg2,…,arg-n specify the address of locations where the data is stored. Control string and arguments are separated by commas.
Control string contains field specifications which direct the
interpretation of input data. It may include: • field (or format) specifications, consisting of the conversion
character %, a data type character (or type specifier), and an optional number, specifying the field width.
• Blanks, tabs, or newlines. Example:
scanf(“%d%c%f%s”,&count,&code,&ratio,name);
© M. Anand 7
scanf(“control string”,arg1,arg2,…,arg-n);
Operators And Expressions
An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. C operators can be classified into a number of categories. They include
1. Arithmetic operators 2. Relational operators 3. Logical operators 4. Assignment operators 5. Increment and decrement operators 6. Conditional operators 7. Bitwise operators 8. Special operators.
Arithmetic Operators C provides all the basic arithmetic operators. They are listed in the following table
Operator Meaning + Addition or unary
plus - Subtraction or unary
minus * Multiplication / Division % Modulo division
Relational Operators The relational operators are used to compare two values. An expression containing a relational operator is termed as a relational expression. The value of a relational expression is either one or zero. C supports six relational operators. These operators and their meanings are shown in the following table
Operator Meaning < Is less than <= Is less than or equal to > Is greater than >= Is greater than or equal to == Is equal to != Is not equal to
== and != relational operators are also known as equality operators. A simple relational expression contains only one relational operator and takes the following form
expression1 relational-operator expression2
© M. Anand 8
Logical Operators In addition to the relational operators, C has three logical operators. They are
Operator Meaning && Logical AND || Logical OR ! Logical NOT
The logical operators && and || are used when we want to test more than one condition and make decisions Conditional Operator (Ternary Operator) A ternary operator pair “?:” is available in C to construct conditional expressions of the form
exp1 ? exp2 : exp2; Where exp1, exp2, and exp3 are expressions. Here exp1 is evaluated first. If it is nonzero (true), then the expression exp2 is evaluated and becomes the value of the expression. If exp1 is false, exp3 is evaluated and its value becomes the value of the expression. Example: c=(a>b)?a:b;
© M. Anand 9
Decision Making and Branching C language supports control or decision making statements.
They are
1. if statement 2. switch statement 3. Conditional operator statement 4. goto statement
Decision making with if statement
The if statement is a powerful decision making statement and is used to control the flow of execution of statements. The syntax of if statement is
if (condition)
It allows the computer to evaluate the condition first and then,
depending on whether the value of the condition is ‘true’ (non-zero) or ‘false’ (zero), it transfers the control to a particular statement. This point of program has two paths to follow, one for the true condition and the other for the false condition as shown in the following fig.
Types of if statements
1. Simple if statement 2. if….else statement 3. Nested if….else statement 4. else if ladder
test expression
Entry
False
True
© M. Anand 10
Simple if Statement
The general form of a simple if statement is
if (condition) { Statement-block; } Statement-x;
The statement-block may be single statement or a group of
statements. If the condition is true, the statement-block will be executed; otherwise the statement-block will be skipped and the execution will jump to the statement-x. The flowchart of simple if statement is
False
True test expression
?
Entry
Statement-block
Statement-x
Next statement
© M. Anand 11
The if…else Statement
The if…else statement is an extension of the simple if statement. The general form is
if (condition) { True-block Statement(s); } else { False-block Statement(s); } Statement-x;
If the condition is true, then the true-block statement(s),
immediately following the if statement are executed; otherwise, the false-block statement(s) are executed.
© M. Anand 12
Nesting of if…else Statement
When a series of decisions are involved, we may have to use more than one if…else statement in nested form as follows:
if (condition 1) { if (condition 2) { Statement-1; } else { Statement-2; } } else { Statement-3; } Statement-x;
If the condition-1 is false, the statement-3 will be executed;
otherwise it continues to perform the second test. If the condition-2 is true, the statement-1 will be evaluated; otherwise the statement-2 will be evaluated and then the control is transferred to the statement-x.
© M. Anand 13
The else…if ladder (if…else if statement)
A multipath decision is a chain of ifs in which the statement associated with each else is an if. The general form of if…else if statement is
if (condition 1) Statement-1; else if (condition 2) Statement-2; else if (condition 3) Statement-3; …………. else if (condition n) Statement-n; else Default-Statement; Statement-x;
This construct is known as the else if ladder. The conditions are evaluated from the top, downwards. As soon as a true condition is found, the statement associated with it is executed and the control is transferred to the statement-x. When all the n conditions become false, then the final else containing the default-statement will be executed.
© M. Anand 14
The switch Statement The switch statement is a built-in multiway decision statement.
The switch statement tests the value of a given variable against a list of case values and when a match is found, a block of statements associated with that case is executed. The general form of the switch statement is as shown below:
switch(expression) { case value-1: block-1; break; case value-2: block-2; break; …… …… …… case value-n: block-n; break; default: default-block; break; }
The expression is an integer expression or characters. Value-1, value-2,… are constants or constant expressions and are known as case labels. Each of these values should be unique within a switch statement. Block-1, block-2,… are statement lists and may contain zero or more statements.
When the switch is executed, the value of the expression is successively compared against the values value-1, value-2,… if a case is found whose value matches with the value of the expression, then the block of statements that follows the case are executed.
The break statement at the end of each block signals the end of a particular case and causes an exit from the switch statement.
The default is an optional case. When present, it will be executed if the value of the expression does not match with any of the case values.
© M. Anand 15
The goto statement The goto statement is used to branch unconditionally from one
point to another in the program. The goto requires a label in order to identify the place where the branch is to be made. A label is any valid variable name, and must be followed by a colon. The label is placed immediately before the statement where the control is to be transferred. The general forms of goto and label statements are shown below:
goto label; … … … label: Statement;
Forward jump
label: Statement; … … … goto label;
Backward jump The label: can be anywhere in the program either before or after
the goto label; statement. If the label: is before the statement goto label; a loop will be formed and some statements will be executed repeatedly. Such a jump is known as a backward jump. On the other hand, if the label: is placed after the goto label; some statements will be skipped and the jump is known as a forward jump.
© M. Anand 16
Decision Making and Looping
Loop is a sequence of statements executed until some conditions for termination of the loop are satisfied. A program loop consists of two segments, one known as the body of the loop and the other known as the control statement. The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop.
Depending on the position of the control statement in the loop, a control structure may be classified either as the entry-controlled loop or as the exit-controlled loop.
The C language provides for three loop constructs for performing loop operations. They are:
1. The while statement. 2. The do statement 3. The for statement.
The while Statement The simplest of all the looping structures in C is the while statement. The while is an entry-controlled loop statement. The condition is evaluated and if the condition is true, then the body of the loop is executed. After execution of the body, the condition is once again evaluated and if it is true, the body is executed once again. This process of repeated execution of the body continues until the condition finally becomes false and the control is transferred out of the loop. On exit, the program continues with the statement immediately after the body of the loop. The basic format of the while statement is
while (condition) { body of the loop }
The body of the loop may have one or more statements. The braces are needed only if the body contains two or more statements.
© M. Anand 17
The do…while Statement
In do…while statement, the body of the loop is evaluated first. At the end of the loop, the condition in the while statement is evaluated. If the condition is true, the program continues to evaluate the body of the loop once again. This process continues as long as the condition is true. When the condition becomes false, the loop will be terminated and the control goes to the statement that appears immediately after the while statement. The general format of the do…while statement is
do { body of the loop } while (condition);
Since the condition is evaluated at the bottom of the loop, the do…while construct provides an exit-controlled loop and therefore the body of the loop is always executed at least once.
© M. Anand 18
The for Statement The for loop is another entry-controlled loop that provides a
more concise loop control structure. The general form of the for loop is
for(initialization; condition; increment) { body of the loop }
The execution of the for statement is as follows:
1. Initialization of the control variables is done first. Eg. i=1 and count=0.
2. The value of the control variable is tested using the condition. If the condition is true, the body of the loop is executed; otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement in the loop. Now, the increment section is executed and the condition is evaluated. If the condition is satisfied, the body of the loop is again executed. This process continues till the value of the control variable fails to satisfy the condition.
© M. Anand 19
Arrays An array is a group of related data items that share a common name. For example,
a[10] represents any 10 values. While the complete set of values is referred to as an array, the individual values are called elements. One-Dimensional Arrays A list of items can be given one variable name using only one subscript and such a variable is called a single-subscripted variable or a one-dimensional array. The subscript can begin with number 0. That is a[0] is allowed. For example, if we want to represent a set of five numbers by an array variable number, then we may declare the variable no as follows int no[5]; and the computer reserves five storage locations as shown below:
no[0] no[1] no[2] no[3] no[4]
The values to the array elements can be assigned as follows:
no[0]=37 no[1]=98 no[2]=57 no[3]=35 no[4]=71
This would cause the array no to store the values as shown below:
37 no[0] 98 no[1] 57 no[2] 35 no[3] 71 no[4]
These elements may be used in programs like any other C variable. Example:
a=no[0]+25; no[3]=no[1]+no[2]; a[7]=no[3]*7;
© M. Anand 20
Declaration of Arrays Arrays must be declared before they are used. The general form
of array declaration is
type variable-name[size];
The type specifies the type of element that will be contained in the array, such as int, float, or char and the size indicates the maximum number of elements that can be stored inside the array. For example,
float height[25];
declares the height to be an array containing 25 real elements. Any subscripts 0 to 24 are valid.
© M. Anand 21
Two-Dimensional Arrays C allows us to define a table of items by using two-dimensional
arrays. The two-dimensional arrays are declared as follows:
type array_name[row_size][column_size]; Two-dimensional arrays are stored in memory as shown in the following fig.
Column 0 Column 1 Column 2
Row 0 0,0 0,1 0,2
Row 1 1,0 1,1 1,2
Row 2 2,0 2,1 2,2
Row 3 3,0 3,1 3,2
Each dimension of the array is indexed from zero to its maximum size minus one; the first index selects the row and the second index selects the column within that row.
© M. Anand 22
User-Defined Functions C functions can be classified into two categories, namely, library functions and user-defined functions. Advantages of user-defined functions are
1. It facilitates top-down modular programming as shown in the following figure.
2. The length of a source program can be reduced by using functions at appropriate places.
3. It is easy to locate and isolate a faulty function for further investigations.
4. A function may be used by many other programs. The Form of C Functions
The general form of function is
function-name(argument list) argument declaration { local variable declarations; executable statement1; executable statement2;
………. ……….
return(expression); }
The declaration of local variables is required only when any local
variables are used in the function. The return statement is the mechanism for returning a value to
the calling function. Function Name:
A function must follow the same rules of formation as other variable names in C. Argument List: The argument list contains valid variable names separated by commas. The list must be surrounded by parentheses. The argument variables receive values from the calling function. Some examples of functions with arguments are:
quadratic(a,b,c) square(x) power(x,y)
© M. Anand 24
Return Values and their Types A function may or may not send back any value to the calling function. If it does, it is done through the return statement. The return statement can take one of the following forms
return;
Or return(expression);
When a return is encountered, the control is immediately passes back to the calling function. An example of the use of a simple return is as follows:
if(error) return;
The second form of return with an expression returns the value
of the expression. For example, the function
mul(x,y) int x,y; { int p; p=x*y; return(p); }
returns the value of p. The last two statements can be combined into one statement as follows:
return(x*y); A function may have more than one return statements. Example:
if(x<=0) return(0); else return(1);
Calling a Function A function can be called by simply using the function name in a statement. Example:
main() { int p; p=mul(5,2); printf(“%d”,p); }
© M. Anand 25
when the compiler encounters a function call, the control is transferred to the function mul(x,y). This function is then executed line by line as described and a value is returned when a return statement is encountered. This value is assigned to p. Recursion Calling a function with in the same function is called recursion. Example:
#include<stdio.h> #include<conio.h> main() { printf(“\nWelcome to C”); main(); }
When executed, this program will produce an output something like this:
Welcome to C Welcome to C Welcome to C Welcome t
© M. Anand 26
Execution is terminated abruptly; otherwise the execution will continue indefinitely.
Structures Structure is a method for packing data of different types. A
structure is a convenient tool for handling a group of logically related data items. Structure Definition A structure definition creates a format that may be used to declare structure variables. Consider a book database consisting of book name, author, number of pages, and price. We can define a structure to hold this information as follows:
struct book_bank { char title[20]; char author[15]; int pages; float price; };
The keyword struct declares a structure to hold the details of
four fields, namely title, author, pages, and price. These fields are called structure elements or members. Each member may belong to a different type of data. book_bank is the name of the structure and is called the structure tag. The general format of a structure definition is as follows:
struct tag_name { data_type member1; data_type member2; ….. ….. };
We can declare structure variables using the tag name. For
example, the statement
struct book_bank b1,b2,b3; declares b1,b2 and b3 as variables of type struct book_bank. In defining a structure you may note the following syntax:
1. The template is terminated with a semicolon. 2. Each member is declared independently for its name and type in
a separate statement inside the template.
© M. Anand 27
3. The tag name can be used to declare structure variables of its type.
It is also allowed to combine both the template declaration and variables declaration in one statement. Example:
struct book_bank { char title[20]; char author[15]; int pages; float price; }b1,b2,b3;
Giving Values to Members
The link between a member and a variable is established using the member operator ‘.’ Which is also known as ‘dot operator’ or ‘period operator’. For example, b1.price
Is the variable representing the price of b1 and can be treated like any other ordinary variable.
strcpy(b1.title,”BASIC”); strcpy(b1.author,”SAM”); b1.pages=255; b1.price = 535.00;
we can also use scanf to give the values through the keyboard.
scanf(“%s”,b1.title); scanf(“%s”,b1.author); scanf(“%d”,&b1.pages); scanf(“%d”,&b1.price);
© M. Anand 28
OBJECT ORIENTED PROGRAMMING IN C++ C++ was invented by Bjarne Stroustrup in 1979, while he was
working at Bell Laboratories in Murray Hill, New Jersey. Stroustrup initially called the new language “C with Classes”. However, in 1983, the name was changed to C++. C++ extends C by adding Object-Oriented features. Features of object-oriented programming are:
• Emphasis is on data rather than procedure. • Programs are divided into what are known as objects. • Data structures are designed such that they characterize the
objects. • Functions that operate on the data of an object are tied together
in the data structure. • Data is hidden and cannot be accessed by external functions. • Objects may communicate with each other through functions. • New data and functions can be easily added whenever
necessary. • Follows bottom-up approach in program design.
Basic Concepts Of Object-Oriented Programming The basic concepts of OOP are
1. Classes 2. Objects 3. Data abstraction 4. Encapsulation 5. Inheritance 6. Polymorphism 7. Dynamic binding 8. Data hiding
1. Classes: Class is template for an object. A class serves as a plan, or blue print. We can create any number of objects related to the class. Data items in a class are called data members. The functions within a class are called member functions. 2. Objects: An instance of a class is called object. We can create any number of objects related to the class. Each object is associated a data type class. Object can be defined as variables and type class. 3. Data abstraction:
© M. Anand 30
Abstraction refers to the act of representing without including the background details or explanations. Classes use the concept of
abstraction and are defined as a list of abstract attributes such as size, weight and cost, and functions to operate on these attributes. They encapusulate all the essential properties of the objects that are to be created. The attributes are sometimes called data members. The functions that operate on these data are sometimes called methods or member functions. 4. Data Hiding: The insulation of data from direct access of program is called data hiding. In C++, the class construct allows to declare data and methods, as a public, private and protected group. The implementation details can be hidden. This is done by the data hiding principle. 5. Encapsulation: The wrapping up of data and functions into a single unit is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world, and only those functions which are wrapped in the class can access it. 6. Inheritance: Inheritance is the process by which objects of one class acquire the properties of objects of another class. The main advantages of the inheritance are
• Reusability of the code • To increase the reliability of the code • To add some enhancements to the base class
7. Polymorphism: Polymorphism means one name, multiple forms. It allows us to have more than one function with the same name in a program. Operator overloading and function overloading comes under polymorphism. This helps to reduce complexity by allowing the same interface to be used to specify a general class of action. The process of making an operator to exhibit different behaviors in different instances is known as operator overloading. 8. Dynamic Binding: Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run-time. This is also known as late binding. It is associated with polymorphism and inheritance. BENEFITS OF OOP
1. Through inheritance we can eliminate redundant code and extend the use of existing classes.
© M. Anand 31
2. The principle of data hiding helps the programmer to build secure programs.
3. It is possible to have multiple objects to co-exist without interference
4. It is possible to map objects in the problem domain to those in the program.
5. It is easy to partition the work in a project based on objects. 6. Object-Oriented Systems can be easily upgraded from small to
large systems. 7. Software complexity can be easily managed. 8. Object oriented languages greatly enhance the possibility of
code reuse. 9. Message passing techniques for communication between objects
is simpler. APPLICATIONS OF OOP The applications of OOP are
• Real time systems • Simulation and modeling • Object Oriented databases • Hypertext, hypermedia and expert text • Artificial Intelligence and expert systems • Neural networks and parallel processing • Decision support and office automation systems • CAD/CIM systems
CAD – Computer Aided Design CIM – Computer Input Microfilm
APPLICATIONS OF C++
1. C++ allows us to create hierarchy-related Objects. 2. We can build special object oriented libraries, which can be
used later by many programmers. 3. C++ programs are easily maintainable and expandable. When a
new feature needs to be implemented, it is very easy to add to the existing structure of an object.
4. C++ is able to map the real world problem properly. STRUCTURE OF C++ PROGRAM A typical C++ program would contain four sections as shown in the following figure:
© M. Anand 32
Include files
Class declaration
Member functions definitions
Main function program
The include files section or link section provides instructions to the compiler to link functions from the system library. In class declaration section we can declare variables and functions of the class. The member functions definitions section contains all the member functions of the class. Every C++ program must have one main() function section. The main() function section contains two parts, declaration part and executable part. The declaration part declares all the variables used in the executable part. There is at least one statement in the executable part. All statements in the declaration and executable part end with a semicolon. All sections, except the main function section may be absent when they are not required. Function Overloading
Overloading refers to the use of the same thing for different purposes. Using the same function name to create functions that perform a variety of different tasks is called function overloading. This is also known as function polymorphism in OOP. Using the concept of function overloading, we can design a family of functions with one function name but with different argument lists. The function would perform different operations depending on the argument list in the function call. The functions are differentiated by the number and type of the arguments. Eg.: //Declarations
int add(int a, int b); //prototype1 int add(int a, int b, int c); //prototype2 double add(double x, double y); //prototype3 double add(int p, double q); //prototype4 double add(double p, int q); //prototype5 //Function calls cout<<add(5,10); //uses prototype1 cout<<add(15,10.3); //uses prototype4 cout<<add(12.4,7.9); //uses prototype3 cout<<add(3,5,9); //uses prototype2 cout<<add(9.23,7); //uses prototype5
A function call first matches the prototype having the same number and type of arguments and then calls the appropriate function for execution. A best match must be unique.
© M. Anand 33
Classes and objects A class is a way to bind the data and its associated functions
together. Specifying a Class A class specification has two parts:
1. Class declaration 2. 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. The general form of a class declaration is: class class_name { private: variable declarations; function declarations; public: variable declarations; function declarations; }; The keyword class specifies, that what follows is an abstract data of type class_name. The body of a class is enclosed within braces and terminated by a semicolon. The class body contains the declaration of variables and functions. These functions and variables are collectively called class members. They are usually grouped under two section, namely private and public. The keywords private and public are known as visibility labels. The private class members can be accessed only from within the class and the public members can be accessed from outside the class. By default, the members of a class are private. The variables declared inside the class are known as data members and the functions are known as member functions. The binding of data and functions together into a single class-type variable is referred to as encapsulation. Example: class item { int no; float cost; public: void getdata(); void putdata();
© M. Anand 34
};
Creating Objects Once a class has been declared, we can create variables of that type by using the class name. Example: item x, y, z; Accessing Class Members The class members can be accessed using an object of the same class. The general format of calling a member function is object-name.function-name(actual-arguments); Example: x.getdata();
x.putdata(); Defining Member Functions Member functions can be defined in two places: 1. Outside the class definition 2. Inside the class definition Outside the Class Definition Member functions that are declared inside a class have to be defined separately outside the class. The general form of a member function definition is return-type class-name::function-name(argument declaration) { Function body } The membership label class-name :: tells the compiler that the function function-name belongs to the class class-name. Eg.: void item::getdata() { cout<<”Enter the item number : “; cin>>no; cout<<”Enter the item cost : “; cin>>cost; } void item::putdata() { cout<<”\nItem number : “<<no; cout<<”\nItem cost : “<<cost; }
© M. Anand 35
The characteristics of member functions are • Several different classes can use the same function name. • Member functions can access the private data of the class. • A member function can call another member function
directly, without using the dot operator. Inside the Class Definition Another method of defining a member function is to replace the function declaration by the actual function definition inside the class. Eg.: class item { private: int no; float cost; public: void getdata() { cout<<”Enter the item number : “; cin>>no; cout<<”Enter the item cost : “; cin>>cost; } void putdata() { cout<<”\nItem number : “<<no; cout<<”\nItem cost : “<<cost; } };
© M. Anand 36
Constructors and Destructors
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 also provides another member function called the destructor that destroys the objects when they are no longer required. Constructor
A constructor is a ‘special’ member function whose task is to initialize the objects of its class. It is special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created.
A constructor is declared and defined as follows:
class integer {
int m,n; public:
integer(void); //constructor declaration ….. …..
};
integer :: integer(void) //constructor definition {
m=0; n=0;
} The declaration
integer I1; creates the object I1 of type integer and initializes its data members m and n to zero.
A constructor that accepts no parameters is called the default constructor.
The constructor functions have some special characteristics. These are:
• They should be declared in the public section. • They are invoked automatically when the objects are created. • They do not have return types and they cannot return values. • They cannot be inherited, though a derived class can call the
base class constructor. • They can have default arguments.
© M. Anand 38
• Constructors cannot be virtual.
• We cannot refer to their addresses. • An object with a constructor cannot be used as member of a
union. • They make ‘implicit calls’ to the operators new and delete when
memory allocation is required. Parameterized Constructors
C++ permits us to initialize the data members with different values by passing arguments to the constructor function when the objects are created. The constructors that can take arguments are called parameterized constructors.
class integer {
int m,n; public:
integer(int x, int y); //parameterized constructor ….. …..
};
integer :: integer(int x, int y) {
m=x; n=y;
}
There are two ways to pass the initial values as arguments to the constructor function when an object is declared.
1. By calling the constructor explicitly. 2. By calling the constructor implicitly.
The following declaration illustrates calling the constructor explicitly.
integer I1=integer(10,20); //explicit call
This statement creates an integer object i1 and passes the
values 10 and 20 to it. The following declaration illustrates calling the constructor implicitly.
integer I1(10,20); //implicit call
This method, sometimes called the shorthand method. When
the constructor is parameterized, we must provide appropriate arguments for the constructor.
© M. Anand 39
Multiple Constructors in a Class (Constructor Overloading) Defining more that one constructor in a class is called multiple
constructors in a class or constructor overloading. Example:
class integer {
int m,n; public:
integer() // constructor 1 { m=0; n=0; } integer(int x) // constructor 2 { m=x; n=x; } integer(int x, int y) // constructor 3 { m=x; n=y; }
};
This declared three constructors for an integer object. The first constructor receives no arguments, the second receives one argument and the third receives two arguments. The declaration
integer I1;
would automatically invoke the first constructor and set both m and n of I1 to zero. The statement
integer I2(10); would call the second constructor which will initialize the data members m and n to 10. and the statement
integer I3(10,20); would invoke the third constructor which will initialize the data members m to 10 and n to 20. Copy Constructor
© M. Anand 40
The constructor that creates a new class object from an existing object of the same class is called copy constructor. A copy constructors is used to declare initialize an object from another object of the same class. The general format of the copy constructor is
class_name:: class_name(class_name &ptr)
For example, the statement
integer I2(I1); would define the object I2 and at the same time initialize it to the values of I1. Another form of this statement is
integer I2=I1; The process of initializing through a copy constructor is known
as copy initialization. A copy constructor takes a reference to an object of the same
class as itself as an argument. Destructors A destructor is used to destroy the objects that have been created by a constructor. The destructor is a member function whose name is the same as the class name but is preceded by a tilde. For example, the destructor for the class integer can be defined as shown below:
~integer() { }
A destructor never takes any argument nor does it return any value. It will be invoked implicitly by the compiler upon exit from the program(or block or functions) to clean up storage that is no longer accessible.
© M. Anand 41
Operator Overloading
The mechanism of giving additional meanings to an operator is known as operator overloading. Defining Operator Overloading
An additional task to an operator can be defined with the help of a special function, called operator functions. The general form of an operator function is:
return-type class-name :: operator op(argument-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. The op is preceded by the keyword operator. Operator op is the function name.
complex operator+(complex); complex operator-(complex); friend complex operator+(complex,complex); friend complex operator-(complex,complex); complex operator==(complex); friend complex operator<(complex,complex);
Overloaded operator functions can be invoked by expressions such as
op x or x op
for unary operators and x op y
Overloading Unary Operators
A unary operators act on only one operand. Example of unary operators are the increment operator ++ , decrement operator --, unary minus, etc. The unary minus operator changes the sign of an operand when applied to a basic data item. The unary minus when applied to an object should change the sign of each of its data items. The following program shows how the unary minus operator is overloaded. Overloading Binary Operators
© M. Anand 43
Binary operators overloaded by means of member functions take one formal argument which is the value to the right of the operator. Binary operators require two operands to perform the operation. The
following program shows add two complex numbers by overloading binary operator +. In overloading of binary operators, the left-hand operand is used to invoke the operator function and the right-hand operand is passed as an arugment. Inheritance: Extending Classes Inheritance is the process of creating new classes, called derived classes, from existing or base classes. The derived class inherits all the capabilities of the base class. The main advantages of the inheritance are
• reusability of the code • to increase the reliability of the code. • to add some enhancements to the base class
A class can also inherit properties from more than one class or
from more than one level. A derived class with only one base class, is called single inheritance and one with several base classes is called multiple inheritance. On the other hand, the traits of one class may be inherited by more than one class. This process is known as hierarchical inheritance. The mechanism of deriving a class from another ‘derived’ is known as multilevel inheritance. The following figure shows various forms of inheritance that could be used for writing extensible programs.
© M. Anand 44
A
B
C
A
B
A B
C
Defining Derived Classes A derived class can be defined by specifying its relationship with the base class in addition to its own details. The general form of defining a derived class is
class derived-class-name : visibility-mode base-class-name { ….. ….. //members of derived class ….. };
The colon indicates that the derived-class-name is derived from the base-class-name. The visibility-mode is optional and, if present, may be either private or public. The default visibility mode is private. Visibility specifies whether the features of the base class are privately derived or publicly derived. Example: i) class ABC : private XYZ //private derivation { member of ABC; }; i) class ABC : public XYZ //public derivation { member of ABC; }; i) class ABC : XYZ //private derivation {
A
C B
C
D
A
B
© M. Anand 45
© M. Anand 46
member of ABC; }; when a base class is privately inherited by a derived class, ‘public members’ of the base class become ‘private members’ of the derived class. The public members of the base class can only be accessed by the member functions of the derived class. When the base class is publicly inherited, ‘public members’ of the base class become ‘public members’ of the derived class. In inheritance, some of the base class data elements and member functions are ‘inherited’ into the derived class. We can add our own data and member functions and thus extend the functionality of the base class.