Anda di halaman 1dari 36

Programming with C++

Computer Languages: The computer can understand only the high and low voltage
power supplies which are represented by 0 and 1 respectively. Instructions given to
computer with such binary code (1 & 0) representation are called the machine language
instructions. To do programming in machine code is very difficult so computer languages
were designed. These languages are classified into two types:
1. Low Level Language
2. High Level Language
Low Level Language: A low level language is called assembly language is designed in
the beginning. It has a simple instruction set of command through which all the tasks are
done. The Instructions given to the computer are not binary codes but are of English
words like MOV, LOAD etc. Hence writing program in assembly was much easier and
simpler than machine code. But still the computer can understand only the machine
language. Hence a converter or translator is developed to translate the low level language
program into machine language. This translator is called an assembler.
High Level Language: These were English like languages and hence the programmers
found them very easy to learn. To convert the program written in higher level language
into machine level language, compilers and Interpreter are used. Examples of High Level
Languages are FORTRAN, COBOL, Pascal, and C.
History of C++: C++, an extension of c, as developed by Bjarne Stroustrup in the early
1980s at Bell Laboratories. C++ provides a number of feature that upgrade the C
Language, but more impotently, it provides the capabilities for object-oriented
programming.
Characteristics of C++:
1. Simplicity
2. Platform Independent
3. Architectural Neutral
4. Support OOPs and its feature
a. Object
b. Class
c. Encapsulation
d. Data Abstraction
e. Inheritance
f. Reusability
g. Polymorphism
5. Error Handling
6. Pointers
7. File Handling
8. Case Sensitive

Visit engineerhunt for more::


Identifier: Identifiers are the names given to various program elements, such as
variables, functions and array. Identifiers consist of letters and digits, in any order, except
the first character must be a letter.
Keywords: The Keywords are identifiers that are reserved for their special purpose.
These words are not redefined by the user as these words are reserved words. For
example if, int and void etc.
Data Types in C++: There are following three data types in C++
1. Character
2. Integer
3. Float
Type
int
long int
float
double
char

Bytes
2
4
4
8
1

Range
-32768 to 32767
-2147483648 to 2147483647
3.4E-38 to 3.4E+38
1.7E-308 to 1.7E+308
-128 to 127

Constant: Constants are the data elements, whose value does not change throughout the
program.
Escape Sequence: Escape Sequence are commands included with standard output object
(cout) to perform specific actions:
Escape Sequence
Action
\a
sounds a bell
\b
moves cursor back 1 space
\n
next Line
\t
horizontal tab
\r
return
//
for comment statement
Variables: Variables are place holder in memory which is used to store some values. For
example: int a,b,c;
char d;
Operators in C++:
In C++ there are different types of operators:
1. Assignment Operator
2. Arithmetic Operator
3. Relational Operators.
4. Logical Operators.

1. Assignment Operator (=): An assignment operator is used to assign the value


back to a variable.
2. Arithmetic Operator (+, -, *, /, %) : Arithmetic operators are used for
performing most common operations of mathematics like addition, subtraction
etc.
3.
Relational or Comparison Operator (<,>, <=,>=, = =,! =): Relational operators
are used to compare the value of the variable if they are less than or equal to or
greater than the other and so on.
4. Logical Operator ( &&,||, !): logical operators are used to check for more than
one condition in a single expression.
The logical AND (&&) operators are used along with comparison operators.
When two conditions are used along with logical && operator and if both the
condition are true it returns true. If one or both the conditions are false then the value
returned by the expression is 0.
The Logical Operator OR (||) is also used with comparison operators. When
the two conditions are used along with logical (||) operator, and if either both the
condition are true or any one of the conditions is true then the expression will return true.
The expression with logical OR operator will return false if and only if both the
conditions are false.
Logical NOT (!) is generally used with comparison operators to negate their
effect.
Increment and Decrement: (++ ,--) The increment ++ add 1 to its operand and
Decrement operator subtracts one.
For example:
a=a+1 or a++
a=a-1 or a
Ternary Operator: C++ includes a very special operator called the ternary operator or
conditional operator. The ternary operator acts like a shorthand version of the if-else
condition. The general format of the ternary operator is:
Expr1? Expr2: Expr3
For example: x=10
Y=x>9?100:200;
The sizeof Operator: The sizeof() operator returns the size (in bytes) of an object or data
types.
For example:
Int x;
Sozeof(x);

