Professional Documents
Culture Documents
C&C++ Programming Final
C&C++ Programming Final
Letters :
C language comprises the following set of letters to form a standard
program. They are :
• A to Z (Uppercase characters)
• a to z (lowercase characters)
Digits :
• C language comprises the following sequence of numbers to associate the
letters.
• 0 to 9 digits.
Tokens
• Smallest unit in a program/statement
• It makes the compiler understand what is written in the
program
• Example: main, (,), printf , (semicolon), etc..
• Tokens are broadly classified as:
Keywords
• Keywords are pre-defined words in a C compiler.
• In C there are certain reserved word that we
cannot declare as variable.
• These words are known as keywords
• Each keyword is meant to perform a specific
function in a C program.
• There are 32 keywords in C language.
• All keywords are written in lowercase only
Identifiers
• Identifiers are the fundamental building blocks
of a program
• Used to give names to variables, functions,
arrays, structures, etc.
• They are user-defined names and consist of a
sequence of letters and digits
• Rules for identifier naming:
• Valid characters are alphabets, digits, and underscore
• First character cannot be a digit
• Uppercase and lowercase are distinct
• Keywords cannot be used as identifier names
Examples
• Examples of legal identifiers:
• Student_Name
• StudentName
• Student_name
• Student1
• _student
• Examples of illegal identifiers :
• Student Name
• Name&Rollno
• 1st_student
Data types
• Data type is one of the most important attribute
of an identifier.
• It determines the possible values that an
identifier can have
• Each of the data types are represented
differently within the computer’s memory
• In C data type is broadly classified as:
• Basic data types
• Derived data types
• User defined data types
Data Types
Basic Data Types
Basic/primitive data types:
• void valueless
Integers
Integers
char
• It stores a single character of data belonging
to the C character set.
• It occupies 1 byte of memory
• The type modifiers for char are signed and
unsigned.
• Each char type has an equivalent integer
interpretation, so that a char is really a special
kind of short integer
• By default, char is unsigned.
Characters
float
• It is used to store real numbers with single
precision i.e. a precision of 6 digits after
decimal point.
• The type modifier for float is long
User defined data types:
•The C language provide the flexibility to the
user to create new data types.
•The newly created data types are called user
in C are:
• Structure
• Union
• Enumeration
• Derived Data types:
• These data types are derived from the basic
data types . Derived data types that are
available in C are:
• Array type
• Function type etc.
Variable Declaration
Examples:
char name;
int x, y,z;
float number;
float n1, n2, sum;
double counter;
Variable Initialization
• Giving a value to a variable during the
variable’s declaration is called “variable
initialization.”
Syntax:
type variable_name = value;
Example:
int count = 100;
float grade = 3.75;
char status = ‘S’;
Declaration
• First step in c is declaring the variables
• Why???
• Ans: we need space to store data in
memory
• int x
• Compiler will allots a address to x and
Then compiler can store the data in that
Memory space.
Header Files
• Header files
• Contain function prototypes for library functions
• <stdlib.h> , <math.h> , etc
• Load with #include <filename>
• #include <math.h>
• Custom header files
• Create file with functions
• Save as filename.h
• Load in other files with #include "filename.h"
• Reuse functions
• Example #include<square.h>
Header Files
Comment
• Programmers insert comments to document
programs and improve program readability.
• Arithmetic expression:-
• An expression that involves arithmetic operators
and combines them constants and variables is
called an arithmetic expression.
• The result of an arithmetic expression is always a
numeric value.
Classification based on number of
Operands
Unary operator:-
• An operator that takes only one operand is called unary operator.
• E.g. Unary minus as in –2.5, &, sizeof operator, ++, --
Binary operator:-
• An operator that takes two operands to write an arithmetic expression is called
binary operator.
Binary operator Meaning
• + Plus
• - minus
• * multiplication
• / division
• % modulus operator for remainder used with integer
numbers.
<<, ==, &&
• Ternary operator:- (Conditional operator):-
• This is a special feature of C language.
• This case needs three operands.
• Operand1 ? operand2 : operand3;
• operand1 is evaluated first, if it results true ,
the value of operand2 is taken otherwise the
value of operand3 is taken for further
processing
Relational operator
• A relational operator is used to compare two
values and the result is always logical i.e.
either true or false.
• e.g. a>b return a value zero when the result is
false and a non-zero when it is true.
• Associativity Left to Right
Assignment Operators
• Assignment operator:-
• Assignment operator denoted as =, stores the
value of the expression on the right hand side
of the equal sign in the variable represented
by the left hand side of the equal sign.
• e.g. The statement sum = 4+7-8/2 will
store value 7 in the variable sum..
• Increment/Decrement operators:-
• The increment operator, ++, adds 1 to its operand
and – subtracts 1 from its operand.
• e.g. Let sum = 10;
• x=5;
• then
• sum = sum + (++x); yields 16
• sum = sum + (x++); yields 15
• sum = sum + (--x); yields 14
• sum = sum + (x--); yields 15
Increment and Decrement Operators
Logical operators
• A logical operator is used to connect relational expression or logical
expressions and returns the logical value i.e. true or false.
• The logical operators supported by C are
conditi
on
evaluat
ed
tru
e fal
se
statement
The if Statement
• The if statement has the following syntax:
The condition must be a
boolean expression. It must
if is a C evaluate to either true or false.
reserved word
if ( condition
)
statement;
• if ( grade >= 60 )
{
printf( "Passed\n" );
} /* end if */
Example
• Demonstration of IF Statement
1. Enter a number and print result if Number is
less than 0.
conditi
on
evaluat
ed
tru fal
e se
statement1 statement2
The if-else Statement
• An else clause can be added to an if
statement to make an if-else statement
if ( condition
)
statement1;
else
statement2;
• If the condition is true, statement1 is executed; if the condition
is false, statement2 is executed
• One or the other will be executed, but not both
If…Else Statement
#include <stdio.h> //include the stdio.h header file in your program
void main () // start of the main
{
int num; // declare variable num as integer
printf ("Enter the number"); // message to the user
scanf ("%d", &num); // read the input number from keyboard
if (num < 0) // check whether number is less than zero
{
printf ("The number is negative"); // if it is less than zero then it is negative
}
else // else statement
{
printf ("The number is positive"); // if it is more than zero then the given number is positive
}
getch();
}
Nested if else Statements
• The statement executed as a result of an if statement or
else clause could be another if statement
• These are called nested if statements
• An else clause is matched to the last unmatched if (no
matter what the indentation implies)
• Braces can be used to specify the if statement to which an
else clause belongs
• Example: Enter 1 or 2
Nested if else
The switch Statement
• The switch statement provides another way to
decide which statement to execute next
• The switch statement evaluates an expression,
then attempts to match the result to one of
several possible cases
• Each case contains a value and a list of
statements
• The flow of control transfers to statement
associated with the first case value that matches
The switch Statement
• Often a break statement is used as the last
statement in each case's statement list
• A break statement causes control to transfer to
the end of the switch statement
• If a break statement is not used, the flow of
control will continue into the next case
• Sometimes this may be appropriate, but often
we want to execute only the statements
associated with one case
The switch Statement
• An example of a switch statement:
switch (option)
{
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
default:
otherCount++;
break;
}
The switch Statement
• A switch statement can have an optional
default case
• The default case has no associated value and
simply uses the reserved word default
• If the default case is present, control will transfer
to it if no other case value matches
• If there is no default case, and no other value
matches, control falls through to the statement
after the switch
Switch Statement
tru
variable e
equals first case body
const 1
fals
e
tru
variable e second case body
equals
const 2
while(Condition)
{
Statements;
}
while statement
Example: This while statement prints numbers 10 down to 1
Note that, the first line (n=10) is
actually not a part of the loop statement.
n=10;
while (n>0)
{
printf(“%d “, n);
n=n-1;
}
Output:
10 9 8 7 6 5 4 3 2 1
The for Statement in C
• The syntax of for statement in C:
for (initialization expression;
loop repetition condition;
update expression)
statement;
• The initialization expression set the initial value of the
loop control variable.
• The loop repetition condition test the value of the
loop control variable.
• The update expression update the loop control
variable.
for statement
for flowchart
for (n=10;n>0;n=n-1)
{
printf(“%d “, n);
}
Output:
10 9 8 7 6 5 4 3 2 1
Nested Loops
• Nested loops consist of an outer loop with one
or more inner loops.
• e.g.,
for (i=1;i<=100;i++){ Outer loop
for(j=1;j<=50;j++){
…
} Inner loop
}
• The above loop will run for 100*50 iterations.
for vs. while statements
do
{
Repeated_Actions;
} while (Condition);
n=10;
do
{
printf(“%d “, n);
n=n-1;
} while (n>0);
Output:
10 9 8 7 6 5 4 3 2 1
Loop statements
• If the body part has only one statement, then the bracket symbols, { } may
be omitted.
Example:
Break statement takes the execution control out of the loop. The break
statement, when executed in a while, for, do…while or switch statement,
causes an immediate exit from that statement.
continue statement
• In while and do…while loops, the continue statement transfers the control to the loop
condition.
• In for loop, the continue statement transfers the control to the updating part.
Continue statement skips the execution of the statements after it and takes the
control to the beginning of the loop.
continue statement
Example:
n = 10; Output:
while (n>0) 10 9 9 9 9 9 …………
{
printf(“%d “, n);
if (n%2==1) continue; The loop then prints number 9
over and over again. It never
n = n –1; stops.
}
Return statement
• Exits the function.
• return exits immediately from the currently
executing function to the calling routine,
optionally returning a value. The syntax is:
• return [expression];
• For example,
int sqr (int x) { return (x*x);}
goto
• Unconditionally transfer control.
• goto may be used for transfering control from
one place to another. The syntax is:
• goto identifier; Control is unconditionally
transferred to the location of a local label
specified by identifier. For example,
• Again:
• ...
• goto Again;
goto statement
• It is used to translate connector symbols – jump to another part inside a program.
• But, it is not recommended to use - it may cause unstructured programs.
Example:
n=10;
A:
printf(“%d “, n);
n = n -1;
if (n>0) goto A;
Output:
10 9 8 7 6 5 4 3 2 1
String Handling Library
• Functions defined in #include<string.h>
• String handling library provides many useful
functions:
• Manipulate string data(copy and concatenate)
• Comparing strings
• Determine string length
• Search strings
String Manipulation Functions
• List of string manipulation functions
Function prototype Function description
char *strcpy( char *s1, const char *s2 Copies string s2 into array s1.
)
The value of s1 is returned.
char *strncpy( char *s1, const char Copies at most n characters of
*s2, int n )
string s2 into array s1. The
value of s1 is returned.
char *strcat( char *s1, const char *s2 ) Appends string s2 to array s1.
The first character of s2
overwrites the terminating
null character of s1. The value
of s1 is returned.
char *strncat( char *s1, const char Appends at most n characters
*s2, int n )
of string s2 to array s1. The
strcpy() and strncpy()
• strcpy() copies the entire second argument
string into first argument.
• strcpy( s1, s2);
• strncpy() copies the first n characters of second
string argument into first string argument.
• strncpy( s1, s2, 4);
• A null character ('\0') is appended explicitly to first
argument, because the call to strncpy in the
program does not write a terminating null
character.
• The third argument is less than the string length of
the second argument.
Example Code
This program
demonstrate
s string
manipulation
/ processing
functions:
strcpy() and
strncpy()
Output
The string in array x is: Happy Birthday to You
The string in array y is: Happy Birthday to You
The string in array z is: Happy Birthday
Comparison Functions of the
String Handling Library
• Comparing strings
• Computer compares numeric ASCII codes of
characters in string
• strcmp() Compares its first string argument with its
second string argument, character by character.
• Function strncmp() does not compare characters
following a null character in a string.
strcmp()
int strcmp( const char *s1, const char *s2 );
• Compares string s1 to s2
• Returns
• a negative number if s1 < s2,
• zero if s1 == s2
• a positive number if s1 > s2
strncmp()
int strncmp( const char *s1, const char *s2, int n);
Example: Syntax
char c; Variable-name =
c = getchar(); getchar();
#include<stdio.h>
void main()
{
char c;
printf(“enter a character”);
c=getchar();
printf(“c = %c ”,c);
}
Enter a character k
c = k
getch() & getche()
• These functions read any alphanumeric character
from the standard input device
• The character entered is not displayed by the getch()
function until enter is pressed
• The getche() accepts and displays the character.
• The getch() accepts but does not display the
character.
Syntax
getche();
#include<stdio.h>
void main()
{
printf(“Enter two alphabets:”);
getche();
getch();
}
Syntax
char str[length of string in number];
gets(str);
puts(str);
#include<stdio.h>
void main()
{
char ch[30];
printf(“Enter the string:”);
gets(ch);
puts(“Entered string:”);
puts(ch);
}
Arrays
• An array is an ordered list of values
The entire array Each value has a numeric index
has a single name
0
• C arrays have no bounds checking.
• If size is omitted, initializers determine it
• int n[] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array.
Initializing Arrays
• Array is same as the variable can prompt for
value from the user at run time.
• Array is a group of elements so we use for
loop to get the values of every element
instead of getting single value at a time.
• Example: int array[5], i; // array of size 5
for(i=0;i<5;i++){// loop begins from 0 to 4
scanf(“%d”, &array[i]);
}
Program of
Initializing an
array to zero
using loop.
0
Element Value
0 0
1 0
2 0
3 0
4 0
5 0 n[ 0
6 0 0]
n[
7 0 1]
n[
8 0 2]
n[ 0
9 0 3]
n[ 0
4]
n[
5]
n[6]
n[ 0
7]
n[ 0
8]
n[ 0
9]
Character Arrays
• Character arrays
• Character arrays can be initialized using string literals
• char string1[] = "first";
•It is equivalent to
• char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };
• Null character '\0' terminates strings
• string1 actually has 6 elements
• Can access individual characters
• string1[ 3 ] is character ‘s’
• Array name is address of array, so & not needed for scanf
scanf( "%s", string2 );
•
• 2D
• Long Jump
• Distance, Height [D,H]
• 3D
• High Jump
• Distance, Height, Roll [D,H,R]
Pointers
• A variable which stores address of another
variable
• Example:
int *p;
int i;
p= &i;
• *p gives value at address stored in p.
• int *p means p is containing an address of
variable on which an integer is stored
Calling Functions by Reference
• Call by reference with pointer arguments
• Pass address of argument using & operator
• Allows you to change actual location in memory
• * operator
• Used as alias/nickname for variable inside of function
• void double( int *number )
• {
• *number = 2 * ( *number );
• }
• *number used as nickname for the variable passed
#include <stdio.h>
void cubeByReference(int *nPtr); //function prototype
int main( void )
{
int number = 5;
printf("The original value of number is %d", number);
cubeByReference( &number ); //pass address of number
printf("\nThe new value of number is %d\n", number);
} // end main
struct sname {
type var1;
type var2;
type var3;
.
.
type varN;
};
• struct car{
• char *name;
• int seats;
• float price };
• struct keyword introduces the definition for structure car
• car is the structure name or tag and is used to declare variables of
the structure type
• car contains three members of type char, float, int
• These members are name, price and seats.
int main()
{
struct car myCar; //define struct variable
myCar.name = “Renault";
myCar.price = 500000;
myCar.seats = 2;
printf("%s %f %d \n”, myCar.name,
myCar.price, myCar.seats);
} //end main
Renault 500000 2
#include <stdio.h>
struct car{ Program to
char name[50]; enter data into
int seats;
float price;
structure.
};
main()
{
struct car myCar;
printf(“Enter name of car:\n”);
gets(myCar.name);
printf(“Enter number of seats in car:\n”);
scanf(“%d”, &myCar.seats);
printf(“Enter price of car:\n”);
scanf(“%f”, &myCar.price);
printf(“\n\nParticulars of car are:\n”);
printf(“Car name:%s”,myCar.name);
printf(“\nNumber of seats:%d”,
myCar.seats);
printf(“\nPrice:%f”, myCar.price);
} //end main
Enter name of car: Micra
Enter number of seats in car: 4
Enter price of car: 600000
•Embedded structures
Example
struct Date
{
int dd;
int mm;
int yy;
};
struct Student
{
char name[20];
int rollno;
int marks;
struct Date dob;
};
Here structure Student is nesting structure and structure date is nested structure
Example: embedded structures
struct Student
{
char name[20];
int rollno;
struct date
{
int dd;
int mm;
int yy;
} dob;
};
#include<stdio.h>
void main() WAP to read
{
struct time{
and display the
int second; car number,
int minute;
int hour; starting time
};
struct car and reaching
{
int carno;
time using
struct time st; structure within
};
structure.
struct car myCar;
printf(“\n car no. starting time reaching
time:”);
scanf(“%d”, &myCar.carno);
scanf(“%d %d %d”, & myCar.st.hour,
&myCar.st.minute, &myCar.st.second);
printf(“\n%d”, myCar.carno);
printf(“\t %d:%d:%d \t” myCar.st.hour,
myCar.st.minute, myCar.st.second);
}
Unions
• union
• Memory that contains a variety of objects over time
• Only contains one data member at a time
• Members of a union share space
• Conserves storage
• Only the last data member defined can be accessed
• union definitions
• Same as struct
• union Number {
• int x;
• float y;
• };
• union Number value;
Union
• Union is similar as structure. The major
distinction between them is in terms of
storage.
• In structure each member has its own storage
location whereas all the members of union
uses the same location.
• The union may contain many members of
different data type but it can handle only one
member at a time union can be declared using
the keyword union.
Union Declaration
union item
{
int m;
float x;
char c;
}code;
This declare a variable code of type union item
Unions
• Valid union operations
• Assignment to union of same type: =
• Taking address: &
• Accessing union members: .
• Accessing members using pointers: ->
#include <stdio.h>
union job{
Program using
char name[32]; union.
float salary;
int worker_no;
}u;
main()
{
printf("Enter name:\n");
scanf("%s",&u.name);
printf("Enter salary: \n");
scanf("%f",&u.salary);
printf("Displaying\nName :%s\n",u.name);
printf("Salary: %.1f",u.salary);
}
Enter name Hillary
Enter salary 1234.23
Displaying
Name: f%Bary
Salary: 1234.2
type-specifier func-name(struct-variable);
#include <stdio.h>
struct car{
Passing of
char name[50]; structure to a
int seats; function by
float price;
}; value
void cardata(struct car); /*function
prototype*/
void main()
{
struct car myCar = {“Racer”, 1, 1200000};
cardata(myCar); //function calling
}
void cardata(struct car newCar)
{
printf(“\nData about your car is: %s %d %f”,
newCar.name, newCar.seats, newCar.price);
}
Renault 500000 2
Renault 500000 2
Renault 500000 2
Concepts and Basics of C++
Programming
Object-Orientation
• A thinking methodology
– Everything is an object.
– Any system is composed of objects (a system
is also an object).
– The evolution and development of a system is
caused by the interactions of the objects
inside/outside a system.
Everything is an object
• A student, a professor
• A desk, a chair, a classroom, a building
• A university, a city, a country
• The world, the universe
• A subject such as CS, IS, Math, History, …
The development of a system is caused by
interactions
Any valid
identifier
class class_name
{ Class body (data member +
….
…. methods)
….
};
class classname
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
protected:
variable declarations;
function declarations;
} obj1, obj2,…..objN;
Class name
• Name given to a particular class (any user
define name). It can also be called as tag
name of the class that act as the type
specifier for class using which we can
create objects.
• The class is specified by keyword “class”
Data Members
• Data type properties that describe the
characteristics of a class.
• We can declare any number of data
members of any type in a class.
E.g. int x;
Member functions
Eg: obj.getdata();
Access privileges in C++.
class demo
{
int x;
public:
demo(int a)
{
x=a;
}
friend void display(demo);
};
void display(demo d1)
{
cout<<d1.x;
}
void main()
{
demo d2(5);
display(d2);
}
• class sample
{
int a;
int b;
public:
void setval(){ a=25,b=40}
friend float mean(sample s);
};
float mean(sample s)
{ return (s.a+s.b)/2.0;
}
void main()
{ sample X;
X.setval();
cout<<mean(X);
}
Friend class
• Library functions
• User defined functions.
– Programmer can create their own function in
C++ to perform specific task
Why use function?
• Writing functions avoids rewriting of the
same code again and again in the
program.
• Using function large programs can be
reduced to smaller ones. It is easy to
debug and find out the errors in it.
• Using a function it becomes easier to
write program to keep track of what they
are doing.
//Function Declaration retn_type func_name(data_type
1,data_type );
//Function Definition
rent_type func_name(data_type par1,data_type
par2)
{
// body of the function
}
//Function Call
func_name(par1,par2);
Function prototype
• A prototype statement helps the
compiler to check the return type and
arguments type of the function.
• A prototype function consist of the
functions return type, name and
argument list.
• Example
– int sum( int x, int y);
Example
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
void sum(int, int); // function declaration
int a, b;
cout<<“enter the two no”;
cin>>a>>b;
sum(a,b); // function calling
getch();
}
void sum( int x, int y) // function definition
{
int c=x+y;
cout<< “ sum is”<<c;
}
#include<conio.h>
main()
{
int a=10,b=20;
int sum(int, int);
int c=sum(a,b); //actual arguments
Cout<<“sum is” << c;
getch();
}
int sum(int x, int y) //formal arguments
{
int s;
s=x+y;
return(s); //return value
}
Categories of functions
#include<conio.h>
void main()
{
clrscr();
int a=10,b=20;
void mul(int,int);
mul(a,b); /*actual arguments
getch();
}
void mul(int x, int y) /*formal arguments
{
int s;
s=x*y;
Cout<<“mul is” << s;
}
A function with parameter and return value
#include<conio.h>
void main()
{
int a=10,b=20,c;
int max(int,int);
c=max(a,b);
Cout<<“greatest no is” <<c;
getch();
}
int max(int x, int y)
{
if(x>y)
return(x);
else
{
return(y);
}
}
A function without parameter and return
value
#include<conio.h>
void main()
{
clrscr();
int a=10,b=20;
int sum();
int c=sum(); /*actual arguments
Cout<<“sum is”<< c;
getch();
}
int sum() /*formal arguments
{
int x=10,y=20;
return(x+y); /*return value
}
Default arguments
• In the function prototype (declaration) ,
the default values are given. Whenever a
call is made to function without
specifying an argument , the program
will automatically assign values to the
parameters from the default function
prototype.
• Default arguments facilitate easy
development and maintenance of
programs.
#include<iostream.h>
void main()
{
void sum(int x=10, int y=20);
sum();
}
• I/O Operations:
– Input: A stream that flows from an input device (
i.e.: keyboard, disk drive, network connection) to
main memory
– Output: A stream that flows from main memory to
an output device ( i.e.: screen, printer, disk drive,
network connection)
Iostream Library Header Files
• iostream library:
– <iostream.h>: Contains cin, cout, cerr, and clog
objects
– <iomanip.h>: Contains parameterized stream
manipulators
– <fstream.h>: Contains information important to
user-controlled file processing operations
Stream Input/Output Classes and Objects
• ios:
– istream and ostream inherit from ios
• iostream inherits from istream and ostream.
• << (left-shift operator)
– Overloaded as stream insertion operator
• >> (right-shift operator)
– Overloaded as stream extraction operator
– Both operators used with cin, cout, cerr, clog, and
with user-defined stream objects
Stream-Insertion Operator
• << is overloaded to output built-in types
– Can also be used to output user-defined types
– cout << ‘\n’;
• Prints newline character
– cout << endl;
• endl is a stream manipulator that issues a newline character
and flushes the output buffer
Cascading Stream-Insertion/Extraction
Operators
• << : Associates from left to right, and returns a
reference to its left-operand object (i.e. cout).
– This enables cascading
– cout << "How" << " are" << " you?";
• What is overloading
– Overloading means assigning multiple
meanings to a function name or operator
symbol
– It allows multiple definitions of a function
with the same name, but different signatures.
• C++ supports
– Function overloading
– Operator overloading
Why is Overloading Useful?
• Function overloading allows functions that
conceptually perform the same task on
objects of different types to be given the
same name.
• Local Variable
• Global variable
• Local Variables are defined inside the
function body or in a compound
statement. The scope of these variables
are inside the function where they are
defined.
Eg: int fact (int n)
{
int i, fact, j; // i, j are local variables.
-----
----
}
• Global variables are those variables whose
scope is available through out the program.
Static Data Members
A data member of a class can be qualified as static. A
static member variable has certain special
characteristics. These are:-
• It is initialized to zero when the first object of its class
is created. No other initialization is permitted.
• Only one copy of that member is created for the entire
class and is shared by all the objects of that class, no
matter how many objects are created.
• It is visible only within the class, but its lifetime is the
entire program.
Static Data Members
• The type and scope of each static
member variable must be defined outside
the class definition.
• They are also known as class variables
since they are associated with the class
itself rather than with any class object.
Static Member Functions
struct employee_type
{
int code;
char name[20];
int dept_code;
float salary;
};
• No variable has been associated with this
structure
• No memory is set aside for this structure.
Structure variable Declaration
• Syntax:-
Struct structure_name obj_name1, obj_name2;
At this point, the memory is set aside for the structure
variable employee.
Eg:- the object of structure student can be declare as
follows:
Struct student
{
Char name;
Int rollno;
Int reg no;
};
Object/ variable declaration
• Void main()
{
student data; //object declaration
data.name; //calling of name field
data.rollno; //calling of rollno field
data.regno; //calling of reg no field
}
How the elements of the structure variables
are stored in memory
1197
1198
var 1 1199
1200
1201
var 2 1202
1203
1204
1205
var 3
1206
1207
1208
var 4
1209
1210
1211
Intializing Structures
struct student_type
{
int rollno;
char name[25];
int age;
float height;
};
struct student_type student={1000,”Surbhi
salaria”,18,5.6};
Entering Data into Structures
Void main()
{
struct employee_type
{
int code;
char name[25];
char dept[15];
float salary;
}; continue
struct employee_type employee;
cout<<“\n\nParticulars of emp as entered by user\n”;
cout<<“\nEnter employee code:\n”; cout<<“\nEmployees code:”<<employee.code;
cin>>employee.code; cout<<“\nEmployee’s name:”<<employee.name;
cout<<“\nEmployee’s dept:”<<employee.dept;
cout<<“\nEnter name:\n”; cout<<“\nEmployee’s sal:”<<employee.salary;
gets(employee.name);
cout<<“\nEnter employee’s dept:\n”;
gets(employee.dept);
cout<< “\nEnter employee’s salary:\n”;
cin>>employee.salary; }
Use of Assignment Statement for
Structures
• Value of one structure variable can be assigned to
another variable of the same type using simple
assignment statement.if student1 and student2
are structure variable of type student_type,then
student2=student1;
Assigns value of structure variable student1 to
student2
WAP to copy structure elements
from one object to another object
#include<iostream.h>
#include<conio.h>
#include<string.h>
main()
{
Struct disk
{
Char name[15];
Float type;
Int price;
};
struct disk d1={“sony”,1.44,20};
struct disk d2,d3;
strcpy(d2.name,d1.name);
d2.type=d1.type;
d2.price=d1.price;
d3=d2;
Cout<<d1.name<<d1.type<<d1.price;
Cout<<d2.name<<d2.type<<d2.price;
Cout<<d3.name<<d3.type<<d3.price;
getch();
}
Difference b/t array and structure
Void main()
{
Struct student
{
int subject1;
int subject2;
int subject3;
};
int i,total=0;
float av;
struct student st[20];
for(i=0;i<=5;i++)
{
cout<<“enter the marks of 3subjects of “<<i+1
<<“student”,;
cin>>st[i].subject1;
cin>>st[i].subject2;
cin>>st[i].subject3;
total= st[i].subject1+ st[i].subject2+ st[i].subject3;
av=total/3;
Cout<<“avg of marks of “<<i+1<<“student is=“<<av;
}
getch();
}
Array within Structure
char name[20]; }
char grade;
}s;
main()
{
cout<<“\nEnter rollno,name and grade of student:\n”;
cin>>s.rn>>s.name>>s.grade;
display(s);
getch();
}
UNION
• Is an instant of a class.
• In terms of variables, class would be the type
and an object would be a variable.
Classes in C++
class class_name
{
…. Class body (data member +
…. methods)
….
};
Class name
class class_name
{
private: Public members or methods
…
…
…
public:
…
…
…
};
Private:
only members of that class have accessibility
• can be accessed only through member
functions of that class i.e by the functions
declared inside the class only.
• Arrays
– Structures of related data items
– Static entity - same size throughout program
• A few types
– C-like, pointer-based arrays
– C++, arrays as objects
Arrays
• Array
– Consecutive group of memory locations
– Same name and type
• To refer to an element, specify
– Array name and position number
• Format: arrayname[ position number ]
– First element at position 0
– n element array c:
– c[ 0 ], c[ 1 ]…c[ n - 1 ]
• Array elements are like normal variables
– c[ 0 ] = 3;
– cout << c[ 0 ];
• Performing operations in subscript. If x = 3,
– c[ 5 – 2 ] == c[ 3 ] == c[ x ]
Arrays
Name of array (Note that
all elements of this
array have the same
name, c)
c[0] -45
c[1] 6
c[2] 0
c[3] 72
c[4] 1543
c[5] -89
c[6] 0
c[7] 62
c[8] -3
c[9] 1
c[10] 6453
c[11] 78
• Function prototype:
– void modifyArray( int b[], int arraySize
);
– Parameter names optional in prototype
• int b[] could be simply int []
• int arraysize could be simply int
Sorting Arrays
• Sorting data
– Important computing application
– Virtually every organization must sort some data
• Massive amounts must be sorted
• Bubble sort (sinking sort)
– Several passes through the array
– Successive pairs of elements are compared
• If increasing order (or identical), no change
• If decreasing order, elements exchanged
– Repeat these steps for every element
Sorting Arrays
• Example:
– Original: 3 4 2 6 7
– Pass 1: 3 2 4 6 7
– Pass 2: 2 3 4 6 7
– Small elements "bubble" to the top
Computing Mean, Median and
Mode Using Arrays
• Mean
– Average
• Median
– Number in middle of sorted list
– 1, 2, 3, 4, 5 (3 is median)
• Mode
– Number that occurs most often
– 1, 1, 1, 2, 3, 3, 4, 5 (1 is mode)
Searching Arrays: Linear Search and
Binary Search
• Search array for a key value
• Linear search
– Compare each element of array with key value
– Useful for small and unsorted arrays
• Binary search
– Can only be used on sorted arrays
– Compares middle element with key
• If equal, match found
• If key < middle, repeat search through the first half of the
array
• If key > middle, repeat search through the last half of the
array
– Very fast; at most n steps, where 2^n > # of
elements
• 30 element array takes at most 5 steps
n
– 2 > 30
5
Multiple-Subscripted Arrays
• Multiple subscripts - tables with rows, columns
– Like matrices: specify row, then column.
1 2
3 4
1 0
3 4
Multiple-Subscripted
Arrays
// variable address= p
// variable value=*p
Another Program
int a=20;
int *p;
p=&a;
Cout<<a<<&a;
Cout<<p<<&p<<*p;
P has an address 500
Variables, Addresses and Pointers
• main()
• Memory Value
{ • a (1001) 5
int a = 5; • b (1003) 6
int b = 6; • c (1005) 1001
int *c;
// c points to a
c = &a;
}
Pointer to pointer
void main()
{
int a=25,b=78,sum;
int *x,*y;
x=&a;
y=&b;
sum= *x + *y;
cout<<“Sum is : ”<<sum;
}
Assignment in pointers
int x = 5;
int &z = x; // z is another name for x
int &y ; //Error: reference must be initialized
cout << x << endl; -> prints 5
cout << z << endl; -> prints 5
z = 9; // same as x = 9;
int a=5;
int *p;
p=&a;
Cout<<p<<*p<<&p;
Int &b=a;
a=a+2;
Cout<<b;
Problems Associated With
Pointers: Null Pointer
• A null pointer is generally used to signify that
a pointer does not point to any object
• NULL pointer is a type of pointer of any data
type and generally takes a value as zero. This
is, however, not mandatory. This denotes that
NULL pointer does not point to any valid
memory address.
Example of Null Pointer
• int* exforsys;
• exforsys=0;
• The above statement denotes exforsys as an
integer pointer type that does not point to a
valid memory address. This shows that exforsys
has a NULL pointer value.
Difference between Null Pointer and
Void Pointer
class CLASSNAME
{
public:
CLASSNAME([parameter list]);
};
Example
#include<iostream.h>
#include<conio.h>
class Rectangle
{
private:
int length,breadth;
public:
Rectangle()
{
Length=5,breadth=6;
}
void area()
{
int a=(length*breadth);
cout<<“area is”<<a;
}
};
void main()
{
clrscr();
Rectangle r1;
r1.area();
getch();
}
Parameterized Constructor
#include<iostream.h>
class Rectangle
{
private:
int length,breadth;
public:
Rectangle(int a,int b)
{
length=a,breadth=b;
}
void area()
{
int a=(length*breadth);
cout<<“area is”<<a;
}
};
void main()
{
clrscr();
Rectangle r1(5,6);
Rectangle r2(7,8);
r1.area();
getch();
}
Copy constructor
Class counter
{
Int c;
public:
Counter();
Counter(int a)
{
C=a;
}
Counter(counter &ob)
{
cout<<“copy constructor invoked”;
C=ob.C;
}
}
Void show()
{
cout<<C;
};
Void main()
{
Clrscr();
Counter C1(10);
Counter C2(C1);
C1.show();
C2.show();
getch();
}
Default Constructor
class CLASSNAME
{
……………….
public:
~CLASSNAME();
};
Example
main()
{ void xyz()
Class abc {
{ If(a>b)
Private: big=a;
Public: big=b;
{ }
Cin>>a>>b; } {
cout<<destructor is under wrk”;}
};
Class abc obj;
obj.xyz();
}
Pointers and classes
}
void book::putdata()
{
cout<<"price is"<<price<<"\n";
cout<<"year is"<<year<<"\n";
}
book::book()
{
price=0;
year=0;
}
int main()
{
book b1,b2(10,50);
b1.putdata();
b2.putdata();
getch();
}
Multiple Constructors
in a class
class marks
{
int n, m;
public:
marks()
{
n=0; m=0;
}
marks(int x,int y)
{
n=x; m=y;
}
void add()
{
cout<<(n+m);
}
};
void main()
{
marks ob(4,5);
ob.add();
}
Copy Constructor
A copy constructor is a special in
constructor
void main()
{
string str1("George");
string str2 = str1; // default copy constructor
str2.copy("Mary");
class string {
private:
char *s;
int size;
public:
string(char *); // constructor
~string(); // destructor
string(const string&); // copy constructor
void print();
void copy(char *);
};
string::string(const string& old_str)
{
size = old_str.size;
s = new char[size+1];
strcpy(s,old_str.s);
}
void main()
{
string str1("George");
string str2 = str1;
str1.print(); // what is printed ?
str2.print();
str2.copy("Mary");
str1.print(); // what is printed now ?
str2.print();
}
void main()
{
rectangle rc(3.0, 2.0, 1, 3);
C++ statements;
}
What is a destructor?
• It is a member function which deletes an
object.
• A destructor function is called automatically
when the object goes out of scope:
– (1) the function ends
– (2) the program ends
– (3) a block containing temporary variables ends
– (4) a delete operator is called
• A destructor has:
– (i) the same name as the class but is preceded by a
tilde (~)
– (ii) no arguments and return no values
class string {
private:
char *s;
int size;
public:
string(char *); // constructor
~string(); // destructor
};
string::string(char *c)
{
size = strlen(c);
s = new char[size+1];
strcpy(s,c);
}
string::~string()
{
delete []s;
}
Comments on destructors
• If you do not specify a destructor, the
compiler generates a default destructor
for you.
• When a class contains a pointer to
memory you allocate, it is your
responsibility to release the memory
before the class instance is destroyed.
#include <iostream.h>
#include <string.h>
class string {
private:
char *s;
int size;
public:
string(char *); // constructor
~string(); // destructor
void print();
void copy(char *);
};
void string::print()
{
cout << s << endl;
}
Data File Handling
Introduction
• ifstream infile(“data”);
outfile<<“total”;
outfile.close();
infile>> string;
Opening files using member
function open()
• This function is used to open multiple files
that uses same stream object.
• Syntax:-
file_stream class stream_object;
stream_object.open(“filename”);
Example
ofstream outfile;
outfile.open(“Data”);
…………………..
…………………..
outfile.close();
outfile.open(“Data2”);
…………………….
…………………..
outfile.close();
Open(): File Modes
stream-object.open(“filename”,mode);
• EOF()
Void main()
{
Ifstream infile;
Infile.open(“text”);
While(!infile.eof())
{
------
-----
}}
• FAIL()
Main()
{
Ifstream infile;
Infile.open(“text”);
While(!infile.fail())
{
Cout<<“cudn’t open a file”;
}}
Reading and Writing in Files
1) ofstream fileout;
fileout.open(“hello”,ios::app);
2)fileout.open(“hello”, ios::in | ios::out);
Files
• A file is a collection of related data stored
in a particular area on the disk.
• Programs can be designed to perform
the read and write operations on these
files
• A program involves either or both of
following kinds of data communication:
– Data transfer between the console unit and the
program
– Data transfer between the program and a disk
file
Introduction
• Computer programs are associated to work
with files as it helps in storing data &
information permanently.
• File - itself a bunch of bytes stored on some
storage devices.
• In C++ this is achieved through a component
header file called fstream.h
• The I/O library manages two aspects- as
interface and for transfer of data.
• The library predefine a set of operations for
all file related handling through certain
classes.
• C++ provides a new technique for
handling I/O operations through
mechanism known as streams.
• A stream refers to a flow of data.
• Classified in 2 categories:
1. Output stream
2. Input stream
In output stream flow of data is from
program to the output device.
In input stream the flow of data is from
input device to a program in main
memory.
Classes for file stream
operations
• The I/O system of C++ contains a set of
classes that define the file handling
methods.
• These include:
– ifstream
– ofstream
– fstream
– These classes are derived from fstreambase
and from corresponding iostream class
Why to use Files:
• Convenient way to deal large quantities of data.
• Store data permanently (until file is deleted).
• Avoid typing data into program multiple times.
• Share data between programs.
• We need to know:
how to "connect" file to program
how to tell the program to read data
how to tell the program to write data
error checking and handling EOF
Opening and closing a file
• If we want to use a disk file, we need to
decide the following things:
– Suitable name for the file
– Data type and structure
– Purpose
– Opening Method
Filename
• The file name is a string of characters
that make up a valid filename for the
operating system.
• It has two parts, a primary name and an
optional period with extension
• Example:
– Input.data
– Test.doc
Opening a file
• For opening a file, we must first create a
file stream and then link it to the
filename.
• A file stream can be defined using the
classes ifstream, ofstream and fstream
that are contained in the header file
fstream
• A file can be opened in two ways:
– Using a constructor function of the class
– Using the member function open() of the class
Opening files using constructor
• Constructor is used to initialize an object
while it is being created. Here, a filename
is used to initialize the file stream object.
• This involves following steps:
– Create a file stream object to manage the
stream using appropriate class
– Initialize the file object with the desired
filename.
• For example:
– ofstream outfile(“results”); // output only
• This creates outfile as an ofstream object
that manages the output stream.
• This statement opens the file results and
attaches it to the output stream outfile
• The following statement declares infile
as an ifstream object and attaches it to
the file data for reading
– ifstream infile (“data”); //input only
– The program may contain statements like:
– outfile<<total;
– outfile<<sum;
– infile>>number;
– infile>>string
• We can also use same file for both reading
and writing data
Program1
……..
ofstream outfile(“salary”); //creates outfile and connects “salary”
to it
……...
Program2
……….
ifstream infile(“salary”); //creates infile and connects “salary” to
it
– ………
• Instead of using two program, one for
writing data and another for reading
data, we can use single program to do
both operations on file.
– …..
– outfile.close(); //disconnect salary file from
outfile
– ifstream infile(“salary”); // and connect to
infile
– …..
– …..
– infile.close();
example
#include<fstream.h> ifstream inf(“item”);
#include<iostream.h> inf>>name;
main()
{ char name[30]; inf>>cost;
float cost; cout<<”item
ofstream name”<<name;
outf(“item”); cout<<“item
cout<<“enter item cost”<<cost;
name”;
cin>>name; inf.close();
outf<<name; getch();
cout<<“enter cost”; }
cin>>cost;
outf<<cost<<“\n”;
outf.close();
Opening file using Open()
• This function is used to open multiple
files that uses same stream object.
• Syntax:-
file_stream class stream_object;
stream_object.open(“filename”);
ofstream outfile;
outfile.open(“Data1”);
…………………..
…………………..
outfile.close();
outfile.open(“Data2”);
…………………….
…………………..
outfile.close();
#include<fstream.h> const int n=80;
#include<iostream.h> char line[n];
main() ifstream fin;
{ ofstream fout; fin.open(“country”);
fout.open(“country”); cout<<“contents of country
fout<<“usa\n”; file”;
fout<<“uk\n”; while(fin)
fout<<“india\n”; { fin.getline(line,n);
fout.close(); – cout<<line;
}
fout.open(“capital”); fin.close();
fout<<“washinton\n”; fin.open(“capital”);
fout<<“london\n”; cout<<“contents of capital
fout<<“india\n”; file”;
fout.close(); while(fin)
{ fin.getline(line,n);
– cout<<line;
}
fin.close();
getch();
}
Detecting end-of-file
• This condition is necessary for preventing
any further attempt to read data from the
file.
while(fin)
here fin is ifstream object which returns a
value 0 if any error occur in file including
end-of-file condition.
if(fin1.eof()!=0)
{ exit(1);}
eof() is a member function of class ios. It
returns non zero value if the end-of-file(eof)
condition is encountered and zero
otherwise.
Reading from files simultaneously
fin1.getline(line,size);
#include<fstream.h> cout<<"capital of"<<line;
#include<iostream.h> if(fin2.eof()!=0)
#include<conio.h> {
#include<stdlib.h> cout<<"exit from capital\n";
main() exit(1);
{ }
const int size=80; fin2.getline(line,size);
char line[size]; cout<<line<<endl;
}
ifstream fin1, fin2; getch();
fin1.open("country"); }
fin2.open("capital");
for(int i=1;i<=3;i++)
{
if(fin1.eof()!=0)
{ cout<<"exit from
country\n";
exit(1);
}
Open(): File Modes
• We can have two arguments in open(), to specify
the file-mode.
stream-object.open(“filename”,mode);
the second argument mode specifies the purpose
for
which file is opened and mode known as file mode
parameter.
Parameter Meaning
ios::app Append to
end-of-file
ios::ate Go to end of file on
opening
ios::binary Binary file
ios::in Open file for
reading only
ios::nocreate Open fail if file
does not exist
ios::noreplace Open fail if file already
exist
int n=file_size/ob_len;
Inheritance
• The mechanism of creating a new class
from an existing class is known as
inheritance.
Types of Inheritance
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance
• Syntax:
class DerivedClassName : access-level BaseClassName
where
– access-level specifies the type of derivation
• private by default
• Public
• Protected
• Any class can serve as a base class
– Thus a derived class can also be a base class
Examples
Class ABC : private XYZ//private derivation
{
Members of ABC
};
Class ABC : public XYZ //public derivation
{
Members of ABC
};
Class ABC : XYZ //private derivation by default
{
Members of ABC
};
Public vs private inheritance
• The public keyword in the inheritance
syntax means that publicly accessible
members inherited from the base class
stay publicly accessible in the derived
class
• But sometimes its preferable to inherit
the public members of a parent in such a
way that they become private in the child
Private inheritance
• Public members of base class become
private members of derived class
• Public and protected members are only
available to derived-class member
functions - not to a derived object.
Protected inheritance
• private members of the base class are
not accessible in the derived class (to
preserve encapsulation)
• Protected qualification allows
encapsulated data members which are
not publicly accessible to be accessible
by derived classes
• ("Protected" members are not accessible
from outside the class, except in derived
classes)
Class B
Not
Private Inheritable
Protecte
d
Public
ClassD2:private B
Class D1:public
B
Private Private
Protecte Protected
d Public
Public
Multiple Single
A B A
C B
C1.B::input()
Overriding in Single Inheritance
#include<iostream.h>
#include<conio.h> void show(int b)
class A { y=b;
{ int x; cout<<"y of class B =
public: "<<y<<"\n";
void show(int a) }
{ };
x=a; int main()
cout<<"x of class A = {
"<<x<<"\n"; B obj;
}
};
obj.show(10);
class B: public A
{
getch();
int y;
public:
return 0;
}
Ambiguity resolution in Inheritance
Class M Class P:public M, public N
{ {
Public: Public:
void display(void) void display(void)
{ {
cout<<“class M”; M::display();
} }
}; };
Class N // Ambiguity may also arise
{ in single inheritance .
public: Derived class overrides
the inherited function
void display(void)
{
cout<<“class N”;
}
};
Hybrid Inheritance
Record – Student
– Test score
Marks Avg –
– result
Result – //Multiple copies of
the variables of
student class are
generated
Virtual base class
Class A
{ …….
– A ………..};
– B1 B2 Class B1:virtual public
–
A
– C {…….
…….};
Class B2:public virtual
A
{…….
……..};
Class C:public
B1,public B2
{………
………}; //only one
copy of A will
be inherited
Virtual base class
class test : virtual public
student
class student
{
{ protected: float part1,part2;
protected: int roll_no; public:
public: void get_marks(float x,
float y)
void get_no(int a)
{ part1=x; part2=y;}
{ void put_marks()
roll_no=a; { cout<<“marks
} obtained”<<“part1”<<part1<
<“part2”<<part2;}
void put_no(void) };
{ class sports: public virtual
cout<<“roll no. student
:”<<roll_no; {
} protected : float score;
public:
};
void get_score(float s)
{ score=s; }
Virtual base class
void put_score() int main()
{ {
cout<<“sports wt:”<<score; result student1;
} student1.get_no(100);
}; student1.get_marks(50.5,65.
class result : public test , public 2);
sports student1.get_score(10.5);
{ student1.display();
float total; return 0;
public: }
void display(void);
};
void result::display(void)
{
total= part1+part2+score;
put_no();
put_marks();
put_score();
cout<<“total score: “<<total;
}
Abstract Class
• An abstract class is one that is not used
to create objects.
• An abstract class is designed only to act
as a base class i.e. to be inherited by
other classes.
• It is a design concept in program
development and provides a base upon
which other classes may be built.
Order of Constructors and destructors
in derived classes
• Derived-class constructor
– Calls the constructor for its base class first to initialize its
base-class members
– If the derived-class constructor is omitted, its default
constructor calls the base-class’ default constructor
• Destructors are called in the reverse order of
constructor calls.
– Derived-class destructor is called before its base-class
destructor
Order of Constructors in derived
classes
Class B:public A
{ //A() base constructor
}; //B() derived constructor
• Aggregation
– “has a” relationship
Aggregation and Inheritance
• In general, the difference between
inheritance
and aggregation is the difference between
the
is-a relationship and the has-a relationship.
For example,
– an apple is fruit; thus, you would use
inheritance to model the relationship
between
the classes Apple and Fruit.
– A person has a name; thus, you would
use aggregation to model the
relationship
between the classes Person and Name.
Aggregation
A tire has a circle as its boundary:
class Tire
{
private
String rating;
Circle boundary;
}
Example
• Types
– Built in (int, char) or user-defined
– Can use existing operators with user-defined types
• Cannot create new operators
• Overloading operators
– Create a function for the class
– Name function operator followed by symbol
• Operator+ for the addition operator +
8.2 Fundamentals of Operator
Overloading
• Cannot change
– How operators act on built-in data types
• I.e., cannot change integer addition
– Precedence of operator (order of evaluation)
• Use parentheses to force order-of-operations
– Associativity (left-to-right or right-to-left)
– Number of operands
• & is unitary, only acts on one operand
• Cannot create new operators
• Operators must be overloaded explicitly
– Overloading + does not overload +=
8.3 Restrictions on Operator Overloading
8.6 Overloading Unary Operators
• Upcoming example
– If non-member function, needs two arguments
– Example:
• class String {
• friend const String &operator+=(
• String &, const String & );
• ...
• };
– y += z equivalent to operator+=( y, z )
• Reserves memory from a much larger
free store, or heap
• Gives the programmer a pointer to refer
to this memory
There are two types of memory
management operators in C++:
• new
• delete
Concrete
Classes
• An interface is a collection of
constants and method declarations
• An interface describes a set of
methods that can be called on an
object
• The method declarations do not
include an implementation
– there is no method body
What is an Interface?
• A child class that extends a parent
class can also implement an
interface to gain some additional
behavior
• Implementing an interface is a
“promise” to include the specified
method(s)
• A method in an interface cannot be
made private
When A Class Definition
Implements An Interface:
• It must implement each method in
the interface
• Each method must be public (even
though the interface might not say
so)
• Constants from the interface can
be used as if they had been
defined in the class (They should
not be re-defined in the class)
Declaring Constants with
Interfaces
• Interfaces can be used to declare
constants used in many class
declarations
– These constants are implicitly public,
static and final
– Using a static import declaration
allows clients to use these constants
with just their names
Implementation vs. Interface
Inheritance
Implementation Interface Inheritance
Inheritance • Functionality lower in
• Functionality high in hierarchy
the hierarchy • Superclass specifies
• Each new subclass one or more abstract
inherits one or more methods
methods declared in • Must be declared for
superclass each class in
• Subclass uses hierarchy
superclass • Overridden for
declarations subclass-specific
implementations
Creating and Using
Interfaces
• Declaration begins with interface
keyword
• Classes implement an interface
(and its methods)
• Contains public abstract methods
– Classes (that implement the interface)
must implement these methods
Creating and Using
Interfaces
• Consider the possibility of having a
class which manipulates
mathematical functions
• You want to send a function as a
parameter
– Note that C++ allows this directly
– Java does not
• This task can be accomplished with
interfaces
POLYMORPHISM
• Polymorphism means many (poly) shapes
(morph)
• It can be defined one interface multiple
methods which means that one interface can
be used to perform different but related
activities.
• It is achieved by two ways:
• Overloading
• Overriding
Run time(Dynamic)Polymorphism
• In this dynamic binding is performed
• In dynamic binding the decision regarding the
selection of appropriate function to be called
is made by compiler at run time.
• This is because the information pertaining to
the selection of appropriate function
definition corresponding to a function call is
known only at the run time.
• It is also called the late binding as the
compiler delays the binding decision until run
time.
• The advantage is that it allows greater
flexiability by enabling user to create class
libraries that can be reused and extended as
per requirement
• The disadvantage is that there is little less od
execution speed as compiler will have to
perform certain overheads at run time
VIRTUAL FUNCTIONS
• Exception Handling
• Exception are the errors that occur at run
time and can stop the working of the
program abruptly.
• They can occur in various situations- one
such condition when the number is divided
by 0.
• For handling such exceptions we have an
error handling mechanism called as
exception handling.
Objective