C++ Notes (Unit-1,2,3)
C++ Notes (Unit-1,2,3)
C++ Notes (Unit-1,2,3)
(C++)
Virendra Sir
(Scholars Education)
UNIT-1
Overview
C++ is a compiled, general-purpose, case-sensitive programming language that
supports procedural, object-oriented programming.
Object-Oriented Programming
Encapsulation
Data hiding
Inheritance
Polymorphism
Environment Setup
Before you start doing programming using C++, you need the following two software‟s
available on your computer.
1) Text Editor:
This will be used to type your program. Examples of few editors include Windows Notepad, OS
Edit command etc.
Name and version of text editor can change on different operating systems. For example,
Notepad will be used on Windows and vim or vi can be used on windows as well as Linux, or
UNIX.
The files you create with your editor are called source files, and for C++ they typically are
named with the extension .cpp, .cp.
2) C++ Compiler:
This is actual C++ compiler, which will be used to compile your source code into final
executable program.
Most C++ compilers don't care what extension you give your source code, but if you don't
specify otherwise, many will use .cpp by default.
A Simple Program:
The simple program HELLO.CPP. "Getting started," have many interesting parts. This section
will review this program in more detail.
#include <iostream.h>
#include <conio.h>
void main()
{
TC Business School | BEST BCA College In JAIPUR 2
cout<< "Hello World!\n";
getch();
}
The file iostream.h is included in the file. The first character is the # symbol, which is a
signal to the preprocessor. Each time you start your compiler, the preprocessor is run.
The preprocessor reads through your source code, looking for lines that begin with the
hash (Preprocessor) symbol (#).
include is a preprocessor instruction that says, "What follows is a filename. Find that file
and read it in right here. Another way include is a keyword that include a header file in
our program.
"The angle brackets { } tell the preprocessor to look in all the usual places for this file. If
your compiler is set up correctly, the angle brackets will cause the preprocessor to look
for the file iostream.h in the directory that holds all the H files for your compiler. The file
iostream.h (Input-Output-Stream) is used by cout, which helps with writing to the screen.
The preprocessor runs before your compiler each time the compiler is invoked. The
preprocessor translates any line that begins with a hash (processor) symbol (#).
2 Lines, begins the actual program with a function named main(). Every C++ program
has a main() function. Usually functions are invoked or called by other functions, but
main() is special. When your program starts, main() is called automatically.
main(), must start what kind of value it will return. The return value type for main() in
HELLO.CPP is void, which means that this function will not return any value at all.
All functions begin with an opening brace ({) and end with a closing brace (}). The braces
started aftermain() function are on lines 3 and 5. Everything between the opening and
closing braces is considered a part of the function.
The line 4. The object cout is used to print a message to the screen. These two objects,
cout and cin, are used in C++ to print strings and values to the screen. A string is just a
set of characters.Here‟s cout is used
cout, followed by the output redirection operator (<<). Whatever follows the output
redirection operator is written to the screen. If you want a string of characters written, be
sure to enclose them in double quotes ("), as shown on line 4.
The symbol \n is a special formatting character. It tells cout to cout to put a new line after
the words Hello World!
The main() function ends on line 5 with the closing brace.
To print a value to the screen, write the word cout, followed by the insertion operator (<<), which
you create by typing the less-than character (<) twice. know this is two characters, C++ treats it
as one.
Example::Using cout.
// using cout
#include <iostream.h>
void main()
{
cout<< "Hello.\n";
cout<< "Welcome to Scholars education Pvt Ltd.,Brahampuri,Jaipur.\n";
cout<< "Here is 5: " << 5 << "\n";
cout<< "The useendl writes a new line to the screen." <<endl;
cout<< "Here is a very big number:\t" << 90000 <<endl;
cout<< "Here is the sum of 2 and 5:\t" << 2+5 <<endl;
cout<< “Scholars.cpp is a C++ programmer!\n";
}
OUTPUT:
Hello .
Welcome to Scholars education Pvt Ltd.,Brahampuri,Jaipur.
Here is 5: 5
The useendl writes a new line to the screen.
Here is a very big number: 90000
Here is the sum of 2 and 5: 7
Scholars.cpp is a C++ programmer!
Comments:
When you are writing a program, Some Code can be confusing and unclear. And you
are not sure how that confusion clears into your program, but you want to use
comments. That‟s means your aresure how that confusion clear into your program.
Comments are simply text that is ignored by the compiler, but that may inform the reader
of what you are doing at any particular point in your program.
1) The double-slash (//) comment, and the slash-star (/*) comment. The double-slash
comment, which will be referred to as a C++-style comment, tells the compiler to ignore
everything that follows this comment, until the end of the line. Double-slash (//)
commentis also called Single line Comment.
2) The slash-star comment mark tells the compiler to ignore everything that follows until it
finds a star-slash (*/) comment mark. These marks will be referred to as C-style
comments. Every /* must be matched with a closing */.Slash-star commentis also called
Multi line Comment.
OUTPUT :
Hello World!
That comment ended!
Yes Error
No
Figure (2)
Object File (.obj)
5) Once the Source Program has been converted into an Object File, it is still not in the form
that we can run.
The reason behind this is that there may be some reference to the
standard library functions or user-defined functions in other object file, which are compiled
separately. Therefore, these object file are to be linked together along with standard library
functions that are contained in library files. To link on object file, select link from the compile
menu.
After this the .obj file will be compiled with the one or more library files. The
result of this linking process produces an executable file with .exe extension.
Linker
.Exe File
Figure (3)
TC Business School | BEST BCA College In JAIPUR 6
6) .Exe file is an executable file which can direct execute from command prompt.
7) After pressing Alt+F9 , it will complete the whole process creating .obj and .exe
8) To display the output of the program press Alt+F5
Evolution of OOPS
Object Oriented Programming Language OOp’s
Procedural Language
Assembly Language
Machine
Language
Machine Language
Assembly Language
We use short English words for instruction. Like Add, jump, multi etc. This is
easily to learn. It is a low-level symbolic code converted by an assembler.
A program is written in source code (Text File) and translated into machine
language by an assembler.
To execute a program assembler take a lot of time so to overcome this problem
the new language was generated which was “Procedural Language”.
Procedural Language
Procedural language is a type of computer programming language that specifies
a series of well-structured steps and procedures with in programming.
Are easy to read, write and maintain than machine and assembly language.
Use a compiler or interpreter to translate code.
Encapsulation
Data hiding
Inheritance
Polymorphism
Advantage of OOPS
These are some of major advantage of OOPS:
4.
Data Moving Data can moved freely from Data cannot move freely
function to function because of access specifier
5. Expansion It is not easy to add new data Easy ways to add feature
and function i.e. new data and functions.
6. Data Access Function use global data for Data cannot move easily
sharing that can be access from function to function
freely because of access specifier.
C is a structure programming language where we have to write the all at a strut but C++
is a modular programming language (Processer programming language) where the
program are written in the form of Classes.
Classes
A class can be defined as a template/blueprint that describes the
behaviors/states that object of its type support.
A class is a collection of object of similar type. Once a class is defined, any
number of objects can be created which belong to that class.
The entire set of data and code of an objects can be made user-defined data
type with the help of a class, In fact object are variable of the type class.
Object
Object is run time states (instances of a class) in an object-oriented system.
Programming problem is analyzed in terms of objects.
Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors - wagging, barking, and eating. An object is an
instance of a class.
In OOP class can be execute by instance of class.
Another way we understand an object using diagram
Encapsulation
C++ programs are composed of the following two fundamental elements:
Program statements (code): This is the part of a program that performs actions
and they are called functions.
Program data: The data is the information of the program which affected by
the program functions.
Encapsulation is an Object Oriented Programming concept that binds together the data
and functions that manipulate the data, and that keeps both safe from outside
interference and misuse. Data encapsulation led to the important OOP concept of data
hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use
them and data abstraction is a mechanism of exposing only the interfaces and hiding
the implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the creation of
user-defined types, called classes. We already have studied that a class can contain
private, protected and public members. By default, all items defined in a class are
private.
Inheritance
One of the most important concepts in object-oriented programming is that of
inheritance. Inheritance allows us to define a class in terms of another class,
which makes it easier to create and maintain an application.
This also provides an opportunity to reuse the code functionality and fast
implementation time.
When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should
inherit the members of an existing class. This existing class is called the base
class, and the new class is referred to as the derived class.
The idea of inheritance implements in a relationship. (it create a new class from a
existing once. New class inherit code form a existing class)
Fig(1) Inheritance
Polymorphism
Polymorphism is another important OOP concept. Polymorphism means the ability to
take more than one form.
Figure(1) example that a single function name can be used to handle different number
and different type of arguments. This is something similar to a particular word having
several different meaning (arguments). Using a single function name to perform
different types of tasks is known as function overloading.
Overloading
C++ allows you to specify more than one definition for a function name or an operator
inthe same scope, which is called function overloading and operator overloading
respectively.
An overloaded declaration is a declaration that had been declared with the same name
as a previously declared declaration in the same scope,
Output:
Output:
Output:
Output:
Output:
Introduction to C++:C++ tokens, data types, C++ operators, type conversion, variable
declaration, statements, expressions, conditional statements, jumping statements,
loops, array, Function, Pointers, Structures.
Introduction of C++
C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form
programming language that supports procedural, object-oriented, and generic
programming.
C++ is regarded as a High-level language, as it comprises a combination of low-level
language features.
C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill and
originally named C with Classes but later it was renamed C++ in 1983.
C++ is a superset of C.
The purpose of learning a programming language is to become a better programmer;
that is, to become more effective at designing and implementing new systems and at
maintaining old ones.
C++ is used by hundreds of thousands of programmers in essentially every application
domain.
C++ is being highly used to write device drivers and other software that rely on direct
manipulation of hardware under real-time constraints.
Simple Program
Output:
Hello World!
Note:-
Void Main()Main() is a function which is system defined and the word Void means the
function doesn‟t return a Value.
return 0;
The return statement causes the main function to finish. return may be followed by a
return code (in our example is followed by the return code 0). A return code of 0 for the
main function is generally interpreted as the program worked as expected without any
errors during its execution. This is the most usual way to end a C++ console program.
Variables
Definition:
1. Variable is used to store the value. The value of a variable can be change during
the execution of program or a variable is the name of memory location where the
value is to be store.
2. Variable are declare at the starting of a Program with there data type.
3. Maximum length is 8.
As a programmer, you will frequently want your program to
"remember" a value. For example, if your program requests a value from the user, or if it
calculates a value, you will want to remember it somewhere so you can use it later. The
way your program remembers things is by using variables.
For example:
int b;
This line says, "I want to create a space called b that is able to hold one integer value."
A variable has a name (in this case, b) and a type (in this case, int, an integer). You
can store a value in b by saying something like:
Identifiers
Identifiers refer to the names of variables, functions and arrays.
Identifier name must differ in spelling and case from any keywords.
We cannot use keywords as identifiers; they are reserved for special use.
Identifiers are user-defined names and consist of a sequence of letters
and digits, with a letter as a first character. Both uppercase and lowercase
letters are permitted. The underscore character is also permitted.
A valid identifier is a sequence of one or more letters, digits or underscores
characters (_). Neither spaces nor punctuation marks or symbols can be
part of an identifier.
TC Business School | BEST BCA College In JAIPUR 25
Only letters, digits and single underscore characters are valid. In addition,
variable identifiers always have to begin with a letter.
Note:
Very important: The C++ language is a "case sensitive" language. That means that
an identifier written in capital letters is not equivalent to another one with the same
name but written in small letters. Thus, for example, the
RESULT variable is not the same as the result variable or the Result variable. These
are three different variable identifiers.
Data Types
While writing program in any language, you need to use various variables to
store various information. Variables are nothing but reserved memory locations to store
values. This means that when you create a variable you reserve some space in
memory.
You may like to store information of various data types like character, wide
character, integer, floating point, double floating point, boolean etc. Based on the data
type of a variable, the operating system allocates memory and decides what can be
stored in the reserved memory.
Definition: Every Programming handles a different Type of Data and Value it depend
on Type of Data. There is a way to store a value in a variable is know as “Data Type”
Several of the basic types can be modified using one or more of these type modifiers:
How much memory it takes to store the value in memory, and what is maximum and
minimum value which can be stored in such type of variables. Following is the example,
which will produce correct size of various data types on your computer.
#include<iostream.h>
#include<conio.h>
int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
getch();
return 0;
This example uses endl, which inserts a new-line character after every line and<<
operator is being used to pass multiple values out to the screen. We are also using
sizeof() function to get size of various data types.
When the above code is compiled and executed, it produces the following result which
can vary from machine to machine:
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
1) Enum
An enumerated type declares an optional type name and a set of zero or more
identifiers that can be used as values of the type. Each enumerator is a constant
whose type is the enumeration.
Creating an enumeration requires the use of the keyword enum. The general
form of an enumeration type is:
enum enum-name { list of names } var-list;
2) Typedef Declarations
You can create a new name for an existing type using typedef. Following is the
simple syntax to define a new type using typedef:
Syntax
typedef type newname;
For example, the following tells the compiler that feet is another name for int:
typedef int feet;
Now, the following declaration is perfectly legal and creates an integer variable
called distance:
feet distance;
3) Class(module, block)
All variable and methods are grouped in a class each class described and
individual object and each object is set to be instance of a class and each
instance of the class has its on variable and methods.
Classes are basically used for creating the user defined data type and the
functions of that class are called its member function. So classes is declared by
Practice Sheet-1
1) WAP to print the “welcome to C++ language” and “C is a Object Oriented
programming language” and “it is case sensitive”.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<"Welcome to C language \n";
cout<<"C is a structured programming language \n";
cout<<"it is case sensitive";
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
int x=10,y=20, sum;
clrscr();
sum=x+y;
cout<<sum is:";
cout<<sum;
getch();
TC Business School | BEST BCA College In JAIPUR 30
}
3) WAP to print the student roll no and marks- Hindi, English, math and find out
the sum and average.
#include<iostream.h>
#include<conio.h>
void main()
{
int rollno,hindi,english,math,sum;
float average;
clrscr();
cout<<"enter the roll no=";
cin>>rollno;
cout<<":: marks:: \n";
cout<<"Enter the marks hindi=";
cin>>hindi;
cout<<"Enter the marks english=";
cin>>english;
cout<<"Enter the marks hindi=";
cin>>math;
sum=hindi+english+math;
average=sum/3;
cout<<"the sum is="<<sum;
cout<<"the average is="<<average;
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
float SI,P,R,T;
clrscr();
cout<<"Enter the value of Priniciple =";
cin>>P;
cout<<"Enter the value of Rate =";
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
cout<<"Enter the value of a=";
cin>>a;
cout<<"Enter the value of b=";
cin>>b;
c=a;
a=b;
b=c;
cout<<"\n After swapping value of a="<<a;
cout<<"\n After swapping value of b=”<<b;
getch();
}
9) WAP to print the net salary of employee where the Basic salary is given.
#include<iostream.h>
#include<conio.h>
void main()
{
float x,x2,x4,x6;
float sum;
clrscr();
cout<<"Enter the value of x=";
cin>>x;
x2=x*x;
x4=x2*x2;
x6=x4*x2;
sum=1-x2/2+x4/24-x6/720;
cout<<"sum of series="<<sum;
getch();
}
Keywords
Keywords are the reserve words which have some special meaning
in the Programming Language.
C++ Keywords
The following list shows the reserved words in C++. These reserved words maynot be
used as constant or variable or any other identifier names.
Keywords are the words whose meaning has already been explained to the C++
compiler.
The keywords cannot be used as variable name because if we do so, we are
trying to assign a new meaning to the keyword, which is not allowed by the
computer. For Example: auto, break, case, char, float , for, goto, int etc
Practice Sheet-2
1) Write a program which reads two float numbers and display their product.
2) Rahul basic salary is input throughthe keyboard. His dearness allowance is 40%
of basic salary, and house rent allowance is 20% of basic salary. Calculate his
gross salary.
#include<iostream.h>
#include<conio.h>
void main()
{
float f,c;
clrscr();
TC Business School | BEST BCA College In JAIPUR 35
cout<<"Enter value for Centigrade = ";
cin>>c;
f=1.8*c+32;
cout<<"Fahrenheit is = "<<f;
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
int tday,week,day;
clrscr();
cout<<"Enter total days = ";
cin>>tday;
week=tday/7;
day=tday%7;
cout<<"Total week is = "<<week;
cout<<"\nTotal day is = "<<day;
getch();
}
X+Y
The preceding expression uses two operands and one operator to add the value
stored in the variable.
C++ is rich in built-in operators and provide the following types of operators:
l Operators
1) Arithmetic Operators:
These operators are the symbols that are used to perform arithmetic operations on
variable. The following table describes the commonly used arithmetic operators.
#include<iostream.h>
#include<conio.h>
void main()
{
int a = 21;
int b = 10;
int c ;
c = a + b;
cout << "Line 1 - Value of c is :" << c << endl ;
c = a - b;
cout << "Line 2 - Value of c is :" << c << endl ;
c = a * b;
cout << "Line 3 - Value of c is :" << c << endl ;
c = a / b;
cout << "Line 4 - Value of c is :" << c << endl ;
c = a % b;
cout << "Line 5 - Value of c is :" << c << endl ;
c = a++;
cout << "Line 6 - Value of c is :" << c << endl ;
c = a--;
cout << "Line 7 - Value of c is :" << c << endl ;
getch();
return 0;
}
When the above code is compiled and executed, it produces the following result:
Line 1 - Value of c is :31
Line 2 - Value of c is :11
Line 3 - Value of c is :210
Line 4 - Value of c is :2
Line 5 - Value of c is :1
Line 6 - Value of c is :21
Line 7 - Value of c is :22
(arithmetic X=X+Y;
assignment)
X=X-Y;
X=X*Y;
X=X/Y;
X=X%Y;
Example:-
a=a+1 equivalent to a+=1
a=a-1 equivalent to a-=1
a=a%b equivalent to a%=b
The following C++ program in test.cpp file and compile and run this program-
#include<iostream.h>
#include<conio.h>
Void main()
{
int a = 21;
int c ;
c = a;
cout << "Line 1 - = Operator, Value of c = : " <<c<< endl ;
c += a;
When the above code is compiled and executed, it produces the following result:
The following C++ program in test.cpp file and compile and run this program
#include<iostream.h>
#include<conio.h>
void main()
{
int a = 21;
int b = 10;
int c ;
if( a == b )
{
cout << "Line 1 - a is equal to b" << endl ;
}
else
{
cout << "Line 1 - a is not equal to b" << endl ;
}
if ( a < b )
{
cout << "Line 2 - a is less than b" << endl ;
}
else
{
cout << "Line 2 - a is not less than b" << endl ;
}
if ( a > b )
{
cout << "Line 3 - a is greater than b" << endl ;
}
else
{
cout << "Line 3 - a is not greater than b" << endl ;
}
/* Let's change the values of a and b */
a = 5;
When the above code is compiled and executed, it produces the following result:
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
Operand--;
Y=X--;
(Postdecrement
If the initial value of X is 5, after
Operator)
the execution of the preceding
statement, value of both X will
be 4 and value of Y will be 5.
5) Logical Operators:
Logical operators are used to evaluate expression and return a Boolean value.
Logical operators simulate Boolean algebra in C++.
The following tables explain the usage of logical operators.
Operator Meaning Usage Description Example
cin>>b;
if((a==10)&&(b==20))
cout<<"True \n";
else
cout<<"False \n";
cin>>b;
if((a==10)||(b==20))
cout<<"Condition is True\n";
else
cin>>b;
if(a!=10)
cout<<"Condition is False\n";
else
cout<<"Condition is True";
The following C++ program in test.cpp file and compile and run this
program
#include <iostream.h>
#include <conio.h>
void main()
{
int a = 5;
int b = 20;
int c ;
if ( a && b )
{
cout << "Line 1 - Condition is true"<< endl ;
}
if ( a || b )
{
cout << "Line 2 - Condition is true"<< endl ;
}
/* Let's change the values of a and b */
a = 0;
b = 10;
if ( a && b )
{
cout << "Line 3 - Condition is true"<< endl ;
}
else
{
cout << "Line 4 - Condition is not true"<< endl ;
}
if ( !(a && b) )
{
cout << "Line 5 - Condition is true"<< endl ;
}
return 0;
}
Note:-
Example:
a=5;
b=10;
m=a>b?a:b;
m=5>10?5:10;
output:
Operator Meaning
| Bitwise OR
~ 1’s complement
^ Bitwise exclusive OR
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^
are as follows:
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
TC Business School | BEST BCA College In JAIPUR 49
A^B = 0011 0001
~A = 1100 0011
The following C++ program in test.cpp file and compile and run this program
#include<iostream.h>
#include<conio.h>
void main()
{
unsigned int a = 60; // 60 = 0011 1100
unsigned int b = 13; // 13 = 0000 1101
int c = 0;
c = a & b; // 12 = 0000 1100
cout << "Line 1 - Value of c is : " << c << endl ;
c = a | b; // 61 = 0011 1101
cout << "Line 2 - Value of c is: " << c << endl ;
c = a ^ b; // 49 = 0011 0001
cout << "Line 3 - Value of c is: " << c << endl ;
c = ~a; // -61 = 1100 0011
cout << "Line 4 - Value of c is: " << c << endl ;
c = a << 2; // 240 = 1111 0000
cout << "Line 5 - Value of c is: " << c << endl ;
c = a >> 2; // 15 = 0000 1111
cout << "Line 6 - Value of c is: " << c << endl ;
getch();
return 0;
}
When the above code is compiled and executed, it produces the following
result:
Line 1 - Value of c is : 12
Line 2 - Value of c is: 61
Line 3 - Value of c is: 49
Line 4 - Value of c is: -61
Line 5 - Value of c is: 240
Line 6 - Value of c is: 15
#include<iostream.h>
#include<conio.h>
void main()
{
/*Logical AND && */
char rs;
char ch1,ch2;
ch1='A';
ch2='B';
clrscr();
if((ch1=='A')&&(ch2=='B'))
{
cout<<"Both Condition are true in Logical AND \n";
}
else
{
cout<<"False \n";
}
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
cout<<"Enter the First Integer value=";
cin>>a;
cout<<"\n Enter the Second Integer Value=";
cin>>b;
/*Logical AND*/
if((a==10)&&(b==20))
{
cout<<"Both Condition are true in Logical AND \n";
}
if(a||b)
{
cout<<"Condition is True \n";
}
else
{
cout<<"Condition is False";
}
/*Logical NOT */
if(a!=10)
{
cout<<"Condition is False\n";
}
else
{
cout<<"Condition is True";
}
getch();
}
x=5;
cout<<"\n initilize the value of x= "<<x;
y=--x;
cout<<"\n Pre-Decrement value of x= "<<x;
cout<<"\n Pre-Decrement value of y="<<y;
/*Post-Decrement Operator*/
cout<<endln;
cout<<endln;
x=5;
cout<<"\n initilize the value of x="<<x;
y=x--;
cout<<"\n Post-Decrement value of x="<<x;
cout<<"\n Post-Decrement value of y=”<<y;
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
int a=5;
int b=10;
int m;
clrscr();
m=(a>b)?a:b;
if(a>b)
{
m=a;
cout<<"m="<<m;
}
else
{
m=b;
cout<<"m="<<m;
5) WAP to calculate the Quadrant value and Reminder value using two variables
(Using Arithmetic Operator).
#include<iostream.h>
#include<conio.h>
void main()
{
int first,second,q,r;
clrscr();
cout<<"Enter the any no=";
cin>>first;
cout<<"Enter the second value=";
cin>>second;
q=first/second;
r=first%second;
cout<<"\n Quadrant="cout<<q;
cout<<"\n Reminder="cout<<r;
getch();
}
7) Apple cost RS 60 per dozen. It is required to find the cost of 28 apples to the
nearest rupees and print the answer as Rupees.
#include<iostream.h>
#include<conio.h>
void main()
{
int rate=60,rup,total;
clrscr();
cout<<"Per dozen apples rate= "<<rate;
rup=rate/12;
cout<<"1 apple cost=”<<rup;
total=rup*28;
cout<<"28 apple cost="<<total;
getch();
}
8) Write a program to print any values and count thousand, hundred, ten and one.
#include<iostream.h>
void main()
int number,x,x1,x2,x3,x4,x5,x6;
clrscr();
cin>>number;
x=number/1000;
x1=number%1000;
x2=x1/100;
x3=x1%100;
cout<<"\n hundred="<<x2;
x4=x3/10;
x5=x3%10;
cout<<"\n Ten="<<x4;
x6=x5/1;
getch();
Syntax:
if(boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}
If the Boolean expression evaluates to true, then the block of code inside the if
statement will be executed. If Boolean expression evaluates to false, then the first set of
code after the end of the if statement (after the closing curly brace) will be executed.
Flow Diagram
#include <iostream.h>
#include <conio.h>
int main ()
{
// local variable declaration:
int a = 10;
// check the boolean condition
if( a < 20 )
{
// if condition is true then print the following
cout << "a is less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
getch();
return 0;
}
When the above code is compiled and executed, it produces the following result:
2) if…else Statement
An if statement can be followed by an optional else
statement, which executeswhen the Boolean expression is false.
Syntax
The syntax of an if...else statement in C++ is:
if(boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}
else
{
// statement(s) will execute if the boolean expression is false
}
Example
#include<iostream.h>
#include<conio.h>
int main ()
{
// local variable declaration:
int a = 100;
// check the boolean condition
if( a < 20 )
{
// if condition is true then print the following
cout << "a is less than 20;" << endl;
}
else
{
// if condition is false then print the following
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Flowchart
Syntax
if(boolean_expression 1)
{
// Executes when the boolean expression 1 is true
}
else if( boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
else if( boolean_expression 3)
{
// Executes when the boolean expression 3 is true
}
else
{
// executes when the none of the above condition is true.
}
Example
#include <iostream.h>
#include <conio.h>
int main ()
{
// local variable declaration:
int a = 100;
// check the boolean condition
if(a == 10)
{
// if condition is true then print the following
cout << "Value of a is 10" << endl;
}
else if( a == 20 )
{
// if else if condition is true
cout << "Value of a is 20" << endl;
}
else if( a == 30 )
{
// if else if condition is true
cout << "Value of a is 30" << endl;
}
else
{
// if none of the conditions is true
cout << "Value of a is not matching" << endl;
When the above code is compiled and executed, it produces the following result:
Q) WAP to find maximum and minimum value out of 3 values and find its mid value?
#include<iostream.h>
#include<conio.h>
void main()
int a,b,c,min,max,mid;
cout<<"Ener 3 no=";
cin>>a>>b>>c;
max=a;
max=b;
max=c;
min=a;
min=b;
min=c;
cout<<"max="<<max<<endl;
cout<<"min="<<min<<endl;
getch();
};
When the above code is compiled and executed, it produces the following result:
4) Nested if Statement
It is always legal to nest if-else statements, which means you can use one if orelse if
statement inside another if or else if statement(s).
Syntax
if( boolean_expression 1)
{
// Executes when the boolean expression 1 is true
if(boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
}
You can nest else if...else in the similar way as you have nested if statement.
Example
#include <iostream.h>
When the above code is compiled and executed, it produces the following result:
5) Switch Statement
A switch statement allows a variable to be tested for equality against a list ofvalues.
Each value is called a case, and the variable being switched on is checked for each
case.
Syntax
switch(expression)
{
case constant-expression :
statement(s);
break; //optional
case constant-expression :
#include <iostream.h>
#include <conio.h>
int main ()
{
// local variable declaration:
char grade = 'D';
switch(grade)
{
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
getch();
switch(ch1) {
case 'A':
cout << "This A is part of outer switch";
switch(ch2) {
case 'A':
cout << "This A is part of inner switch";
break;
case 'B': // ...
}
break;
case 'B': // ...
}
Example
#include <iostream.h>
#include <conio.h>
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
switch(a)
{
case 100:
cout << "This is part of outer switch" << endl;
switch(b)
The ? : Operator
C++ programming language provides the following type of loops to handle looping
requirements.
#include <iostream.h>
#include <conio.h>
int main ()
{
// for loop execution
for( int a = 10; a < 20; a = a + 1 )
{
cout<<"value of a: " <<a <<endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
#include<iostream.h>
#include<conio.h>
int main()
{
int a;
cout<<"enter any no ;"<<endl;
cin>>a;
if(a%2==0)
{
cout<<"no is not prime"<<endl;
}
else
{
cout<<"no is prime"<<endl;
}
getch();
#include<iostream.h>
#include<conio.h>
int main()
{
int i,n,r=0;
cout<<"enter the value of table:";
cin>>n;
cout<<"table is:"<<endl;
for(i=1;i<=10;i++)
{
r=n*i;
cout<<n<<'*'<<i<<'='<<r<<endl;
}
getch();
return 0;
}
2) While Loop
It is also known as Entry control loop. The wile loop is used to execute a block of
statements for a definite number of times, depending on a condition. The while
statement always checks the condition before executing the statements within the loop.
When the execution reaches the last statement in the while loop, the control is passed
back to the beginning of the loop. It the condition still holds true, the statements within
the loop are executed again. The execution of the statement within the loop continues
until the condition evaluates to false.
Syntax
while(condition)
{
statement(s);
}
While
Structure
Star
t
True
Conditio Statement
n
False
Stop
Example
#include <iostream.h>
#include <conio.h>
int main ()
{
// Local variable declaration:
int a = 10;
// while loop execution
while( a < 20 )
{
cout << "value of a: " << a << endl;
a++;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
#include<iostream.h>
#include<conio.h>
int main()
{
int i,sum=0,n;
cout<<"Enter the number upto the sum is to be displayed starting from 1 : ";
cin>>n;
i=1;
while(i<=n)
{
sum=sum+i;
i++;
}
cout<<"Sum = "<<sum;
getch();
return 0;
}
3)do…while Loop
It is also known as exit control loop. Unlike for and while loops, which test the loop condition
at the top of the loop, the do...while loop checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax
do
{
statement(s);
}
while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
execute again. This process repeats until the given condition becomes false.
Example
#include <iostream.h>
#include <conio.h>
int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
do
{
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following
result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
#include<iostream.h>
#include<conio.h>
int main()
{
int i,sum=0,n;
cout<<"Enter the number upto the sum is to be displayed starting from 1 : ";
cin>>n;
i=1;
do
{
sum=sum+i;
i++;
}while(i<=n);
cout<<"Sum = "<<sum;
getch();
return 0;
}
Flow Diagram
Example
#include <iostream.h>
#include <conio.h>
int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
do
{
cout << "value of a: " << a << endl;
a = a + 1;
if( a > 15)
TC Business School | BEST BCA College In JAIPUR 78
{
// terminate the loop
break;
}
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
continue Statement
The continue statement works somewhat like the break statement. Instead of forcing
termination, however, continue forces the next iteration of the loop to take place, skipping any
code in between.
For the for loop, continue causes the conditional test and increment portions of the loop to
execute. For the while and do...while loops, program control passes to the conditional tests.
Syntax
The syntax of a continue statement in C++ is:
continue;
Flow Diagram
#include <iostream.h>
#include <conio.h>
int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
do
{
if( a == 15)
{
// skip the iteration.
a = a + 1;
continue;
}
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
goto Statement
goto statement is used to Break the normal execution of a Program. The goto require a
level In order to identify the place where the branch is to be made. The level must be followed
by colons (:)
#include<iostream.h>
#include<conio.h>
void main()
{
int n=1,no;
TC Business School | BEST BCA College In JAIPUR 80
clrscr();
cout<<"Enter the natural no limit=";
cin>>no;
l1:
cout<<"natural no= "cout<<n;
n++;
if(n<=no)
goto l1;
getch();
}
Flow Diagram
Example
#include <iostream.h>
#include <conio.h>
int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
LOOP:do
{
if( a == 15)
{
// skip the iteration.
a = a + 1;
goto LOOP;
}
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
return 0;
}
TC Business School | BEST BCA College In JAIPUR 81
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C++ programmers more commonly use the „for (;;)‟
construct to signify an infinite loop.
NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.
Size of Array
Declaring An Array &
Index
Datatype Arrayname[ ] &
Subscript
int a[3];
datatype: Is used to specify the data type for the elements, which will be stored in the
array.
[ ]: Is used to specify the rank of the array. Rank is used to specify the size of the array. [
] is also called Index, Size, Subscript. Know in example [3] this size indicate that the
maximum number of elements we can stores in an array but the compiler Interpret the
first elements as „0‟.
Arrayname: Is used to specify the name of the array using which the elements of the
array will be initialized and manipulated.
BEWARE: In C++ Array subscripts start at 0 and end one less than the array number.
#include<iostream.h>
#include<conio.h>
void main()
{
char ch[5]="SCHOLARS";
cout<<ch;
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
char ch[5]="SCHOLARS";
// char ch[5]={'A','N','A','N','T'};
int i;
clrscr();
for(i=0;i<=4;i++)
{
cout<<ch[i];
}
getch();
}
1) Single dimensional
In single dimensional array the list of items store only in one
dimensional. If the array is integer type then each value will take a space of 2 bytes.
int a[5}={10,20,30,40,50}
#include<iostream.h>
#include<conio.h>
void main()
{
int a[4]={1,2,3,4};
int i;
clrscr();
for(i=0;i<=3;i++)
{
cout<<a[i];
}
for(i=3;i>=0;i--)
{
cout<<a[i];
}
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
int num[10],i,sum=0;
float avg;
clrscr();
for(i=0;i<=9;i++)
{
cout<<”enter the num=";
cin>>num[i];
sum=sum+num[i];
}
avg=sum/10;
cout<<"avg is= "<<avg;
getch();
}
To access the particular element from the array we have to use two subscripts one for
row number and other for column number. The notation is of the form a[i][j], where I
stands for row subscripts and j stands for column subscripts.
Thus, a[0][0] refers to the first element of the two-dimensional array and so on and
a[0][0] is same as a0,0
We can also define and initialize the array as follow:
int values [3][4]={ {1,2,3,4}
{5,6,7,8}
{9,10,11,12}
};
In Two dimensional arrays there is two dimensional known as X and Y and the value is
stored in two dimensional arrays in the form of table. Table is the combination of rows
and column matrix.
Multi-dimensional arrays can be defined as follows:
int a[2][3]={10,20,30,40,50,60}
0 1 2 (0,0) (1,0)
0 10 20 30 (0,1) (1,1)
1 40 50 60 (0,2) (1,2)
#include<stdio.h>
#include<conio.h>
#define m 2
#define n 2
#define p 2
void main()
{
int a[m][n],b[n][p],c[m][p],i,j,k;
clrscr();
printf("Enter values in matrix A ");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
printf("Enter values in matrix B ");
for(i=0;i<n;i++)
{
for(j=0;j<p;j++)
scanf("%d",&b[i][j]);
}
clrscr();
printf("Entered matrix A is = \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%4d",a[i][j]);
printf("\n");
}
printf("Entered matrix B is = \n");
for(i=0;i<n;i++)
{
for(j=0;j<p;j++)
printf("%4d",b[i][j]);
printf("\n");
}
for(i=0;i<m;i++)
{
for(k=0;k<p;k++)
Output….
Multiply second row in First Matrix and First column in second matrix
……, after addition b/w them. Like
Definition
In computers memory is used for storing the information. Each cell has its address when
ever we declare the variable it stores in the memory in some places and each memory
allocation has a unique address. Pointer is a variable which is used to hold the address
of memory allocation.
Declaring An Pointer
Datatype *ptr_name;
char *ptr
There are few important operations, which we help to declare the pointer very frequently.
a) We define a pointer variable
b) Assign the address of a variable to a pointer and
c) Finally access the value at the address variable in the pointer variable.
Thus is done by using unary operator(*) that return the value of the variable located at
the address specified by its operand.
C++ language allow you to define type of variable that can hold several data items of
the same types but structure is another ways to defined data type available in C++
programming, which allows you to combine data items of different types.
Structure is used to represent a record, suppose you want to keep track of your books in
a library. You might want to track the following attributes about each book:
Title
Book ID
Author
Subject
Definition
A structure in C++ is a collection of items of different types. You can think of a structure
as a "record".
Structure is a collection of variable but under one name. In order to declare the structure
we use a keyword called “struct”. The keyword struct declare a structure to hold the
details of different data type like name, city, salary, commission.
Defining of structure
struct tagname
{
Datatype member1;
Datatype member2;
};
Declaration of structure
#include<iostream.h>
#include<conio.h>
struct student
{
char name;
int roll;
float marks;
};
struct s1
{
int salary[10];
char name[10];
float comm[10];
};
Introduction
A union is a special data type available in C++ that enables you to store different data
type in the same memory location.
Union provides an efficient way of using the same memory location for multi-purpose.
Definition
Union is just like the structure and it has the same syntax as a structure
Both structure and union are used to group a number of different variables but there is a
major different between them.
The structure (record) is it storage capacity used different memory location for every
variable but union used only one location for every variable
union keyword is used to declare union and the size of the union is largest size of the
member variable.
Defining of Union
union tagname
{
Datatype member1;
Datatype member2;
};
Declaration of Union
So how is a union declared and initialized? Let's look at an example:
union student
{
char name;
int roll;
float marks;
};
union s1
{
int salary[10];
char name[10];
float comm[10];
};
Classes and objects: Classes, objects, defining member functions, arrays of class
objects, pointers and classes, passing objects, constructors, type of constructors,
destructors, this pointers, access specifiers, friend functions, inline functions.
OOP’s
As we know that C++ is an object oriented programming language structure.
In C++ we use the concept of OBJECT &CLASS. We must create class in c++
and to access the member of class we create an object of class.
Some feature of oop‟s
1) Encapsulation
Binding the data with code is called Encapsulation. In which private
member of class are accessible only the other member of same
class.
Example:
#include<iostream.h>
#include<conio.h>
class A
{
int x,y;
public:
void set(int a, int b)
{
x=a; y=b;
}
void show()
{
cout<<"x="<<x;
cout<<"y="<<y;
}
};
void main()
TC Business School | BEST BCA College In JAIPUR 98
{
A ob;
ob.set(10,20);
ob.show();
getch();
}
Result:
2) Abstraction
It is define as an act of representing essential feature without
including background detail. In other words, hiding the internal
detail from the outside world is called abstraction.
Example:
#include<iostream.h>
#include<conio.h>
class A
{
int a,b,c;
public:
void print()
{
cout<<"Enter two no";
cin>>a>>b;
c=a+b;
cout<<"sum is="<<c;
}
};
void main()
{
A ob;
3) Polymorphism
Most important characteristic of oop‟s analysis and design is
“POLYMORPHISM”. Where “POLY” means “MANY” &
“MORPHISM” means “FORM”.
Following different way to achieve polymorphism
1) Function overloading
2) Operator overloading
3) Dynamic Binding
Example:
#include<iostream.h>
#include<conio.h>
class A
{
int a,b;
public:
void fun(int a)
{
cout<<"one argument a="<<a;
}
void fun(int a, int b)
{
cout<<"\n two argument a & b="<<a<<b;
}
};
Result:
4) Inheritance
Inheritance is one of the most key features of C++. Inheritance
allow to user to create a new class [child class] from an existing
class [Base class].
Though inheritance concept the derived class inherit all the feature
from a base class & derived class can have additional feature of its
own.
Inheritance is used to increase “Reusability” of class.
Type of Inheritance
1) Single level
3) Hierarchical
4) Hybrid
#include<iostream.h>
#include<conio.h>
class x
{
int a; // member variable a of the class x
public:
void getval() // member function of class x
{
cout<<"Enter value of a :";
cin>>a;
}
void show()
{
cout<<"You entered value for a : "<<a;
}
};
int main()
{
x o;
o.getval(); // accessing of member function through the object o
o.show();
getch();
return 0;
}
#include<iostream.h>
#include<conio.h>
int main()
{
getch();
return 0;
}
Q) WAP to find greater then 3 value.
#include<iostream.h>
#include<conio.h>
int main()
{
int a,b,c;
cout<<"Enter three numbers:";
cin>>a>>b>>c;
if((a>b)&&(a>c))
cout<<a<<" is greater than "<<b<<" and "<<c;
else if((b>a)&&(b>c))
cout<<b<<" is greater than "<<a<<" and "<<c;
else
cout<<c<<" is greater than "<<a<<" and "<<b;
getch();
return 0;
}
Q) WAP Using switch case greater than 4 value program
#include<iostream.h>
#include<conio.h>
int main()
{
int a,b,c,d,flag;
cout<<"Enter four numbers:";
cin>>a>>b>>c>>d;
if((a>b)&&(a>c)&&(a>d))
flag=0;
TC Business School | BEST BCA College In JAIPUR 105
else if((b>a)&&(b>c)&&(b>d))
flag=1;
else if((c>a)&&(c>b)&&(c>d))
flag=2;
else
flag=3;
switch(flag)
{
case 0:
cout<<a<<" is greater than "<<b<<" "<<c<<" and "<<d;
break;
case 1:
cout<<b<<" is greater than "<<a<<" "<<c<<" and "<<d;
break;
case 2:
cout<<c<<" is greater than "<<a<<" "<<b<<" and "<<d;
break;
default:
cout<<d<<" is greater than "<<a<<" "<<b<<" and "<<c;
break;
}
getch();
return 0;
}
Constructor
A class constructor is a special member function of a class that the constructor is
automatically called when an object is created of that class.
A constructor will have exact same name as the class and it does not have any return
type at all, not even void.
There are several forms in which a constructor can take its shape namely
1) Default Constructor
2) Parameterized Constructors
3) Copy constructor
void main()
{
clrscr();
demo obj;
obj.get();
getch();
}
Result
Example
#include<iostream.h>
#include<conio.h>
class creature
{
private:
int main()
{
creature obj;
getch();
return 0;
}
Result:
2) Parameterized Constructors
A parameterized constructor is just one that has parameters specified in it.
A constructor that can take arguments are called parameterized constructors.
A default constructor does not have any parameter, but if you need, aconstructor can
have parameters. This helps you to assign initial value to anobject at the time of its
creation as shown in the following example:
Example:
#include<iostream.h>
#include<conio.h>
class Creature
{
private:
intyearOfBirth;
public:
Creature(int year)
{ //Parameterized Constructor
int main()
{
clrscr();
Creature obj(1994);
getch();
return 0;
}
Result:
3) Copy constructor
#include<iostream.h>
#include<conio.h>
class abc
{
int a, b;
public:
abc(int x, int y)
{
a = x;
b = y;
}
abc::abc(abc&p)
{
//If you like, you can define the same function outside the
class using the scope resolution operator (::)
a = p.a;
b = p.b;
}
void showdata()
{
cout<< a << " " << b <<endl;
}
};
void main()
{
clrscr();
abc c1(10, 20);
abc c2(c1);
c1.showdata();
c2.showdata();
getch();
}
Result:
#include<iostream.h>
#include<conio.h>
class product
{
int code;
public:
product()
{
//Default Constructor
}
product(int x) //Parameterized Constructor
{
code=x;
}
product(product &y) //Copy Constructor
{
code=y.code;
}
void display()
{
cout<<code<<endl;
}
};
void main()
{
product p1(10);
product p2(p1); //Copy Constructor Call
product p3=p2; //again copy Constructor call
p1.display();
p2.display();
p3.display();
getch();
}
Result:
Example:
#include<iostream.h>
#include<conio.h>
class product
}
product(int x) //Parameterized Constructor
{
code=x;
}
product(product &y) //class constructor
{
code=y.code; //copy the value
}
void display()
{
cout<<code<<"\n";
}
};
int main()
{
clrscr();
product p1(10);
product p2(p1); //copy constructor called
product p3=p1; //again copy constructor called
p1.display();
p2.display();
p3.display();
getch();
return 0;
}
Result:
Example
#include<iostream.h>
#include<conio.h>
class copy
{
doublevar, fact;
public:
void main()
{
clrscr();
double n;
cout<<"\n Enter the number:";
cin>>n;
copy obj(n);
copy cpy=obj;
cout<<"number "<<n<<" factorial is="<<obj.calculate();
cout<<"\nnumber "<<n<<" factorial is="<<cpy.calculate();
getch();
}
Result:
Constructor overloading
In case of constructor overloading we can have two or
more than two constructor but the list of argument should be different.
void main()
{
clrscr();
demo d();
demo d1(10);
getch();
}
Result:
Example:
#include<iostream.h>
#include<conio.h>
class point
{
int x,y;
public:
Constructor must be defined in the public. The constructor must be a public member.
if an object is copied from another object then the copy constructor is called.
Destructors
~ classname();
A destructor will have exact same name as the class prefixed with a tilde (~) symbol
before use it, and it can neither return a value nor can it take any parameters. Destructor
Example 1:
#include<iostream.h>
#include<conio.h>
class sample
{
public:
sample() // Constructor
{
cout<<"object created \n";
}
~sample() //Destructor
{
cout<<"Object Destory \n";
}
};
int main()
{
sample s;
getch();
return 0;
}
Example 2:
class creature
{
private:
intyearofBirth;
public:
creature()
{
yearofBirth=1970;
cout<<"constructure called"<<endl;
cout<<yearofBirth<<endl;
}
~creature()
{
cout<<"destructure called"<<endl;
}
};
int main()
{
cout<<"main start"<<endl;
creature obj;
cout<<"main end"<<endl;
getch();
return 0;
}
Result:
Destructor is used to free the allotted memory to object at run time, so that free memory
can be reused by other program or object.
To allot memory to an object new operator is used in constructor function and in
destructor function. Delete operator is used to free the allotted memory.
For Example:
#include<iostream.h>
#include<conio.h>
class sample
{
char *t;
public:
sample(int length)
{
t=new char[length];
cout<<"Character arary of length="<<length<<" Created";
}
~sample()
{
delete t;
cout<<"\n Memory de-allocated for the character array\n";
}
};
int main()
{
sample s(10);
getch();
return 0;
}
Result:
class Base {
public:
// public members go here
private:
// private members go here
protected:
// protected members go here
};
1) public Members
The data members and member functions declared public can be accessed by other
classes.
class PublicAccess
To use the public data members using the dot (.) operator and the respective object of
class.
Example
#include<iostream.h>
#include<conio.h>
TC Business School | BEST BCA College In JAIPUR 120
class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
void main()
{
clrscr();
Derived obj;
obj.doSomething(); // Not Allowed, because we can not access public function
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
cout<<obj.a;
getch();
}
2) private Members
class PrivateAccess
Example)
#include<iostream.h>
#include<conio.h>
class Student
{
private: // private data member
int rollno;
public: // public access of functions
int getRollno()
{
return rollno;
}
void setRollno(int i)
{
rollno=i;
}
};
Example-2)
#include<iostream.h>
#include<conio.h>
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:private Base //Not mentioning private is OK because for classes it defaults
to private
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
getch();
}
3) protected Members
A protected member variable or function is very similar to a private member but it
provided one additional benefit that they can be accessed in child classes which are
called derived classes.
The protected access specfiers used inheritance.
class ProtectedAccess
Example-1)
#include<iostream.h>
#include<conio.h>
class Declare
{
private:
int a;
public:
int b;
protected:
int c;
public:
void main()
{
clrscr();
Declare d;
d.call();
void main()
{
clrscr();
demo d;
d.get();
cout<<"===============Result Display=====================";
cout<<endl;
d.display();
getch();
}
Result
Friend function
A friend function is permitted full access to private and protected members of different
class.
A friend function of a class is defined outside that class scope but it has the right to
access all private and protected members of the class.
To understand the important to friend. There are certain situations, where we need to
share our private or protected data with non-members. Than the concept the friend
comes. A friend class is a class whose member function can access another class‟s with
private and protected member.
To declare the friend function the declension is started with the keyword friend.
Syntex
class class_name
void main()
{
clrscr();
A obj;
show(obj);
getch();
}
Result
#include<iostream.h>
#include<conio.h>
class test
{
int x,y,z;
public:
void getdata(int a,int b)
{
x=a;
y=b;
}
friend int sum(test t);
};
void sum(test t)
{
t.z=t.x+t.y;
}
void main()
{
test obj;
int no1,no2;
cout<<"Enter first digit=";
cin>>no1;
cout<<"Enter second digit=";
cin>>no2;
obj.getdata(no1,no2);
sum(obj); //obj.sum(obj);
getch();
}
Result
Note:
The Friend function and friend class are the techniques used to access the private members
of a class by using friend keyword. The common difference between friend function and friend
class is that when friend function is used the private class members can be accessed but in
friend class, only the names of the friend class is accessed not the private members of the
class.
The friend function is used to access the private and protected members of another class. In
this type of function, a friend keyword is used before the function name at the time of
declaration. There are some restrictive conditions applied to friend function. The first condition is
that friend function is not inherited by a child class. The second condition is that storage class
specifier may not be present in friend function, which means that it can not be declared as static
and extern.
The friend function is not called with an invoking object of the class.
#include<iostream.h>
#include<conio.h>
class XYZ
{
private:
int num=100;
char ch='Z';
public:
friend void disp(XYZ obj);
};
//Global Function
void disp(XYZ obj)
{
cout<<obj.num<<endl;
cout<<obj.ch<<endl;
}
Void main()
{
XYZ obj;
disp(obj);
getch();
}
Output
A
11
#include<iostream.h>
#include<conio.h>
class XYZ
Output:
100
Z
Inline function
With an inline function, the compiler tries to expand the code in the body of the function
in place of a call to the function.
The main objectives of using function in program is to save some memory space, which
become appreciable when a function is likely to be called many time. However, every
time a function is called, it takes a lot of extra time in executed time for task such as
jumping to the function and execution time may be save, solution of this problem is to
use macro.
#include<iostream.h>
#include<conio.h>
class inline_function
{
public:
inline float mul(float x,float y)
{
return(x*y);
}
};
void main()
{
clrscr();
inline_function inlineF;
cout<<"multiplication of two digit="<<inlineF.mul(10,20);
getch();
}
Result
Q) WAP to fine the multiplication value and the cubic value using inline function
void main()
{
clrscr();
line obj;
float val1,val2;
cout<<"Enter two value=";
cin>>val1>>val2;
cout<<"\n Multiplication value is="<<obj.mul(val1,val2);
cout<<"\n cube value is="<<obj.cube(val1)<<endl<<obj.cube(val2);
getch();
}
Result
Example
#include<iostream.h>
#include<conio.h>
class data
{
static int x;
int y;
public:
void getdata(int a)
{
y=a;
x++;
}
void show_x()
{
cout<<"x="<<x<<"\n";
}
};
int data::x; //static member defination
void main()
{
clrscr();
data d1,d2;
d1.show_x();
Result
Note:
In above program when object are declared then initial value of static data member is
zero.
Whenever Function is called its value is increased by 1.
Object d1 object d1
Y=10 Y=20
X=2
Fig(1) Static Data Member
Know, this variable (x) is shared between both object, So the value of x is display 2.
1) It can only access other static data member and member function.
#include<iostream.h>
#include<conio.h>
class test
{
int x;
static int y;
public:
void set_xy(int a)
{
x=a;
y++;
}
void show_x()
{
cout<<"x="<<x<<"\n";
}
static void show_y()
{
cout<<"y="<<y;
}
};
int test::y;
void main()
{
clrscr();
test t1,t2;
t1.set_xy(10);
t2.set_xy(20);
t1.show_x();
t2.show_x();
test::show_y(); //calling static function
getch();
}
Result