Data Input and Output: cin and cout are the two predefined objects which represent
standard input and output stream. These objects are the members of iostream class.
Hence the header file <iostream.h> should be included in the beginning of all the
programs.
cout: The cout is used to display an object onto the video screen. The << insertion
operator is used along with the cout statement.
cout<<Welcome to c++;
cin: The cin statement is used to read a number, a character or a string of characters
from a standard input device, normally the keyboard. The extraction operator >> is used
with cin statement.
Cin>>varaiable;
Write a program to calculate the sum of two numbers:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a,b;
cout<<Enter first number:;
cin>>a;
cout<<Enter second number:;
cin>>b;
cout<<Sum=<<a+b;
getch();
}
Write a program to find circumference of a circle:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
float pi=3.14, c;
int r;
cout<<Enter the radius:;
cin>>r;
c=2 * pi * r;
cout<<endl;
cout<<The circumference of Circle is:<<c;

getch();
}
Write a program to swap two numbers using third variable:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a,b ,temp;
cout<<Enter the first number:;
cin>>a;
cout<<Enter the second number:;
cin>>b;
temp=a;
a=b;
b=temp;
cout<<endl;
cout<<The value numbers after swapping is :
cout<<\nFirst number:< <a;
cout<<\nSecond Number:<<b;
getch();
}
Write a program to obtain the gross salary by calculating DA, HRA and TA:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int bs,da,hra,ta,gs;
cout<<Enter the basic salary:;
cin>>bs;
da=500;
hra=1000;
ta=300;
gs=bs+hra+ts+da;
cout<<\nThe gross salary=<<gs;
getch();
}

Write a program to convert kilometer into meters:


#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int km,m;
cout<<Enter the distance in Kilometer:;
cin>>km;
m=km * 1000;
cout<<\n The distance in meter is:<<m;
getch();
}

Control Statements:
1. Sequential
2. Conditional
a. Branching
i. If
ii. If-else
iii. Nested-if
iv. Switch
b. Looping
i. For
ii. While
iii. Do-while
3. Unconditional
a. Goto
b. Break
c. Continue
Conditional Statements:
Branching:
1. If Statement: An if statement test a particular condition. If the condition is true
then statement or set of statement is executed. If the condition evaluates to false
then it will come out of loop. The syntax is:
if (expression)
{
statements;
}

For example:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int marks;
cout<<Enter Marks:;
cin>>marks;
if (marks>40)
{
cout<<Passed;
}
getch();
}
2. if-else Statement: When the condition is false then other set of statements will be
executed i.e. the else part of the if loop will be executed. The syntax is:
if (expression)
{
statements;
}
else
{
statements;
}
for example:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int marks;
cout<<Enter marks:;
cin>>marks;
if (marks>40)
{
cout<<Passed;
}
else
{
cout<<Failed;
}
getch();

}
3. Nested if Statement: A nested if is an if that has another if in its body or in its
elses body. The syntax is:
If (expression)
{
if (expression)
{
statements;
}
else
{
statements;
}
}
else
{
statements;
}
For example:
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char id[20],pass[20];
cout<<Enter your ID:;
cin>>id;
cout<<Enter Password:;
cin>>pass;
if (strcmp(id,scott)==0)
{
if (strcmp(pass,tiger)==0)
{
cout<<Welcome to c++ Programming world;
}
else
{
cout<<Wrong Password;
}
}
else
{
cout<<Wrong ID;
}

