Professional Documents
Culture Documents
In this tutorial we will give you simple and easy study material related to C++ language, C++ is
object oriented programming language. C++ are mainly used for Design Operating system,
History of C++
C++ language is developed by Bjarne Stroustrup in the year 1979 at bell laboratory at USA, C+
Prerequisites
Before learning C++ Programming language you need basic knowledge of C programming
Overview of C++
C++ is a computer programming language developed in 1980 by Bjarne Stroustrup at the Bell
Design Database
Utilities
Application Software
Features of C++
C++ is object oriented programming language and it is a very simple and easy language, It is the
enhanced form of C programming language. this language have following features and here we
Simple
Portability
Powerful
Platform dependent
Compiler based
Use of Pointers
Simple
Every C++ program can be written in simple English language so that it is very easy to
Platform dependent
A language is said to be platform dependent whenever the program is execute in the same
operating system where that was developed and compiled but not run and execute on other
Portability
It is the concept of carrying the instruction from one system to another system. In C++
Language .cpp file contain source code, we can edit also this code. .exe file contain application,
only we can execute this file. When we write and compile any C++ program on window operating
When we can copy .exe file to any other computer which contain window operating system then it
works properly, because the native code of application an operating system is same.
Powerful
C++ is a very powerful programming language, it have a wide verity of data types, functions,
This main advantage of C++ is, it is object oriented programming language. It follow concept of
Case sensitive
C++ is a case sensitive programming language. In C++ programming 'break and BREAK' both
are different.
If any language treats lower case latter separately and upper case latter separately than they can
be called as case sensitive programming language [Example c, c++, java, .net are sensitive
programming languages.] other wise it is called as case insensitive programming language
Compiler based
C++ is a compiler based programming language that means without compilation no C++ program
can be executed. First we need compiler to compile our program and then execute.
C++ is a strongly tight syntax based programming language. If any language follow rules and
regulation very strictly known as strongly tight syntax based language. Example C, C++, Java,
.net etc. If any language not follow rules and regulation very strictly known as loosely tight syntax
based language.
Example HTML.
Pointers is a variable which hold the address of another variable, pointer directly direct access to
memory address of any variable due to this performance of application is improve. In C++
Implementation details are hidden from other modules which represent a clearly
defined interface.
Applications of C++
For Develop Graphical related application like computer and mobile games.
C++ Language are also used for design OS. Like window xp.
Google also use C++ for Indexing
Some of the Google applications are also written in C++, including Google file
system and Google Chromium.
Installation of TC is very simple just download turbo C or C++ and run .exe files
When you install the Turbo C or C++ compiler on your system, then TC directory is created on
the hard disk and various sub directories such as INCLUDE, and LIB etc. are created under TC.
Previously Turbo C are not work properly on Window 7 and its above versions. Here you can get
TC Editor
TC Editor is very simple and easy to use; here i will give you all tips related to TC Editor and
some shortcut keys related to TC Editor which is very useful at the time of coding. Turbo C is a
most common C language compiler. Below i will discuss all about its Interfaces.
TC Editor
The interface of Turbo C is very simple. When IDE screen appears, the menu bar is activated. It
File: This menu contains group of commands used for save , edit , print program,
exit from Turbo C editor etc.
Edit: This menu contains group of commands used for editing C program source
code. Example Copy, Cut, Paste, Undo etc.
Search: This menu contains group of commands used for searching specific
word as well as replacing it with another one.
Run: This menu contains group of commands used for running C program.
Compile: This menu contains group of commands used for compiling C
program.
Debug: This menu contains group of commands used for debugging C program.
Project: This menu contains group of commands used for opening, closing and
creating projects.
Options: This menu contains group of commands used for configuring IDE of
Turbo C and setting up directories etc.
Windows: This menu contains group of commands used for opening, closing
various windows of IDE.
Help: This menu is used to get help about specific topic of C language. Similarly
to get help about a specific keyword or identifier of C.
Previously Turbo C are not work properly on Window 7 and its above versions. Here you can get
Compiler in C++
A compiler is system software which converts programming language code into binary format in
single steps. In other words Compiler is a system software which can take input from other any
programming language and convert it into lower level machine dependent language.
Interpreter
It is system software which is used to convert programming language code into binary format in
Assembler
An assembler is system software which is used to convert the assembly language instruction into
binary format in step by step process. An assembler is system software which is used to convert
Program need not to be compiled every Every time higher level program is
5
time converted into lower level program
It display error after entire program is It display error after each instruction
6
checked interpreted (if any)
Comments in C++
Generally Comments are used to provide the description about the Logic written in program.
When we are used the comments, then that specific part will be ignored by compiler.
possible.
Example
// header files
#include<iostream.h>
#include<conio.h>
void main()
{
// variable declaration
int a,b,c;
a=10;
b=20;
c=a+b;
cout<<"Sum: "<<c;
getch();
}
2. Nested Comments are not possible, that means comments within comments.
Example
void main()
{
/*
/* comments */
*/
}
Example
void main()
{
/* main
function
body part
*/
}
Example
void main()
{
/* MAIN Function BODY */
Keywords in C++
Keyword is a predefined or reserved word in C++ library with a fixed meaning and used to
Every Keyword exists in lower case latter like auto, break, case, const, continue, int etc.
do if static while
Another 30 reserved words that were not in C, these are new to C++
Note: you can not use these keyword for variable and not overload.
Constant in C++
It is an identifier whose value can not be changed at the execution time of program. In
If any single character (alphabet or numeric or special symbol) is enclosed between single cotes '
If set of characters are enclosed between double cotes " " known as string character constant.
Variable in C++
Variable is an identifier which holds data or another one variable is an identifier whose value can
be changed at the execution time of program. Variable is an identifier which can be used to
Syntax
Variable_name = value;
Variable declarations
This is the process of allocating sufficient memory space for the data in term of variable.
Syntax
Datatype variable_name; int a;
If no input values are assigned by the user than system will gives a default value called garbage
value.
Garbage value
Garbage value can be any value given by system and that is no way related to correct programs.
Variable initialization
It is the process of allocating sufficient memory space with user defined values.
Syntax
Datatype nariable_name=value;
Example
int b = 30;
Variable assignment
Syntax
Variable_Name = value
Example
int a= 20;
int b;
Example
To Declare any variable in C++ you need to follow rules and regulation of C++ Language, which
is given below;
Variable declarations
This is the process of allocating sufficient memory space for the data in term of variable.
Syntax
Datatype variable_name;
int a;
If no input values are assigned by the user than system will gives a default value called garbage
value.
Global variable
Global variables are defined outside of all the functions, generally on top of the program. The
global variables will hold their value throughout the life-time of your program.
Local variable
A local variable is declared within the body of a function or a block. Local variable only use within
#include<iostream.h>
#include<conio.h>
Output
Value of a: 10
Value of b: 20
Datatype in C++
Data type is a keyword used to identify type of data. It is used for storing the input of the program
into the main memory (RAM) of the computer by allocating sufficient amount of memory space in
In general every programming language is containing three categories of data types. They are
Fundamental or primitive data types
These are the data types whose variable can hold maximum one value at a time, in C++
Example
int a; // valid
a = 10,20,30; // invalid
These data type are derived from fundamental data type. Variables of derived data type allow us
to store multiple values of same type in one variable but never allows to store multiple values of
different types. These are the data type whose variable can hold more than one value of similar
Example
User defined data types related variables allows us to store multiple values either of same type or
different type or both. This is a data type whose variable can hold more than one value of
Syntax
struct emp
{
int id;
char ename[10];
float sal;
};
In C++ language, user defined data types can be developed by using struct, union, enum etc.
In C++ language Data Type Modifiers are keywords used to change the properties of current
properties of data type. Datatype modifiers are classified into following types.
long
short
unsigned
signed
Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount of
For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the
range by using long int which is 8 byte. We can decrease the range by using short int which is 2
byte.
long:
This can be used to increased size of the current data type to 2 more bytes, which can be applied
on int or double data types. For example int occupy 2 byte of memory if we use long with integer
Syntax
short
In general int data type occupies different memory spaces for a different operating system; to
Syntax
short int a; --> occupies 2 bytes of memory space in every operating system.
unsigned
This keyword can be used to make the accepting values of a data type is positive data type.
Syntax
This keyword accepts both negative or positive value and this is default properties or data type
Example
Note: in real time no need to write signed keyword explicitly for any data type.
Operators in C++
Operator is a special symbol that tells the compiler to perform specific mathematical or logical
Operation.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Given table shows all the Arithmetic operator supported by C Language. Lets suppose
variable Ahold 8 and B hold 3.
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0
Relational Operators
Which can be used to check the Condition, it always return true or false. Lets suppose
variable Ahold 8 and B hold 3.
== A== B False
!= A!=(-4) True
Logical Operator
Which can be used to combine more than one Condition?. Suppose you want to combined two
! !(B<=-A) True
T T T T F F
T F F T F T
F T F T T F
F F F F T T
Assignment operators
Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold 3.
+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
Increment operators are used to increase the value of the variable by one and decrement
Both increment and decrement operator are used on single operand or variable, so it is called as
unary operator. Unary operators are having higher priority than the other operators it means
Syntax
++ // increment operator
-- // decrement operator
pre-increment
post-increment
Syntax
++ variable;
#include<iostream.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=++i;
cout<<"x: "<<x;
cout<<"i: "<<i;
getch();
}
Output
x: 11
i: 11
In above program first increase the value of i and then used value of i into expression.
In post-increment first value of variable is use in the expression (initialize into another variable)
Syntax
variable ++;
Example post-increment
#include<iostream.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=i++;
cout<<"x: "<<x;
cout<<"i: "<<i;
getch();
}
Output
x: 10
i: 11
In above program first used the value of i into expression then increase value of i by 1.
pre-decrement
post-decrement
In pre-decrement first decrement the value of variable and then used inside the expression
Syntax
-- variable;
Example pre-decrement
#include<iostream.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=--i;
cout<<"x: "<<x;
cout<<"i: "<<i;
getch();
}
Output
x: 9
i: 9
In above program first decrease the value of i and then value of i used in expression.
In Post-decrement first value of variable is use in the expression (initialize into another variable)
Syntax
variable --;
Example post-decrement
#include<iostream.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=i--;
cout<<"x: "<<x;
cout<<"i: "<<i;
getch();
}
Output
x: 10
i: 9
In above program first used the value of x in expression then decrease value of i by 1.
Example
#include<iostream.h>
#include<conio.h>
void main()
{
int x,a,b,c;
a = 2;
b = 4;
c = 5;
x = a-- + b++ - ++c;
cout<<"x: "<<x;
getch();
}
Output
x: 0
For writing C++ code you need turbo c editor and write code after writing code save the code with
.cpp extension, compile the code and finally run the program.
Example
#include<iostream.h>
#include<conio.h>
void main()
{
cout<<"This is my first program";
getch();
}
Output
Save C program
Save any C++ program using .cpp Extension with file name. For example your program name is
filename.cpp
For compile any C++ program you just press alt+f9 , after compilation of your C++ program you
If any operator is used on three operands or variable is known as Ternary Operator. It can be
application.
Syntax
In the above symbol expression-1 is condition and expression-2 and expression-3 will be either
Syntax
Flow Diagram
Find largest number among 3 numbers using ternary operator
Example Ternary Operator in C++
#include<iostream.h>
#include<conio.h>
void main()
{
int a, b, c, large;
clrscr();
cout<<"Enter any three number: ";
cin>>a>>b>>c;
large=a>b ? (a>c?a:c) : (b>c?b:c);
cout<<"Largest Number is: "<<large;
getch();
}
Output
Largest number is 7
Priority:
Associativity:
It represents which operator should be evaluated first if an expression is containing more than
*, /, % 3 Left to right
+, - 4 Left to right
|| 7 Left to right
?: 8 Right to left
Example 1:
Example 2:
Types of Error in C++
Error is a abnormal condition whenever it occurs execution of the program is stopped these are
If any error is generated at the time of compilation is known as compile time error, in general
these are raised while break down the rules and regulation of programming language. Compile
Example
Int a=10,b;
In general it is very difficult to identify logical error in C language, to overcome this problem
Warning
Warning is also an abnormal condition but whenever it occurred execution of program will never
be stopped.
Note: In C language warning can be neglected but error can not be neglected.
Structure of C++ Program
Syntax
class class_name
{
data members;
user defined method;
{
..........
..........
}
};
Include section
# include is a pre-processor directive can be used to include all the predefined method of given
Syntax
#include<headerfile.h>
class
Class is a blue print which is containing only list of variables and method.
C++ library is collection of header files, header files is a container which is collection of related
predefined method.
If any method is defined by the user is known as user defined method. Method is collection of
Syntax
returntype method_name()
.......
.......
In the above syntax method name can be any user defined name, return type represents which
Syntax
Main() method
This is starting executable block of any program (it is always executed by processor and OS ).
One C++ program can have maximum one main() the entire statements of given program can be
executed through main(). Without main() method no C++ program will be executed.
Syntax
returntype main()
......
.....
If return type is void that method can not return any value to the operating system. So that void
Example
#include<iostream.h>
#include<conio.h>
void main()
{
cout<<("Hello main";
}
Output
Hello main
IO statements in C++
IO represents input output statements, and input statement can be used to read the input value
from the standard input device (keyboard), output statement can be used to display the output in
standard output device (Monitor) respectively. In C++ language IO statement can be achieve by
#include<iostream.h>
#include<conio.h>
void main()
{
int num;
clrscr();
cout<<"Hello word !"; // print message on screen
getch();
}
Output
Hello word !
cin
#include<iostream.h>
#include<conio.h>
void main()
{
int num;
clrscr();
cout<<"Enter any number:";
cin>>num; // accept one value form keyboard
cout<<"Number is: "<<num;
getch();
}
Output
main() function is the entry point of any C++ program. It is the point at which execution of
program is started. When a C++ program is executed, the execution control goes directly to the
void main()
{
............
............
}
In above syntax;
void: is a keyword in C++ language, void means nothing, whenever we use void
as a function return type then that function nothing return. here main() function no
return any value.
In place of void we can also use int return type of main() function, at that time
main() return integer type value.
main: is a name of function which is predefined function in C++ library.
#include<stdio.h>
void main()
{
cout<<"This is main function";
}
Output
clrscr() and getch() both are predefined function in "conio.h" (console input output header file).
Clrscr()
It is a predefined function in "conio.h" (console input output header file) used to clear the console
screen. It is a predefined function, by using this function we can clear the data from console
(Monitor). Using of clrscr() is always optional but it should be place after variable or function
declaration only.
Example of clrscr()
#include<iostream.h>
#include<conio.h>
void main()
{
int a=10, b=20;
int sum=0;
clrscr(); // use clrscr() after variable declaration
sum=a+b;
cout<<"Sum: "<<sum;
getch();
}
Output
Sum: 30
Getch()
It is a predefined function in "conio.h" (console input output header file) will tell to the console wait
for some time until a key is hit given after running of program.
By using this function we can read a character directly from the keyboard. Generally getch() are
Example of getch()
#include<iostream.h>
#include<conio.h>
void main()
{
int a=10, b=20;
int sum=0;
clrscr();
sum=a+b;
cout<<"Sum: "<<sum;
getch(); // use getch() befor end of main()
}
Output
Sum: 30
Function in C++
A function is a group of statements that together perform a specific task. Every C++ program has
Function are used for divide a large code into module, due to this we can easily debug and
maintain the code. For example if we write a calculator programs at that time we can write every
logic in a separate function (For addition sum(), for subtraction sub()). Any function can be called
many times.
Advantage of Function
Code Re-usability
Type of Function
Library functions are those which are predefined in C++ compiler. The implementation part of
pre-defined functions is available in library files that are .lib/.obj files. .lib or .obj files are
contained pre-compiled code. printf(), scanf(), clrscr(), pow() etc. are pre-defined functions.
All predefined function are contained limited task only that is for what purpose
function is designed for same purpose it should be used.
These functions are created by programmer according to their requirement for example suppose
you want to create a function for add two number then you create a function with name sum() this
Defining of function is nothing but give body of function that means write logic inside function
body.
Syntax
return_type function_name(parameter)
function body;
Return type: A function may return a value. The return_type is the data type of
the value the function returns.Return type parameters and returns statement are
optional.
Function name: Function name is the name of function it is decided by
programmer or you.
Parameters: This is a value which is pass in function at the time of calling of
function A parameter is like a placeholder. It is optional.
Function body: Function body is the collection of statements.
Function Declarations
A function declaration is the process of tells the compiler about a function name. The actual body
Syntax
return_type function_name(parameter);
Note: At the time of function declaration function must be terminated with ';'.
calling a function.
When we call any function control goes to function body and execute entire code. For call any
function just write name of function and if any parameter is required then pass parameter.
Syntax
function_name();
or
variable=function_name(argument);
Note: At the time of function calling function must be terminated with ';'.
Example of Function in C++
#include<iostream.h>
#include<conio.h>
Output
Sum: 30
Call by Value and Call by Reference in C++
On the basis of arguments there are two types of function are available in C++ language, they
are;
With argument
Without argument
If a function take any arguments, it must declare variables that accept the values as a arguments.
These variables are called the formal parameters of the function. There are two ways to pass
call by value
call by reference
Call by value
In call by value, original value can not be changed or modified. In call by value, when you
passed value to the function it is locally stored by the function parameter in stack memory
location. If you change the value of function parameter, it is changed for the current function only
but it not change the value of variable inside the caller function such as main().
Call by value
#include<iostream.h>
#include<conio.h>
void main()
{
int a=100, b=200;
clrscr();
swap(a, b); // passing value to function
cout<<"Value of a"<<a;
cout<<"Value of b"<<b;
getch();
}
Output
Value of a: 200
Value of b: 100
Call by reference
(address). Here, address of the value is passed in the function, so actual and formal arguments
shares the same address space. Hence, any value changed inside the function, is reflected
#include<iostream.h>
#include<conio.h>
void main()
{
int a=100, b=200;
clrscr();
swap(&a, &b); // passing value to function
cout<<"Value of a"<<a;
cout<<"Value of b"<<b;
getch();
}
Output
Value of a: 200
Value of b: 100
This method copy original value into This method copy address of arguments
1
function as a arguments. into function as a arguments.
Changes made to the parameter inside Changes made to the parameter affect
2 the function have no effect on the the argument. Because address is used
argument. to access the actual argument.
Actual and formal arguments will be Actual and formal arguments will be
3
created in different memory location created in same memory location
Inline Function is powerful concept in C++ programming language. If a function is inline, the
compiler places a copy of the code of that function at each point where the function is called at
compile time.
To make any function inline function just preceded that function with inline keyword.
Why use Inline function
Whenever we call any function many time then, it take a lot of extra time in execution of series of
instructions such as saving the register, pushing arguments, returning to calling function. For
Syntax
inline function_name()
//function body
Example
#include<iostream.h>
#include<conio.h>
void main()
{
show(); // Call it like a normal function
getch();
}
Output
Hello word
Whenever same method name is exiting multiple times in the same class with different number of
overloading.
Suppose we have to perform addition of given number but there can be any number of
arguments, if we write method such as a(int, int)for two arguments, b(int, int, int) for three
arguments then it is very difficult for you and other programmer to understand purpose or
behaviors of method they can not identify purpose of method. So we use method overloading to
easily figure out the program. For example above two methods we can write sum(int, int) and
Syntax
class class_Name
Returntype method()
{
...........
...........
...........
...........
...........
...........
};
In this example, we have created two overloaded methods, first sum method performs addition of
two numbers and second sum method performs addition of three numbers.
class Addition
{
public:
void sum(int a, int b)
{
cout<<a+b;
}
void sum(int a, int b, int c)
{
cout<<a+b+c;
}
};
void main()
{
clrscr();
Addition obj;
obj.sum(10, 20);
cout<<endl;
obj.sum(10, 20, 30);
}
Output
30
60
In this example, we have created two overloaded methods that differs in data type. The first sum
method receives two integer arguments and second sum method receives two float arguments.
class Addition
{
public:
void sum(int a, int b)
{
cout<<a+b;
}
void sum(float a, float b)
{
cout<<a+b+c;
}
};
void main()
{
clrscr();
Addition obj;
obj.sum(10, 20);
cout<<endl;
obj.sum(10, 20, 30);
}
Output
30
25.25
A function can be made a friend function using keyword friend. Any friend function is preceded
with friend keyword. The declaration of friend function should be made inside the body of class
(can be anywhere inside class either in private or public section) starting with keyword friend.
You do not access private or protected data member of any class, to access private and
Syntax
class class_name
......
Friend class
Similarly like, friend function a class can be made a friend of another class using keyword friend.
Syntax
class A
......
}
class B
......
When a class is made a friend class, all the member functions of that class becomes friend
function.
If B is declared friend class of A then, all member functions of class B can access private and
protected data of class A but, member functions of class A can not private and protected data of
class B.
In below example you can access private function of class employee by using friend function.
Example
#include<iostream.h>
#include<conio.h>
class employee
{
private:
friend void sal();
};
void sal()
{
int salary=4000;
cout<<"Salary: "<<salary;
}
void main()
{
employee e;
sal();
getch();
}
Output
Salary: 4000
A virtual function is a member function of class that is declared within a base class and re-
When you want to use same function name in both the base and derived class, then the function
in base class is declared as virtual by using the virtual keyword and again re-defined this
.......
.......
class A
{
public:
virtual void show()
{
cout<<"Hello base class";
}
};
class B : public A
{
public:
void show()
{
cout<<"Hello derive class";
}
};
void main()
{
clrsct();
A aobj;
B bobj;
A *bptr;
bptr=&aobj;
bptr->show(); // call base class function
bptr=&bobj;
bptr->show(); // call derive class function
getch();
}
Output
Hello base class
Recursion in C++
When method is call within same method is called Recursion. The method which call same
method is called recursive method. In other words when a method call itself then that method is
called Recursive method.
Recursive method are very useful to solve many mathematical problems like to calculate factorial
Advantage of Recursion
Disadvantage of Recursion
#include<iostream.h>
#include<conio.h>
void main()
{
int fact(int);
int i,f,num;
clrscr();
cout<<"Enter any number: ";
cin>>num;
f=fact(num);
cout<<"Factorial: "<<f;
getch();
}
int fact(int n)
{
if(a<0)
return(-1);
if(a==0)
return(1);
else
{
return(n*fact(n-1));
}
}
Output
Factorial: 120
Find the Table of any number using recursion
Example
#include<iostream.h>
#include<conio.h>
void main()
{
int table(int,int);
int n,i; // local variable
clrscr();
cout<<"Enter any num : ";
cin>>n;
for(i=1;i< =10;i++)
{
cout<<n<<"*"<<i<<= <<table(n,i)<<endl;
}
getch();
}
int table(n,i)
{
int t;
if(i==1)
{
return(n);
}
else
{
t=(table(n,i-1)+n);
return(t);
//return(table(n,i-1)+n);
}
}
Output
5*1= 5
5*2= 10
5*3= 15
5*4= 20
5*5= 25
5*6= 30
5*7= 35
5*8= 40
5*9= 45
5*10= 50
language, which is in itself one of the most powerful programming languages. If any programming
language follow below oops concept then that language called object oriented programming
language.
Object
Class
Encapsulation
Abstraction
Inheritance
Polymorphism
Object
Object is the physical as well as logical entity where as class is the only logical entity.
Class
Class: Class is a blue print which is containing only list of variables and method and no memory
is allocated for them. A class is a group of objects that has common properties.
Encapsulation
advantage of using of encapsulation is to secure the data from other methods, when we make a
data private then these data only use within the class, but these data not accessible outside the
class.
Abstraction
Abstraction is the concept of exposing only the required essential characteristics and behavior
Hiding of data is known as data abstraction. In object oriented programming language this is
implemented automatically while writing the code in the form of class and object.
Inheritance
The process of obtaining the data members and methods from one class to another class is
Polymorphism
The process of representing one Form in multiple forms is known as Polymorphism. Here one
form represent original form or original method always resides in base class and multiple forms
Access specifiers in C++ define how the members of the class can be accessed. C++ has 3
public
private
protected
The keywords public, private, and protected are called access specifiers. A class can have
Note: By default, all members and function of a class is private i.e if no access specifier is
specified.
class
{
private:
public:
protected:
};
Public class members are accessible out side the class and it is available for every one.
Syntax
class Public_Access_Specifier
Private class members are accessible with the class and it is not accessible out side the class. If
some one try to access out side the it gives compile time error. By default class variables and
class Private_Access_Specifier
#include<iostream.h>
#include<conio.h>
class A
{
private:
int a;
public:
int b;
public:
void show()
{
a=10 ;
b=20;
clrscr();
//Every members can be access here, same class
cout<<"\nAccessing variable within the class"<<endl;
cout<<"Value of a: "<<a<<endl;
cout<<"Value of b: "<<b<<endl;
}
};
void main()
{
A obj; // create object
obj.show();
getch();
}
Note: If here, we access variable a in side main method it will give compile time error
Output
value of a: 10
value of b: 20
value of c: 30
Value of b: 20
Protected Access Specifier in C++
It is similar to private access specifier. It makes class member inaccessible outside the class. But
Syntax
class Protected_Access_Specifier
In below example I will show you all these access specifier public, private and protected.
#include<iostream.h>
#include<conio.h>
class Declaration
{
private:
int a;
public:
int b;
protected:
int c;
public:
void show()
{
a=10;
b=20;
c=30;
cout<<"Value of a: "<<a<<endl;
cout<<"Value of b: "<<b<<endl;
cout<<"Value of c: "<<c<<endl;
}
};
Output
value of a: 10
value of b: 20
value of c: 30
value of b: 5
value of c: 6
Accessing variable outside the class
Value of b: 20
Object is the physical as well as logical entity where as class is the only logical entity.
Class: Class is a blue print which is containing only list of variables and method and no memory
is allocated for them. A class is a group of objects that has common properties.
Data Member
Method
Constructor
Block
State
Behavior
Identity
Syntax
class_name object_reference;
Example
Employee e;
Identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible
to the external user. But,it is used internally by the JVM to identify each object uniquely.
In real world many examples of object and class like dog, cat, and cow are belong to animal's
class. Each object has state and behaviors. For example a dog has state:- color, name, height,
Vehicle class
Car, bike, truck these all are belongs to vehicle class. These Objects have also different different
states and behaviors. For Example car has state - color, name, model, speed, Mileage. as we;;
Class Object
One class definition should exist only For one class multiple objects can be
3
once in the program. created.
class Class_Name
data member;
method;
}
In this example, we have created a Employee class that have two data members eid and ename.
We are creating the object of the Employee class and printing the objects value.
Example
#include<iostream.h>
#include<conio.h>
class Employee
{
public:
int salary // data member
void sal()
{
cout<<"Enter salary: ";
cin>>salary;
cout<<"Salary: "<<salary;
}
};
void main()
{
clrscr();
Employee e; //creating an object of Employee
e.sal();
getch();
}
Output
Salary: 4500
Inheritance in C++
The process of obtaining the data members and methods from one class to another class is
Important points
In the inheritance the class which is give data members and methods is known as
base or super or parent class.
The class which is taking the data members and methods is known as sub or
derived or child class.
Syntax
// data members
// methods
The real life example of inheritance is child and parents, all the properties of father are inherited
by his son.
Diagram
In the above diagram data members and methods are represented in broken line are inherited
from faculty class and they are visible in student class logically.
Advantage of inheritance
If we develop any application using this concept than that application have following advantages,
Tpyes of Inheritance
Based on number of ways inheriting the feature of base class into derived class it have five types
they are:
Single inheritance
Multiple inheritance
Hierarchical inheritance
Multiple inheritance
Hybrid inheritance
Single inheritance
In single inheritance there exists single base class and single derived class.
Multiple inheritances
In multiple inheritances there exists single base class, single derived class and multiple
An intermediate base class is one in one context with access derived class and in another
Hence all the above three inheritance types are supported by both classes and interfaces.
Multiple inheritance
In multiple inheritance there exist multiple classes and singel derived class.
Hybrid inheritance
In order to inherit the feature of base class into derived class we use the following syntax
Syntax
variable declaration;
method declaration;
Explanation
classname-1 and classname-2 represents name of the base and derived classes
respectively.
: is operator which is used for inheriting the features of base class into derived
class it improves the functionality of derived class.
Example of Inheritance in C++
#include<iostream.h>
#include<conio.h>
class employee
{
public:
int salary;
};
class developer : public employee
{
employee e;
public:
void salary()
{
cout<<"Enter employee salary: ";
cin>>e.salary; // access base class data member
cout<<"Employee salary: "<<e.salary;
}
};
void main()
{
clrscr();
developer obj;
obj.salary();
getch();
}
Output
Abstraction in C++
Abstraction is the concept of exposing only the required essential characteristics and behavior
Hiding of data is known as data abstraction. In object oriented programming language this is
implemented automatically while writing the code in the form of class and object.
Abstraction shows only important things to the user and hides the internal details for example
when we ride a bick, we only know about how to ride bick but can not know about how it work ?
#include<iostream.h>
#include<conio.h>
class sum
{
// hidden data from outside world
private: int a,b,c;
public:
void add()
{
clrscr();
cout<<"Enter any two numbers: ";
cin>>a>>b;
c=a+b;
cout<<"Sum: "<<c;
}
};
void main()
{
sum s;
s.add();
getch();
}
Output
Enter any two number:
Sum: 9
Note: Data abstraction can be used to provide security for the data from the unauthorized
methods.
Encapsulation in C++
Advantage of Encapsulation
The main advantage of using of encapsulation is to secure the data from other methods, when
we make a data private then these data only use within the class, but these data not accessible
The common example of encapsulation is Capsule. In capsule all medicine are encapsulated in
side capsule.
Benefits of encapsulation
#include<iostream.h>
#include<conio.h>
class sum
{
private: int a,b,c;
public:
void add()
{
clrscr();
cout<<"Enter any two numbers: ";
cin>>a>>b;
c=a+b;
cout<<"Sum: "<<c;
}
};
void main()
{
sum s;
s.add();
getch();
}
Output
Sum: 9
In above example all data and function are bind inside class sum.
Polymorphism in C++
The process of representing one Form in multiple forms is known as Polymorphism. Here one
form represent original form or original method always resides in base class and multiple forms
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
Suppose if you are in class room that time you behave like a student, when you are in market at
that time you behave like a customer, when you at your home at that time you behave like a son
In C++ programming you can achieve compile time polymorphism in two way, which is given
below;
Method overloading
Method overriding
Whenever same method name is exiting multiple times in the same class with different number of
overloading. In below example method "sum()" is present in Addition class with same name but
class Addition
{
public:
void sum(int a, int b)
{
cout<<a+b;
}
void sum(int a, int b, int c)
{
cout<<a+b+c;
}
};
void main()
{
clrscr();
Addition obj;
obj.sum(10, 20);
cout<<endl;
obj.sum(10, 20, 30);
}
Output
30
60
Define any method in both base class and derived class with same name, same parameters or
signature, this concept is known as method overriding. In below example same method
"show()" is present in both base and derived class with same name and signature.
Example of Method Overriding in C++
#include<iostream.h>
#include<conio.h>
class Base
{
public:
void show()
{
cout<<"Base class";
}
};
class Derived:public Base
{
public:
void show()
{
cout<<"Derived Class";
}
}
int mian()
{
Base b; //Base class object
Derived d; //Derived class object
b.show(); //Early Binding Ocuurs
d.show();
getch();
}
Output
Base class
Derived Class