History of C++ :
· C++ is an object oriented language . It was developed by Bjarne Stroustrup at AT&T Bell Laboratories ,USA in the early 1980
Stroustrup initially called the new language ‘ C with Classes ‘ later in 1983 name was changed to C++
The idea of C++ comes from the C with increment operator
C++ is a superset of ‘C’
The idea of C++ comes from the C with increment operator
C++ is a superset of ‘C’
Application Of ‘C++’ :
Using C++ we can build special object oriented libraries which can be used later by many programmers
C++ programs easily maintainable and expandable
Basic differences between ‘C’ and ‘C++’ ?
C(POP)
|
C++(OOP)
|
C is Commonly known as POP
In procedure oriented program problem can viewed as sequence of instructions like
Reading , calculating , printing
-Here no of functions used to accomplish the tasks that’s why primary focus on the functions
Here we concentrate more on development of functions very little attention data
Here data we use in program which available to multiple functions example global data
Here we divide a large programs into smaller programs known as functions
It employees top-down approach
|
· C++ follows OOP
· In OPP allowed to decomposition of problems in to number of entities called objects
· Here primary focus on data rather than procedure
· OPP concentrate more on data and its treat data as critical element in the program development and does not allow it to flow freely around the system
· Data hidden, cannot accessed by external functions
· Programs divide into smaller units known as objects
· It employees bottom-up approach
|
Structure of CPP program:
Include files
|
Class declaration
|
Member function definitions
|
Main function program
|
Basic Input and output operations:
The standard C++ library includes the header file iostream , where standard input and output stream objects are declared
For out operation we use ‘cout’ object conjunction with insertion operator or putto operator
Ex: cout<<” wel come to c”;
In the above example the identifier “cout “ is predefined object that represents the standard output stream in C++
The “<<” is called insertion OR putto operator . It inserts the contents of the variable on its right to the object on its left.
For input operation we use ‘cin’ object conjunction with extraction operator or getfrom operator
Ex: cin>>n;
In the above example the identifier “cin “ is predefined object that represents the standard input stream in C++
The “>>” is called extraction OR getfrom operator . It extracts the value from the keyboard assign it to the variable on its right .
C++ comments :
C++ comments are two types , Those are
1)single line comments
2) multi line comments
1.single line comments:
Single line comments represented by ‘//’(double slash)
Comments start with double slash symbol and terminate with the end of the line
Ex: // this is an example of single line comments
2. multiline comments:
Multiline line comments shown like this /* ……….*/
Ex: /* hai , I am new for basic c++
Programming */
Tokens:
The smallest individual units of a program are known as tokens .C++ has the following tokens
Keywords
Identifiers
Constant
Strings
Operators
Operators
Keywords :
Every C++ word is classified as either a key word or an identifier .
All keywords have fixed meaning and this meaning cannot be changed keywords serve as basic building blocks for program statements
Some commonly used Keyword are given below:
asm
|
auto
|
break
|
case
|
catch
|
char
|
class
|
const
|
continue
|
default
|
delete
|
do
|
double
|
else
|
enum
|
extern
|
inline
|
int
|
float
|
for
|
friend
|
goto
|
if
|
long
|
new
|
operator
|
private
|
protected
|
public
|
register
|
return
|
short
|
signed
|
sizeof
|
static
|
struct
|
switch
|
template
|
this
|
Try
|
typedef
|
union
|
unsigned
|
virtual
|
void
|
volatile
|
while
|
Identifiers:
Identifiers refers to the names of variables , functions and arrays .These are user defined names and consist of a sequences of letters , and digits with a letter as first character both uppercase and lowercase are permitted although lowercase letters commonly used and underscore character also permitted.
Basic Data Types:
C++ has a concept of 'data types' which are used to define a variable before its use . Depending on data type variable occupy computers memory .
Built-in type (OR) Primary Data Type:
Constants :
Constants are fixed values that don’t change during the execution of a program . C++ supports several types of constants .
Like C ,C++ support several kinds literal constant
· Integer-Constants
· Character-constants
· Floating-constants
· Strings-constants
Basic Data Types:
· Built-in type (OR) Primary DataType
· Derived Data Type
· User-defined type
Type
|
Typical Bit Width
|
Typical Range
|
char
|
1byte
|
-127 to 127 or 0 to 255
|
unsigned char
|
1byte
|
0 to 255
|
signed char
|
1byte
|
-127 to 127
|
int
|
4bytes
|
-2147483648 to 2147483647
|
unsigned int
|
4bytes
|
0 to 4294967295
|
signed int
|
4bytes
|
-2147483648 to 2147483647
|
short int
|
2bytes
|
-32768 to 32767
|
unsigned short int
|
2bytes
|
0 to 65,535
|
signed short int
|
2bytes
|
-32768 to 32767
|
long int
|
4bytes
|
-2,147,483,647 to 2,147,483,647
|
signed long int
|
4bytes
|
same as long int
|
unsigned long int
|
4bytes
|
0 to 4,294,967,295
|
float
|
4bytes
|
+/- 3.4e +/- 38 (~7 digits)
|
double
|
8bytes
|
+/- 1.7e +/- 308 (~15 digits)
|
long double
|
8bytes
|
+/- 1.7e +/- 308 (~15 digits)
|
#include <iostream>
using namespace std;
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;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
Output
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 8
Size of float : 4
Size of double : 8
Size of wchar_t : 4
Derived Data Type
· Array
· Function
· Pointer
· reference
User-defined type
· Structure
· Union
· Class
· Enumeration
Symbolic Constants:
There are two ways of creating symbolic constants in c++
Using the qualifier const ,and
Defining a set of integer constants using enum keyword
In both ‘c’ and ‘c++’ any value declared as const cannot be modified by the program in any way .
Const int size=10;
Enumeration:
An enum is a user-defined type in ‘C++’
An enumeration consists of a set of named integer constants
An enumeration type declaration gives the name of the (optional) enumeration tag and defines the set of named integer identifiers
(Or)
An enum is a user-defined type consisting of a set of named constants called enumerators
4
enum Color
{
COLOR_BLACK, // assigned 0
COLOR_RED, // assigned 1
COLOR_BLUE, // assigned 2
COLOR_GREEN, // assigned 3
COLOR_WHITE, // assigned 4
COLOR_CYAN, // assigned 5
COLOR_YELLOW, // assigned 6
COLOR_MAGENTA // assigned 7
};
Color eColor = COLOR_WHITE;
cout << eColor;
o/p:
Reference Variable :
C++ introduces a new introduces a new kind of variable . A reference variable provides an alias for a previously defined variable .
Main()
{
int sum=10;
int sum=10;
Int &i=sum;
Cout<<sum;
Cout<<I;
}
Void m1(int &);
Main( )
{
Int a=10;
m1(a);
cout<<” I am from main”<<endl;
cout<<a;
}
Void m1(int &s)
{
Cout<<s;
S=s+1;
}
Op:
10 I am from main 11
Operators in C++:
C++ have rich set of operators .All C operators are valid in C++ .in addition to C++ introduce some new operators .
<<- insertion operator
>>-extraction operator
:: (scope resolution)
::* pointer-to-member declaration
->* pointer-to-member operator
.* pointer-to-member operator
Delete - memory release operator
Endl -line feed operator
New- memory allocation operator
Setw -field width operator
scope resolution operator :
If the resolution operator is placed between the class name and the data member belonging the class then data name belonging to the particularly class is affected.
If it is place front of the variable name then the global variable is affected. It is no resolution operator is placed then the local variable is affected.
Int s=10;
Main()
{ints=11;
cout<<s ; //11
cout<<::s; //10
}
}
Member dereferencing operators:
::* pointer-to-member declaration (to declare a pointer to a member of class)
.* pointer-to-member operator (to access a member using object name and a pointer to that member)
->* pointer-to-member operator (to access a member using pointer to the object and a pointer to that member)
Memory management operators :
New , Delete
C++ uses new and delete operators that perform the task of allocating and freeing the memory in a better and efficient way.
Pointer-variable=new data-type
Delete Pointer-variable;
Manipulators:
Manipulators are operators that are used to format the data display . The most commonly used manipulators are endl ,setw
Cout<<setw(10)<<”basic”<<endl;
Cout<<setw(10)<<”allowence”<<endl;
o/p:
allowence
basic
Introduction to Control Structures in C++ :
Control Structures are statements that change the flow of a program to a different code segment based on certain conditions. The control structures are categorized into three major Conditional types they are Selection Statements, Iteration statements, Jump Statements.
· Sequence structure
· Selection structure
· Loop structure /Iteration/Repetition
Sequence structure:
As name refers instructions are executed in the sequence in which they are written in
The program
Void main()
{
statement-1;
statement-1;
Statement-2;
}
Selection structure in C++:
A structure which select which statement or block of statements will execute on the basis of our programming logic
A structure which select which statement or block of statements will execute on the basis of our programming logic
· If
· If-else
· Switch
Loop structure /Iteration/Repetition :
· Do-while
· While
· for
Selection structure in C++:
Simple if statement :
The if statement is a powerful decision making statement. It is used to control the flow of execution of statements .
This allow to computer evaluate expression first and then depending value of expression is true or transfer control to the particular statement
if(conditional-expression)
{
statement-block ;
}
The ‘statement-block’ may be a single statement or a group of statements . In above simple if statement example if the ‘conditional-expression’ results true then the ‘statement-block’ will be executed .
If…..else statement :
The general form of if….else statement is as following: -In case of if…else statement if the ‘conditional-expression’ results true then the ‘statement-block 1’ of if part will be executed and ‘statement-block-2’ of else part will be skipped . If ‘conditional-expression’ results false then the ‘statement-block1’ of if part will be skipped and the ‘statement-block2’ of else part will be executed
if(conditional-expression)
{
statement-block 1 ;
}
else
{
statement-block 2 ;
}
II) switch statement:
We have studied that if statements are used to select one option among multiple options .The use of if statements becomes complex when the number of choices increases . To overcome this problem C has an alternative decision statement known as switch statement .The switch statement is also called as built-in multi way decision statement. In switch statement the value of a given variable or expression is compared against a list of case values and when a match is found , the block of statement inside that case and all subsequent case statement as well as default statement will be executed .To prevent execution of subsequent cases we use break statement at the end of each case
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
default:
block-4;
}
Loop structure /Iteration/Repetition :
· Do-while
· While
· for
In looping ,a sequence of statements are executed until some conditions evaluated as false
A loop consists two segments:-
1. Body of the loop
2. Control statement
The control statement tests the certain conditions and then directs the repeated execution of the statements contained in the body for the loop . Depending on the position of the control statement in the loop , there are three loops available in C .
1. The While statement .
2. The do-while statement .
3. The for statement
The While statement :
The while loop is the simplest loop structure in C .
The general form of WHILE loop is as following: -
while(check-condition)
while(check-condition)
{
Body of loop;
}
The while loop is entry controlled loop in which the check condition is evaluated and if condition is true, then body of the loop is executed. After the execution of the body the control again checks the condition and if the condition results true then once again the body of the loop is executed . This process is repeated until the check condition results false. When check condition results false the control is transferred to the statement out of the body of loop .
The do-while statement :
do
{
Body of loop;
}while(check-condition);
In case of do-while loop, body of loop is executed first then the condition is evaluated .If the condition results true , the body of the loop executed . This process repeats until the check condition results false. When the check condition results false then control goes out of the loop body. It is called exit control loop because the test condition is evaluated at the bottom of the loop. Due to this body of loop is executed at least once even when the test condition false.
Difference between while and do-while :
While
|
Do-while
|
In While loop the condition is
tested first and then the statements are executed if the condition turns out to be true. Its is pre condition checking is there in while
simple while is more commonly
used its execute statements if and only if condition evaluated as true
while loop do not run in case the condition given is false
In a while loop the condition is
first tested and if it returns true then it goes in the loop
While loop is entry control loop
syntax while(check-condition)
{
Body of loop;
}
|
In do while the statements are executed for the first time and then the conditions
are tested, if the condition turns out to be true then the statements are executed again. Its is post condition checking is there in while
A do while is used for a block
of code that must be executed at least once.
A do while loop runs at least once
even though the the condition given is false
In a do-while loop the condition is
tested at the last
where as do while is exit control loop.
syntax
do
{
Body of loop;
}while(check-condition);
|
The for statement :
The for- loop is implemented where the number of times a statement or a block of statement to be executed is known in advance
for(counter-initialization;check-condition;counter-updation)
{
block-statement;
}
The counter-initialization is generally assignment statement which is used to set the loop control variable .
The condition is a relational expression that determines when the loop will exit . Counter–updation defines how loop control variable will change every time the loop body executed .These three parts of the for loop should be ended with semicolon.
Write a program for multiplication table
#include<iostream.h>
#include<conio.h>
//#include<iomanip>
void main()
{
intn,i;
clrscr();
cout<<"enter any number to find multiplication table \n"<<endl;
cin>>n;
for(i=1;i<=10;i++)
cout<<i<<"*"<<n<<"="<<i*n<<endl;
}
o/p:
enter any number to find multiplication table
5
1*5=5
2*5=10
3*5=15
4*5=20
5*5=25
6*5=30
7*5=35
8*5=40
9*5=45
10*5=50
Write a program for calculating sum of digits in a given number
#include<iostream.h>
#include<conio.h>
//#include<iomanip>
void main()
{
intn,i,sum=0;
clrscr();
cout<<"enter number to find sum of digits"<<endl;
cin>>n;
while(n>0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
cout<<"sum of the digits in number are="<<sum;
getch();
}
Write a program for find Fibonacci series
#include<iostream.h>
#include<conio.h>
//#include<iomanip>
void main()
{
intn,i,sum=0;
clrscr();
cout<<"enter number to find sum of digits"<<endl;
cin>>n;
while(n>0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
cout<<"sum of the digits in number are="<<sum;
getch();
}
Functions:
Function is derived data type in C++ language
A function is a self block of code that perform a particular task .
Or
A function is a block of executable statement that perform the tasks that are define with in its block.
Or
A function is a group of statements that together perform a task. Every C++ program has at least one function which is main().
Functions are categorized as two types:
1)Predefined (System defined) functions:
The C++ standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings etc…
2)User – defined function:
These function are defined by the programmer for a specific purpose in a program.
In order to establish make use of a user-defined functions , we need to establish a three elements that are related to functions
1) Function definition
2) Function call
3) Function declaration
1) Function definition :
The function of consists of two parts function header and function body.
Return-type function_name(parameter list)
{
body of the function
}
The function header is:-
return_type function_name(parameter list)
The return_type specifies the type of the data the function returns. The return_type can be void which means function does not return any data type. The function_name is the name of the function. The name of the function should begin with the alphabet or underscore. The parameter list consists of variables separated with comma along with their data types. The parameter list could be empty which means the function do not contain any parameters. The parameter list should contain both data type and name of the variable ,parameters which are present in function definition are known as formal parameters
Function body contain set of instructions that is used for performing certain tasks . Depending on return type it’s return a value
int max(int num1, int num2)
{
Stmt1;
Stmt2;
Stmt3;
return result;
}
Function call:
In functionCall you simply need to pass the required parameters along with function name and if function returns a value then you can store returned value.
For example: ret = max(a, b);
Function Declaration
A function declaration is made by declaring the return type of the function, name of the function and the data types of the parameters of the function. A function declaration is same as the declaration of the variable. The function declaration is always terminated by the semicolon. A call to the function cannot be made unless it is declared. The general form of the declaration is:-
return_type function_name(parameter list);
For example function declaration can be
int max(int num1, int num2);
The variable names in the function declaration can be optional but data types are necessary.
You can write like this also
Int max(int ,int);
Call By Ref :
Reference variable in c++ permits us to pass parameters to the functions by reference when we pass arguments by reference , the formal arguments in the called function become a actual arguments In calling function
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
void swap(int&,int&);
int main()
{
int m,n;
clrscr();
cout<<"entr m,n values"<<endl;
cin>>m>>n;
cout<<"befor swaping m,n values"<<endl;
cout<<m<<n<<endl;
swap(m,n);
cout<<"after swaping m,n values"<<endl;
cout<<m<<n<<endl;
return 0;
}
void swap(int &m,int &n)
{
int t;
t=m;
m=n;
n=t;
}
Returning a Reference :
As a function can be created to return a value of a primitive type, a function can also be defined to return a reference to a primitive type. When declaring such a function, you must indicate that it is returning a reference by preceding it with the & operator
#include<iostream.h>
#include<conio.h>
int &square(int);
main()
{
int a,b;
clrscr();
cout<<"enter a value"<<endl;
cin>>b;
a=square(b);
cout<<"val of a is"<<endl<<a<<endl;
return 0;
}int &square(int x)
{
int &b=x*x;
return b;
}
Default parameters :
C++ allows us to call a function without specifying all its arguments . In such cases the function assigns a default value to the parameter which does not have a matching argument in the function call .Default values are specified when the function is declared .
#include<conio.h>
#include<iostream.h>
#include<iomanip.h>
void print(int =1,int =2,int =3);
void main()
{
int x,y,z;
clrscr();
cout<<"enter values for x and y"<<endl;
cin>>x>>y>>z;
cout<<"with out passing any val"<<endl;
print();
cout<<"passing one val"<<endl;
print(x);
cout<<"passing two vals"<<endl;
print(x,y);
cout<<"passing three vals"<<endl;
print(x,y,z);
}
void print(int a,int b,int c)
{
cout<<"the values are"<<endl;
cout<<"a="<<a<<setw(5)<<"b="<<b<<setw(5)<<"c="<<c<<endl;
}
Any or all of the function's parameters can be assigned default values. The one restriction is this: If any of the parameters does not have a default value, no previous parameter may have a default value.
If the function prototype looks like
long myFunction (int Param1, int Param2, int Param3);
you can assign a default value to Param2 only if you have assigned a default value to Param3. You can assign a default value to Param1 only if you've assigned default values to both Param2 and Param3. Program below demonstrates the use of default values.
Const Arguments:
Using const keyword we can make function arguments into constants
Void swap(const int &,int &);
Inline functions :
when we use normal function in our program its take more time for executing series of instructions .jumping to the functions ,saving registers , pushing arguments into the stack , returning value to the calling functions . When function is small also compiler spent more time for these tasks .
C++ has a different solution to this problem to eliminate the cost of calls to small functions c++ proposes a new feature called inline function . An inline function is function that is expanded in a line when it is invoked . 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 inline a function, place the keyword inline before the function name and define the function before any calls are made to the function
A function definition in a class definition is an inline function definition, even without the use of theinline specifier
C++ has a different solution to this problem to eliminate the cost of calls to small functions c++ proposes a new feature called inline function . An inline function is function that is expanded in a line when it is invoked . 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 inline a function, place the keyword inline before the function name and define the function before any calls are made to the function
A function definition in a class definition is an inline function definition, even without the use of theinline specifier
Syntax:
Inline function-header
{
Function body;
}
Write program for illustrating inline functions
#include<iostream.h>
#include<conio.h>
inline int square(int x)
{
return (x*x);
}
inline int cube(int y)
{
return (y*y*y);
}
int main()
{
int a,b,x,y,z,t;
cout<<"enter x,y values";
cin>>x>>y>>z>>t;
a=square(x);
cout<<"the square of the number is "<<endl<<a<<endl;
b=cube(y);
cout<<"the cube of the number is "<<endl<<b<<endl;
return 0;
}
Disadvantages :
Inline functions are very good for saving time, but if you use them too often or with large functions you will have a tremendously large program. Sometimes large programs are actually less efficient, and therefore they will run more slowly than before. Inline functions are best for small functions that are called often.
Function Overloading :
Overloading refers to the use of the same thing for different purposes .
Function overloading is a feature of C++ that allows us to create multiple functions with the same name with different signature .
Signature consisting of name of the parameters , order of parameters , type of parameters
Ex :
void area(int); //circle
void area(int,int); //rectangle
void area(float ,int,int); //triangle
#include<conio.h>
#include<iostream.h>
void area(int);
long area(long,long);
void area(int,int,int);
void main()
{
int side;
long base,high,ans;
int length,breadth,height;
cout<<"enter side of a square"<<endl;
cin>>side;
area(side);
cout<<"enter base and height for triangle"<<endl;
cin>>base>>high;
ans=area(base,high);
cout<<"area of triangle is:"<<ans<<endl;
cout<<"enter length,breadth,height of a cube"<<endl;
cin>>length>>breadth>>height;
area(length,breadth,height);
}
void area(int x)
{
int y;
y=x*x;
cout<<"area of square is:"<<y<<endl;
}
long area(long a,long b)
{
return(0.5*a*b);
}
void area(int c,int d,int e)
{
cout<<"volume of cube is"<<c*d*e<<endl;
}
Function Overloading :
Overloading refers to the use of the same thing for different purposes .
Function overloading is a feature of C++ that allows us to create multiple functions with the same name with different signature .
Signature consisting of name of the parameters , order of parameters , type of parameters
Ex :
void area(int); //circle
void area(int,int); //rectangle
void area(float ,int,int); //triangle
#include<conio.h>
#include<iostream.h>
void area(int);
long area(long,long);
void area(int,int,int);
void main()
{
int side;
longbase,high,ans;
intlength,breadth,height;
cout<<"enter side of a square"<<endl;
cin>>side;
area(side);
cout<<"enter base and height for triangle"<<endl;
cin>>base>>high;
ans=area(base,high);
cout<<"area of triangle is:"<<ans<<endl;
cout<<"enter length,breadth,height of a cube"<<endl;
cin>>length>>breadth>>height;
area(length,breadth,height);
}
void area(int x)
{
int y;
y=x*x;
cout<<"area of square is:"<<y<<endl;
}
long area(long a,long b)
{
return(0.5*a*b);
}
void area(int c,intd,int e)
{
cout<<"volume of cube is"<<c*d*e<<endl;
}
Basic concepts of object oriented programming :
·
Classes
· Objects
· Data Abstraction and encapsulation
· Inheritance
· Polymorphism
· Dynamic Binding
· Message Passing
Class:
The most important feature of the C++ is the class .The class is the extension of the idea of structure used in C . Class is user-defined data type in C++
“ A class is a way to bind the data and its associated functions together”
(or)
A class is an organization of data and functions which operate on them
A class specifications has two parts
1)class declaration
2)class function definition
Class declaration describes the type and type and scope of its members. class function definitions describe how the class functions are implemented .
Syntax:
classclass-name
{
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};
The class declaration is similar to the structure declaration
In the above syntax he keyword class followed by the class-name .class-name is given by the user. The body of the class enclosed in with in braces and terminated by semicolon . The class body contain declaration of a variables and functions .thesefunctions and variables collectively called class members .
The keywords private and public are known as visibility labels .
The variables declared inside the class are known as data members and the functions are known as member functions .
Class function definition means define the functions of the class .
Note:The only Difference between structure and class is by default members of the class are private and by default members of the structure are public
Defining a member functions:
Member functions defined in two places
· Outside the class definition
· Inside the class definition
Outside the class definition
Member functions that are declared inside a class have to be defined separately outside the class . Their definition are very much like the normal function definition . An important difference between a member function and a normal function is that a member function identity incorporates membership ‘identity label’ in the header . This ‘label’ tells the compiler which class the function belongs to .
Syntax:
Return-type class-name :: Function-name(argument declaration)
{
function body;
function body;
}
The membership label class-name :: tells the compiler that function-name belongs to the class-name . And the scope of the function is restricted to the class-name specified in the headerline
Write a program which is illustrating class
#include<iostream.h>
#include<conio.h>
class item
{
private:
int number;
float cost;
public:
voidgetdata(int a,float b);
voidputdata();
};
void item::getdata(int a,float b)
{
number=a;
cost=b;
}
void item::putdata()
{
cout<<"item number is:"<<number<<endl;
cout<<"item cost is:"<<cost<<endl;
}
main()
{
itemi;
i.getdata(100,23.50);
i.putdata();
}
Member function characteristics :
· Several different classes can use the same function name . The ‘membership label’ will resolve their scope
· Member functions can access the private data of the class , A non-member function cannot do so .
· A member function can call another member function directly .with out using dot operator
Inside the class definition:
Another method of defining a member function is to replace the function declaration by the actual function definition inside the class .When a function is defined inside a class it is treated as an inline an inline function .
#include<iostream.h>
#include<conio.h>
class item
{
intcost,code;
//void read(void);
public:
voidgetdata(int a,int b);
voidputdata()
{
cout<<"cost:"<<cost<<endl;
cout<<"code:"<<code;
}
};
void item::getdata(int a,int b)
{
cost=a;
code=b;
}
main()
{
item i1;
clrscr();
i1.getdata(20,300);
i1.putdata();
getch();
}
Making out side of the inline
Just paste this sample code
inlinevoid item::getdata(int a,int b){
number=a;cost=b;}
Object:
The class variable is known as an object (or) Every Real world entity is known as an object like book , pen etc ..
Declaration of object is similar to the declaration of variable with data type , You can declare more than one object for particular class.
class_name variable name;
item x ,y ,z;
you can declare objects like this also
class item
{
…….
…….
…….
…….
}x,y,z;
Access specifiers(or) visibility Labels:
Access specifiers defines the access rights for the statements or functions that follows it until another access specifier or till the end of a class. The three types of access specifiers are "private", "public", "protected".
private:
The members declared as "private" can be accessed only within the same class and not from outside the class. The use of keyword private is optional . By default the members of a class are private .
public:
The members declared as "public" are accessible within the class as well as from outside the class.
protected:
The members declared as "protected" cannot be accessed from outside the class, but can be accessed from a derived class. This is used when inheritance is applied to the members of a class.
#include<iostream.h>
#include<conio.h>
class sample
{
private:
int cost;
void read();
public:
void update();
void write();
};
void sample::read()
{
cout<<"enter cost of the item"<<endl;
cin>>cost;
}
void sample::update()
{
read();
}
void sample::write()
{
cout<<"cost of the item is:"<<cost;
}
main()
{
sample s1;
clrscr();
s1.update();
s1.write();
getch();
}
#include<iostream.h>
#include<conio.h>
class sample
{
private:
int cost;
void read();
public:
void update();
void write();
};
void sample::read()
{
cout<<"enter cost of the item"<<endl;
cin>>cost;
}
void sample::update()
{
read();
}
void sample::write()
{
cout<<"cost of the item is:"<<cost;
}
main()
{
sample s1;
clrscr();
s1.update();
s1.write();
getch();
}
Write a program which is illustrating nested functions (or) accessing a private member function
a private member function can only be called by another function that is a member of its class .
Even an object cannot invoke a private function using the dot operator ,
#include<iostream.h>
#include<conio.h>
class sample
{
private:
int cost;
void read();
public:
void update();
void write();
};
void sample::read()
{
cout<<"enter cost of the item"<<endl;
cin>>cost;
}
void sample::update()
{
read();
}
void sample::write()
{
cout<<"cost of the item is:"<<cost;
}
main()
{
sample s1;
clrscr();
s1.update();
s1.write();
getch();
}
Static data members :
We can define class members static using static keyword . static variables are normally used to maintain values common to the entire class .
A Static member variable has certain special characteristics these are :
· All static data is initialized to zero when the first object is created, if no other initialization is present.
· When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member available
· It is visible only with in the the class ,its life time is the entire the program
· We can't put it in the class definition but it can be initialized outside the class
Static member functions :
Like static member variable , we can also have static member functions
A Static member functions has certain special characteristics these are :
a static function can have access to only other static members (functions or variables) declared in the same class
a static member function can be called using the class name instead of its objects
syntax
class-name :: function-name;
write a program which is illustrating static keyword
#include<conio.h>
#include<iostream.h>
class test
{
int code;
static int count;
public:
void setcode()
{
code=++count;
}
void getcode()
{
cout<<"the object number is :"<<code<<endl;
}
static void showcount()
{
cout<<"count :"<<count;
}
}
int test::count=3;
void main()
{
int i;
clrscr();
test::showcount();
cout<<"\n";
test t1;
t1.setcode();
test t2;
t2.setcode();
test t3;
t3.setcode();
t1.getcode();
t2.getcode();
t3.getcode();
test::showcount();
getch();
}
Friend functions:
Private members of the class cannot be accessed from outside of the class . That is , a non member functions cannot have access the private data of a class . using friend functions we can access the private data of the class (or)
“ friend functions are special functions which can access the private members of a class”
(or)
“the functions that are declare with keyword friend are Known as friend functions”
Friend functions have the following properties:
-A function should preceded with keyword friend
-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. Even though the prototypes for friend functions appear in the class definition, friends are not member functions
-Friend Function definition does not use the keyword friend or or the scope resolution operator(::)
· -Friend function not in the scope of the class that’s why it cannot called with object .
--Friend Function , can be friend of more than one class
· - Friend Function can be declared anywhere (in public, protected or private section) in the class.
Write a program which is illustrating friend functions:
#include<iostream.h>
#include<conio.h>
class sample
{
private:
int a,b;
public:
void getval();
friend float average(sample);
};
void sample::getval()
{
cout<<"enter values for sum"<<endl;
cin>>a>>b;
}
float average(sample s)
{
return (s.a+s.b)/2.0;
}
int main()
{
sample s;
clrscr();
s.getval();
cout<<"the avreage is:"<<average(s)<<endl;
return 0;
getch();
}
We can also declare all the member functions of one class as the friend functions of the another class .in such cases , the class is called a friend class .
Class Z
{
……..
……..
friend class X;
}
Constant Member Functions:
If a member function does not alter any data in the class . then we may declare it as a constant member function .
Ex:
Void mul( int , int) const;
Double Get_balance() const;
The qualifier const is appended to the function declaration and function definition .
Constructors:
a constructor is a special member function whose task is to intialize the object of its class . It has same name as that of class . The constructor is invoked automatically when the object of that class is created . It is called constructor because it construct the values of data member of the class
Characteristics of a constructor:
· constructor will have exact same name as the class
· constructor does not have any return type at all, not even void.
· Constructor should be declared in public section
· Constructors can be very useful for setting initial values for certain member variables.
In C++ we are having three types of constructors:
1)Default Constructors
2)Parameterized constructors
3)copy constructors
1.Default Constructors:
A constructor that accepts no parameters is called default constructor . the default constructor for class A is A::A().
#include<iostream.h>#include<conio.h>
class integer
{
private:
int a,b;
public:
integer();
void display();
};
integer::integer()
{
a=b=0;
}
void integer::display()
{
cout<<"val of a is"<<a<<endl<<"val of b is"<<b<<endl;
}
int main()
{
clrscr();
integer i1;
i1.display();
return 0;
}
2 .Parameterized constructors:
When objects are created the constructor that take arguments are called parameterized constructors (or) The constructor that can take arguments are called parameterized constructors
This helps you to assign initial value to an object at the time of its creation
When ever we use parameterized constructor in our programming we can call the constructor in two ways
1)explicit calling(integer i2=integer(20))
2)implicit calling(integer i3(30,40)
#include<iostream.h>#include<conio.h>
class integer
{
private:
int a,b;
public:
integer(int);
integer(int,int);
void display();
};
integer::integer(int x)
{
a=b=x;
}
integer::integer(int x,int y)
{
a=x;
b=y;
}
void integer::display()
{
cout<<"val of a is"<<a<<endl<<"val of b is"<<b<<endl;
}
int main()
{
clrscr();
integer i2=integer(20);
i2.display();
integer i3(30,40);
i3.display();
return 0;
}
3 .copy constructors:
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously.
The copy constructor is used to:
· Initialize one object from another of the same type.
· Copy an object to pass it as an argument to a function.
#include<iostream.h>#include<conio.h>
class integer
{
private:
int a,b;
public:
integer();
integer(int);
integer(integer &);
void display();
};
integer::integer()
{
a=b=0;
}
integer::integer(int x)
{
a=b=x;
}
integer::integer( integer &y)
{
cout<<"i am from copy constructor"<<endl;
a=y.a;
b=y.b;
}
void integer::display()
{
cout<<"val of a is"<<a<<endl<<"val of b is"<<b<<endl;
}
int main()
{
clrscr();
integer i1;
i1.display();
integer i2=integer(20);
i2.display();
integer i3(i2);
i3.display();
return 0;
}
Constructor overloading :
Overloading a constructor is very similar to function overloading. Just change the signature (no. of args and type of args) of the constructor.
#include<iostream.h>
#include<conio.h>
class integer
{
private:
int a,b;
public:
integer();
integer(int);
integer(int,int);
void display();
};
integer::integer()
{
a=b=0;
}
integer::integer(int x)
{
a=b=x;
}
integer::integer(int x,int y)
{
a=x;
b=y;
}
void integer::display()
{
cout<<"val of a is"<<a<<endl<<"val of b is"<<b<<endl;
}
int main()
{
clrscr();
integer i1;
i1.display();
integer i2=integer(20);
i2.display();
integer i4(30,40);
i4.display();
return 0;
}
Use of Constructor in C++ :Suppose you are working on 100's of objects and the default value of a data member is 0. Initializing all objects manually will be very tedious. Instead, you can define a constructor which initializes that data member to 0. Then all you have to do is define object and constructor will initialize object automatically. These types of situation arises frequently while handling array of objects. Also, if you want to execute some codes immediately after object is created, you can place that code inside the body of constructor.
Destructors:
Destructor is used to destroy the objects that have been created by a constructor .
Like constructor , The destructor is a member function whose name is the same as the class name but is preceded by a tilde operator . destructor never takes any arguments and does not return any value . It will be invoked implicitly by the compiler upon exit from the program or block or function . destructor releases the memory space for future use .
Ex: destructor for integer class shown below
~integer( ){ }
#include<iostream.h>
#include<conio.h>
int count=0;
class alpha
{
public:
alpha()
{
count++;
cout<<"the no of object created"<<count<<endl;
}
~alpha()
{
cout<<"the no of object destroyed"<<count<<endl;
count--;
}
};
main()
{
clrscr();
alpha a1,a2,a3,a4;
{
cout<<"enter into block1"<<endl;
alpha a5;
}
{
cout<<"enter into block2"<<endl;
alpha a6;
}
cout<<"i am the last line of the program"<<endl;
}
#include<iostream.h>
#include<conio.h>
int count=0;
class alpha
{
public:
alpha()
{
count++;
cout<<"the no of object created"<<count<<endl;
}
~alpha()
{
cout<<"the no of object destroyed"<<count<<endl;
count--;
}
};
main()
{
clrscr();
alpha a1,a2,a3,a4;
{
cout<<"enter into block1"<<endl;
alpha a5;
}
{
cout<<"enter into block2"<<endl;
alpha a6;
}
cout<<"i am the last line of the program"<<endl;
}
OUTPUT :
the no of object created 1
the no of object created 2
the no of object created 3
the no of object created 4
enter into block1
the no of object created 5
the no of object destroyed 5
enter into block-2
i am the last line of the program
the no of object destroyed 4
the no of object destroyed 3
the no of object destroyed 2
the no of object destroyed 1
Opertator overloading:
C++ has the ability to providing the operators with special meaning for a data type . the mechanism of giving special meaning to an operator is known as operator overloading .
We can overload all C++ Operators except (. (or).*,::, sizoof , ?:)
When an operator is overloaded its original meaning is not lost . For example The operator + ,which has been overloaded to add two vectors ,can still be used to add two integers .
Syntax:
Return type classname :: operator op(arglist)
{
Function body;
}
Where Return type is the type of value returned by the specified operation . op is the operator being overloaded . The op preceded by the keyword operator . operator op is the function name.
Operator functions must be either member function or friend function . the basic difference is that a friend function can take one argument for unary operators and two for binary operators.
And member function has no arguments for unary operators and one argument for binary.
Operator overloading using member functions
#include<iostream.h>
#include<conio.h>
class complex
{
float x,y;
public:
complex(){ }
complex(float real , float img){x=real;y=img;}
complex operator+(complex);
void display();
};
complex complex::operator +(complex c)
{
complex temp;
temp.x=x+c.x;
temp.y=y+c.y;
return(temp);
}
void complex::display()
{
cout<<x<<"+i"<<y<<endl;
}
int main()
{
clrscr();
complex c1,c2,c3;
c1=complex(1.6,2.3);
c2=complex(2.4,1.7);
c3=c1+c2;//c3=c1.operator(c2);
cout<<"c1:";c1.display();
cout<<"c2:";c2.display();
cout<<"c3:";c3.display();
return 0;
}
OUTPUT :
c1:1.6+i2.3
c2:2.4+i1.7
c3:4+i4
Operator overloading using friend function
#include<iostream.h>
#include<conio.h>
class complex
{
float x,y;
public:
complex(){}
complex(float real,float img){x=real;y=img;}
friend complex operator+(complex,complex);
void display();
};
complex operator+(complex c,complex c4)
{
return complex((c.x+c4.x),(c.y+c4.y));
}
void complex::display()
{
cout<<x<<"+i"<<y<<endl;
}
int main()
{
clrscr();
complex c1,c2,c3;
c1=complex(1.6,2.3);
c2=complex(2.4,1.7);
c3=operator+(c1,c2);
//c3=c1.operator+(c2);
cout<<"c1:";c1.display();
cout<<"c2:";c2.display();
cout<<"c3:";c3.display();
return 0;
}
OUTPUT :
c1:1.6+i2.3
c2:2.4+i1.7
For C++ Lab Programs Click here
Thanks for visiting this blog. How is the content?. Your comment is great gift to my work. Cheers.
I am totally agree with the post.So better be make use of this technology C++ Language training in Abu Dhabi
ReplyDeleteC++ Language course in Abu Dhabi
C++ Language classes in Abu Dhabi
C++ Programming in Abu Dhabi
Nice Post....It will be helpful for beginner Student.Here is a blog for C++ Programming.
ReplyDeleteGood job! For Sharing your best ideas... I will refer the people to best learning and training Institute for online courses... click the below link:
ReplyDeleteshort courses in pakistan
react native advanced concepts
sorting algorithms c++
graphic designing institute
mern stack course online
php training institute
e commerce online course in pakistan
Tech Inn Solutions
Good Job! You have Shared your well knowledge... I will refer the people to the best IT Solutions providers click the below link:
ReplyDeleteit solutions website
pakistan web developer
app development in pakistan
software developers in pakistan
digital marketing in pakistan
website maintenance packages
professional it consulting services
cre8tivebot
Most sites add the images to make sharing the content more social media friendly but an전주출장샵y of the other platforms should be good for writing.
ReplyDelete