getch();
}
4. Switch Statement: The switch statement is a special multiway decision maker
that tests whether an expression matches one of the number of constant values.
Syntax of the switch statement is:
Switch(expression)
{
case constant1:
statement;
break;
case costant2:
statement;
break;
default:
statement;
};
for example:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a,b, result;
char ch;
cout<<Enter first number:;
cin>>a;
cout<<Enter second Number:;
cin>>b;
cout<<\n--------------Select operation------------;
cout<<\n(+) Addition;
cout<<\n(-) Subtraction;
cout<<\n(*) Multiplication;
cout<<\n(/) Division;
cout<<\nEnter your choice:;
cin>>ch;
switch (ch)
{
case +:
result=a+b;
break;
case -:
result=a-b;
break;
case *:
result=a*b;
break;

case /:
result=a/b;
break;
default:
cout<<\nWront input;
}
cout<<endl<<The calculated result is:<<result;
getch();
}
Loop Statements: The loop statements allow a set of instructions to be performed
repeatedly until a certain condition is fulfilled. The following loop structures are
supported by c++:
1. for loop
2. while loop
3. do-while loop
1. for loop: The for loop is the simplest and most commonly used loop in c++. This
loop consists of three expressions. The first expression is used to initialize the
index value, the second is used to check whether or not the loop is to be continued
again and third to change the index value for further alternation.
The syntax of the for loop is:
for(initialization expression; expression2; expression3)
{
body of the loop;
}
for example
Write a program to find sum of ten different numbers using for loop
#include<iostream.h>
#include<conio.h>
void main()
{
int n,i.sum=0;
clrscr();
cout<<Enter any ten numbers;
cout<<endl;
for (i=0;i<=9;i++)
{
cout<<\nEnter number :;
cint>>n;
sum=sum+n;
}
cout<<\nThe sum of the Entered numbers is:<<sum;
getch();

10

}
2. While Loop: The second loop available in c++ is the while loop. The while loop
is used when we are not certain that the loop will be executed. After checking
whether the initial condition is true or false and finding it to be true, only then the
while loop will enter into the loop operations. The general form of while loop is:
While (condition)
{
statements;
}
For example
Write a program to generate even series from 1 to 50 using while loop
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i;
i=0;
cout<<The series of even no. from 1 to 50 is:;
while(i<=50)
{
cout<<i<<\t;
i=i+2;
}
getch();
}
3. Do While: The do-while loop is another repetitive loop used in c++ programs.
Whenever one is certain about a test condition, then the do-while loop can be
used, as it enters into the loop at least once and then checks whether the given
condition is true or false. As long as the test condition is true, the loop operations
or the statements will be repeated again and again.
Syntax is:
Do
{
Statements;
} while (condition);
For example:
Write a program to generate odd series from 1 to 50 using do-while loop.
#include<iostream.h>
#include<coniol.h>
void main()

11

{
clrscr();
int i;
i=1;
cout<<The series of odd no. from 1 to 50 is:<<endl;
do
{
cout<<i<<\t;
i=i+2;
}while (i<=50);
getch();
}
Unconditional Statements:
Break Statement: The break statement is normally used in the switch case loop
and in each case condition, break statement must be used, If not, the control will
be transferred to the subsequent case condition.
Syntax is :
break;
For example:
Write a program to search a number from 1 to 50 using break
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i,n;
cout<<Enter the no. to search between 1 to 50:;
cin>>n;
cout<<endl<<The search begins now:<<endl;
for(i=1;i<=50;i++)
{
cout<<i<<endl;
if (i==n)
{
cout<<At last! I arrived the number;
break;
}
}
getch();
}

12

Continue statement: The continue statement is used to repeat the same operation
once again even if it checks the error. The general syntax of the continue
statement is:
continue;
for example:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i,n;
for( i=0;i<=10;i++)
{
cout<<\nEnter the number:;
cin>>n;
if(n<=0)
{
cout<<negative value is not allowed reenter the value:;
continue:
}
}
getch();
}
Goto Statement: The goto statement is used to alter the program execution
sequence by transferring the control to some part of the program.
For example:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a,b;
cout<<Enter the run made by Shri Lankan Cricket Team:;
cin>>a;
cout<<Enter the run made by Indian Cricket Team:;
cin>>b;
if (a>b)
{
goto lanka;
}
else
{
goto India;
}

13

Lanka:
Cout<<\n Shri Lanka has won the match;
goto end;
India:
cout<<\n India has won the Match;
end:
cout<<\n this is the match result;
getch();
}
Write a program to generate a table of any number:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i,n;
cout<<Enter a number whose table is to be generated:;
cin>>n;
cout<<\n The Table is :<<endl;
for(i=1;i<=10;i++)
{
cout<<\n<<i<< * <<n<< = <<i*n;
}
getch();
}
Write a program to display the number is prime or not:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n,i,m;
cout<<Enter any number:;
cin>>n;
for(i=2;i<=n-1;i++)
{
m=n%i;
if(m==0)
{
cout<<\nThe number is not prime;
break;

14

}
else
{
cout<<\nThe number is prime;
break;
}
}
getch();
}
Write a program to find factorial of a given number:
#include<iostream.h>
#include<conio.h>
void main()
{
int n,fact,i;
clrscr();
cout<<Enter the number whose factorial is needed:;
cout<<n;
fact=1
for(i=1;i<=n;i++)
{
fact=fact*i;
}
cout<<The factorial of given number is:<<fact;
getch();
}
Write a program to generate Fibonacci series:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int f1,f2,f3,i,n;
cout<<Enter the value of n:;
cin>>n;
f1=0;
f2=1;
cout<<The series is:;
cout<<endl;
cout<<f1;
cout<<endl;

15

cout<<f2;
for(i=1;i<=n;i++)
{
f3=f1+f2;
cout<<endl<<f3;
f1=f2;
f2=f3;
}
getch();
}

Array:
An array is a collection of identical data objects or homogeneous type of data
objects which are stored in consecutive memory location under a common heading or a
variable name. The individual values in an array are called its elements. Array are sets of
same type, which have a single name followed by an index.
Types of Array
1. Single Dimension Array
2. Double Dimension Array
1. One Dimension Array:
For example:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a[10],i,n;
cout<<Enter how many no. to store in the array;
cin>>n;
for(i=0;i<n;i++)
{
cout<<\nEnter number:;
cin>>a[i];
}
cout<<\n Contents of the Array are:;
for(i=0;i<n;i++)
{
cout<<a[i]<<\n;
}
getch();
}
3. Double Dimension Array:
16

For example:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a[3][3],i,j;
cout<<Enter array elements for two dimensional Array:;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<\nEnter number:;
cin>>a[i][j];
}
}
cout<<\n Contents of the Array are:;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<\t<<a[i][j];
}
cout<<endl;
}
getch();
}

String Function: The most common of the string related inbuilt functions are:
1. Strlen: Shows the length of the string.
2. strcpy: Copies one string to another.
3. strcat: Combines two given strings
4. strcmp: Compares two strings
5. strlwr: Converts all characters in a string from uppercase to lowercase.
6. strrev: Reverses the character in the string.
7. strupr: Converts all characters in a string from lowercase to uppercase.
1. strlen():
#include<iostream.h>
#include<conio.h>

17

#include<stdio.h>
void main()
{
clrscr();
char name[20];
int l;
cout<<Enter any text:<<endl;
gets(name);
l=strlen(name);
cout<<The length of the entered text is :<<l;
getch();
}
2. strcpy():
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
char name1[20],name2[20];
cout<<Enter the text of string1:;
gets(name1);
strcpy(name2,name1);
cout<<The text of a string is:<<name1<<endl;
cout<<The text copied to string2 is:<<name2;
getch();
}
3. strcat():
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
char name1[20],name2[20];
cout<<Enter the first string1:;
gets(name1);
cout<<Enter the second string:;
gets(name2);
strcat(name1,name2);
cout<<The combined string is:<<name1;
getch();
}
4. strcmp():
#include<iostream.h>

18

#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
char pass[10];
cout<<Enter your password:;
gets(pass);
if (strcmp(pass,test)= =0)
{
cout<<Password is right welcome to c++;
}
else
{
cout<<Password is wrong;
}
getch();
}
5. strlwr():
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
char str[20];
cout<<Enter the string in upper case:;
gets(str);
cout<<The string in lower case is:<<strlwr(str);
getch();
}
6. strupr():
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
char str[20];
cout<<Enter the string in lower case:;
gets(str);
cout<<The string in upper case is:<<strupr(str);
getch();
}

19

7. strrev():
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
char str[20];
cout<<Enter the string :;
gets(str);
cout<<Reverse of the string is::<<strrev(str);
getch();
}
_____________________________________________________________________
Other most useful functions are isupper, islower, tolower,
toupper,isdigit,sqrt,pow,end,delay etc.
Isupper(): It is used to check the given character is in uppercase or not.
Islower(): It is used to check the given character is in lowercase or not.
Isdigit(): It is used to check the given value is digit or not.
Tolower(): To convert the character into lower case.
Toupper(): To convet the character into upper case.
Sqrt() : To find square root of the numeric value.
Pow(): to calculate the power of the numeric value.
End(): to terminate the program.
Delay(): To delay the execution of program.

Function:
A complex problem may be decomposed into a small or easy manageable parts or
modules called function. A function contains a set of statements which can be invoked
from any part of the program. In C++, the main() is also a function which invokes other
functions to perform various tasks. To create a function in c++ there are three stages:
Function Declaration
Function Definition
Function calling
Types of Function:
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.

20

1. Functions with no arguments and no return values.


#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
void msg();
msg();
getch();
}
void msg()
{
cout<<This is c++ function;
}
2. Functions with arguments and no return values.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
void sum(int ,int);
msg(10,20);
getch();
}
void msg(int a,int b)
{
cout<<Sum=<<a+b;
}
3. Functions with arguments and return values.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int msg(int,int);
int c;
c=msg(10,20);
cout<<Sum=<<c;
getch();
}

21

int msg(int a,int b)


{
return(a+b);
}

Structures:
Structure is a collection of heterogeneous type of data i.e. different types of data.
For example:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
struct student
{
char name[20];
int rollno;
};
void main()
{
clrscr();
student s;
cout<<Enter the name of the student:;
gets(s.name);
cout<<Enter the rollno of the student:;
cin>>s.rollno;
cout<<endl;
cout<<Rollno: <<s.rollno;
cout<<\nName:<<s.name;
getch();
}
Array of Structure:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
struct student
{
char name[20];
int rollno;
};
void main()
{
clrscr();
student s[10];
22

int n,i;
cout<<Enter how many students record you want to enter:;
cin>>n ;
cout<<\n Enter the students record:;
for(i=0;i<n;i++)
{
cout<<endl;
cout<<Enter the name of the student:;
gets(s.name[i]);
cout<<Enter the rollno of the student:;
cin>>s.rollno[i];
}
cout<<endl;
cout<<Rollno\t\tName;
for(i=0;i<n;i++)
{
cout<<s[i].rollno<<\t\t<<s[i].name;
}
getch();
}

Pointers:
A pointer is a variable, which holds the address of other variable.
For example:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a=10,*p;
p=&a;
cout<<Value of variable a using pointer:<<*p;
ocut<<Ther address of a:<<p;
getch();
}

23

Object Oriented Programming:


Class: A class is collection of objects which have similar characteristics. A class is a user
defined data type which holds both data and functions. The data included in the class i.e.
the internal data is called the member data and the functions included in the class are
called the member functions.
Object: An object can be physical existence of a class. In other words , an object is an
instance of a class.
For example :Funciton Definition inside the class
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class student
{
private:
int rollno;
char name[20];
public:
void input()
{
cout<<Enter rollno:;
cin>>rollno;
cout<<Enter student Name:;
gets(name);
}
void output()
{
cout<<\n Name of the Student:<<name;
cout<<\n Roll no of the Student:<<rollno;
}
};
void main()
{
clrscr();
student s;
s.input();
s.output();
getch();
}

24

Function Definition outside the class


#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class student
{
private:
int rollno;
char name[20];
public:
void input();
void output();
};
void student:: input()
{
cout<<Enter rollno:;
cin>>rollno;
cout<<Enter student Name:;
gets(name);
}
void student::output()
{
cout<<\n Name of the Student:<<name;
cout<<\n Roll no of the Student:<<rollno;
}
void main()
{
clrscr();
student s;
s.input();
s.output();
getch();
}
Object Definition using Arrays:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class student
{
private:
int rollno;
char name[20];
public:

25

void input()
{
cout<<Enter rollno:;
cin>>rollno;
cout<<Enter student Name:;
gets(name);
}
void output()
{
cout<<\n<<rollno<<\t\t<<name;
}
};
void main()
{
clrscr();
student s[10];
int i,n;
cout<<Enter how many students record you want to enter:;
cin>>n;
cout<<Enter students record:;
for(i=0;i<n;i++)
{
cout<<endl;
s[i].input();
}
cout<<\nStudents Record are:;
cout<<\nRollno\t\tName;
for(i=0;i<n;i++)
{
s[i].output();
}
getch();
}
Constructor: Constructors are the special member function used for automatic
initialization of the objects of the class. The constructors are defined along with other
member functions. But the format of constructor definition is different from other
member functions. The constructors can take parameters in their parenthesis as needed,
but they cannot have a return value not even void. The name of the constructor is same as
that of class name. The constructors are called in the program automatically whenever an
object of the class is created.
For example:
#include<iostream.h>
#include<conio.h>

26

#include<stdio.h>
class student
{
private:
int rollno;
char name[20];
public:
student()
{
rollno=1;
strcpy(name,Harry);
}
void input()
{
cout<<Enter rollno:;
cin>>rollno;
cout<<Enter student Name:;
gets(name);
}
void output()
{
cout<<\n<<rollno<<\t\t<<name;
}
};
void main()
{
clrscr();
student s;
s.output;
getch();
}
Parameterized constructor :
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class student
{
private:
int rollno;
char name[20];
public:
student(int a, char name2[20])
{
rollno=a;
strcpy(name,name2);

27

}
void input()
{
cout<<Enter rollno:;
cin>>rollno;
cout<<Enter student Name:;
gets(name);
}
void output()
{
cout<<\n<<rollno<<\t\t<<name;
}
};
void main()
{
clrscr();
student s(1,Harry);
s.output;
getch();
}

Inheritance: Inheritance is the most powerful feature of OOPS in C++, it is


implemented by creating the new classes from the existing class. Here, we can take the
form of existing class and then add code to it, without modifying the existing class.
Forms of Inheritance:
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
1. Single Level Inheritance:
Base Class

Derived Class
For example
#include<iostream.h>
#include<conio.h>

28

class father
{
public:
char kothi[20], car[20];
};
class son:public father
{
private:
int cash;
public:
void input()
{
cout<<\nEnter Kothi No:;
cin>>kothi;
cout<<\nEnter Car No:;
cin>>car;
cout<<\nEnter Cash Amount:;
cin>>cash;
}
void output()
{
cout<<\nKothi No:<<kothi;
cout<<\nCar No:<<car;
cout<<\nCash Amount:<<cash;
}
};
void main()
{
clrscr();
son s;
s.input();
s.output();
getch();
}
2. Multilevel Inheritance:
Base Class

Derived 1 Class

Derived 2 Class
29

For example
#include<iostream.h>
#include<conio.h>
class Gfather
{
public:
char kothi[20];
};
class father:public:Gfather
{
public:
char flat[20], car[20];
};
class son:public father
{
private:
int cash;
public:
void input()
{
cout<<\nEnter Kothi No:;
cin>>kothi;
cout<<\n Enter Flat No:;
cin>>flat;
cout<<\nEnter Car No:;
cin>>car;
cout<<\nEnter Cash Amount:;
cin>>cash;
}
void output()
{
cout<<\nKothi No:<<kothi;
cout<<\nFlat No:<<flat;
cout<<\nCar No:<<car;
cout<<\nCash Amount:<<cash;
}
};
void main()
{
clrscr();
son s;
s.input();

30

s.output();
getch();
}
3. Multiple Inheritance:
Base Class1

Base Class 2

Base Class 3

Derived Class
For example
#include<iostream.h>
#include<conio.h>
class Gfather
{
public:
char kothi[20];
};
class father
public:
char flat[20], car[20];
};
class son: public father, public Gfather
{
private:
int cash;
public:
void input()
{
cout<<\nEnter Kothi No:;
cin>>kothi;
cout<<\n Enter Flat No:;
cin>>flat;
cout<<\nEnter Car No:;
cin>>car;
cout<<\nEnter Cash Amount:;
cin>>cash;
}
void output()
{
cout<<\nKothi No:<<kothi;
cout<<\nFlat No:<<flat;

31

cout<<\nCar No:<<car;
cout<<\nCash Amount:<<cash;
}
};
void main()
{
clrscr();
son s;
s.input();
s.output();
getch();
}
4. Hierarchical Inheitance:
Base Class

Derived Class 1

Derived Class 2

Derived Class 3

5. Hybrid Inheritance:
Base Class
Derived Class 1

Derived Class 2

`
Derived

Polymorphism: Base Class Member functions can be overridden by defining a


derived class member function with the same name as that of the base class
member function. This concept is known as polymorphism.
The word poly is a Greek Word meaning many and morphism means
forms. Thus Polymorphism means many forms. Function over loading ,
constructor overloading and operator overloading is the form of polymorphism in
c++.
Function Overloading: Function overloading means a class having same name
of functions but functions contain different number of arguments and different
type of arguments.

32

For Example:
#include<iostream.h>
#include<conio.h>
class demo
{
private:
int a,b;
float f1,f2;
public:
void sum(int x, int y)
{
a=x;
b=y;
cout<<\nSum of Integer Values:<<a+b;
}
void sum(float p, float q)
{
f1=p;
f2=q;
cout<<\nSum of Floating values:<<f1+f2;
}
};
void main()
{
clrscr();
demo d;
d.sum(100,200);
d.sum(10.5f, 7.75f);
getch();
}

File Handling in C++:


Storage of data in variables and arrays is temporary. Files are used for permanent
storage of large amount of data. Computer stores files on secondary storage device such
as Magnetic Disks, Optical Disks and Hard Disks.
The file I/O system of c++ contains a set of classes that define the file handling
methods. These classes designed to manage the disk files, are declared in <fstream.h>.
ofstream class: ofstream class is used for writing information to a file.
Ifstream class: ifstream class is used for reading information from a file.
For example
#include<iostream.h>

33

#include<fstream.h>
#include<conio.h>
{
clrscr();
ofstream obj1;
ifstream obj2;
char str[20];
obj1.open(abc.txt);
obj1<<welcome;
obj1.close();
obj2.open(abc.txt);
obj2>>str;
cout<<str;
getch();
}
File Modes:
File
Mode
ios::in
ios::out
ios::app

Meaning
This specifies that the file is capable of input. It opens file for reading. This
mode is used with ifstream class.
This specifies that the file is capable of output. It opens file for writing. But
previous contents are discarded in this mode.
This causes all output to that file to be append to the end.

Write a program to demonstrate the operation of ios::out and ios::in mode.


#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
clrscr();
char name[20];
int rollno, i;
ofsteam obj1;
obj1.open(abc.txt,ios::out);
for(i=0;i<2;i++)
{
Cout<<\n Enter the Name:;
Cin>>name;
Cout<<\n Enter the roll Number:;
Cin>>rollno;
Obj1<<name<< ;
Obj1<<rollno;
}

34

obj1.close();
ifstream obj2;
obj2.open(abc.txt,ios::in);
for(i=0;i<2;i++)
{
obj2>>name;
obj2>>rollno;
cout<<\nName :<<name;
cout<<\n Roll No:<<rollno;
}
obj2.close();
getch();
}
Write a program to demonstrate the operation of ios::app and ios::in mode.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
clrscr();
char name[20];
int rollno, i;
ofstream obj1;
obj1.open(abc.txt,ios::app);
cout<<\nAppending the file:<<endl;
cout<<Enter the name:;
cin>>name;
cout<<Enter the rollno:;
cin>>rollno;
obj1<<name<< ;
obj1<<rollno;
obj1.close();
ifstream obj2;
obj2.open(abc.txt,ios::in);
for(i=0;i<2;i++)
{
obj2>>name;
obj2>>rollno;
cout<<\nName :<<name;
cout<<\n Roll No:<<rollno;
}
obj2.close();
getch();
}

35

36

Anda mungkin juga menyukai