C++ Data Types and Variable Management
C++ Data Types and Variable Management
int roll;
roll = 5; Or int roll = 5;
char p;
p = ‘y’; Or p = ‘#’; Or p = ‘9’; Or p = ’-‘;
Or char p = ‘y’;
float n;
n = 100.75; Or float n = 100.75;
double z;
z = 175.32; Or double z = 175.32;
char name[10] ;
name = ”raj”; …. invalid
strcpy (name, “raj”); …. valid
Literals
Integer literals
9, 52, +93, -51, 0, 100, -145
Float / double literals
+75.8, 0.75, -45.9, +0.3, -49.33, 0.01
Character literals
‘x’, ‘p’, ‘9’, ‘.’, ’#’, ‘z’, ‘m’, ‘, ‘
String literals
“Rajesh”, “945”, “A-43”, “945.75”, “A-95, Raja garden”
Constants
(1) int val = 100;
val = 500; …. valid
(2) const int val =100;
val = 500; …. invalid
Range 0 to 4294967295
Comments
1. Single line comment (//)
2. Multi line comment (/* ----------------
--------------
---------------- */)
Example:
int x =10; // an integer variable
float p = 500.2; // a float variable
Example:
/*We are declaring
some variables of
different types */
int x = 10 ;
float p = 200.75;
ASCII Values
American Standard Codes for Information Interchange
‘A’ to ‘Z’ …. 65 to 90
‘a’ to ‘z’ …. 97 to 122
‘0’ to ‘9’ …. 48 to 57
Type Conversion
int a = 48.5;
cout <<a; …. 48
float p = 98;
cout <<p; …. 98.0
char n= 65;
cout << n; …. A
int z = ’a’;
cout<<z; …. 97
Operators in c++
(1) Arithmetic operators
(2) Relational operators
(3) Logical operators
(4) Increment \ decrement operators
(5) Conditionals operators
(6) Sizeof operators
(7) C++ short hands
Arithmetic operators
+ , - , * , /, ( %) Only for integers
5/2 …. 2
5.0 / 2 …. 2.5
5%2 …. 1
11 % 3 …. 2
11.0 % 3 …. invalid (error)
Relational operators
< , > , < =, >=, !=, = =
int a =5, b=71, c=93;
a>5 …. False
b <=78 …. True
a==b …. False
a!=b …. True
c >= 93 …. True
= …. Assignment operator
== …. Relational operator
a = 5; …. Assignment
a = = 5; …. comparison
a = b = c = 10; …. Assignment
Logical Operators
&& …. AND
|| …. OR
! …. NOT
int a = 5, b =71, c = 93;
(a > 5 && b <= 78) …. false
(a > 5 || b<= 78) …. true
a>5 …. false
!(a > 5) …. true
Truth Table
A B A AND B A OR B NOT A NOT B
False False False False True True
False True False True True False
True False False True False True
True True True True False False
int a = 5, b= 7, c;
Sizeof operator
int x = 10;
float y = 23.75;
char n = ‘z’;
cout << sizeof (int); …. 2
cout << sizeof (float); …. 4
cout << sizeof (y); …. 4
cout << sizeof (n); …. 1
C++ Shorthand
a=a+5 is same as a+=5
a=a-3 is same as a - =3
a=a/7 is same as a/=7
a=a*5 is same as a*=5
a=a%4 is same as a%=4
# include <iostream.h>
# include <conio.h>
vaid main( )
{
int roll = 5;
char name [10] = “ amit “;
float marks =78;
clrscr () ;
cout<<”my roll number is:”<<roll;
cout << “ my name is “ << name;
cout << “ my marks are : “<< marks;
}
Using cin Object
cin is an object of istream class.
int roll;
char name[10];
float marks;
cout << “Enter roll no, name and marks”;
cin>>roll;
cin>>name;
cin>>marks;
Or
cin>>roll>>name>>marks;
Example:
# include<iostream.h>
#include<conio.h>
void main()
{
int roll;
char name[10];
float marks;
clrscr();
cout<< “Enter roll no, name and marks:”;
cin>>roll>>name>>marks;
cout<<”My roll no is :”<<roll;
cout<<”My name is :”<<name;
cout<<”My marks are:”<<marks;
}
o if else statement
Example 1:
int x = 10;
if(x > 10)
cout<<”Raj”;
cout<<”Vivek”;
Example 2:
if ( x > 10)
{
cout<<”Raj”;
cout<<”Vivek”;
}
Example 3:
void main( )
{
int marks;
cout<<”Enter marks:”;
cin>>marks;
if (marks > = 33 )
cout<<”passed”;
else
cout<<”failed”;
}
Example 4:
void main( )
{
int x;
clrscr( );
cout<<”Enter the number”;
cin>>x;
if ( x > = 45)
{
cout<<”Rishi”;
cout<<”Amit”;
}
else
{
cout<<”Rishabh”;
cout<<”Vishal”;
}
}
o Compound if Statement
Example:
void main( )
{
int x, y;
cout<< “enter two numbers:”;
cin>>x>>y;
if( x <= 100 && y ! = 55)
cout<<”Raj”;
else
cout<<”Amit”;
}
o Nested if statement
Example:
void main( )
{
int x, y, z;
cout <<Enter three numbers”;
cin>>x>>y>>z;
if(x > 50 )
{
if ( y != 40)
cout <<”Rajesh”;
else
cout<<”Amit”;
}
else
{
if ( z > = 48 )
cout<<”Amrita”;
else
cout<<”Vishruta”;
}
}
o Multiple ifs
Example:
void main( )
{
int d;
clrscr( );
cout<<”Enter a number between 1 and 7:”;
cin>>d;
if ( d = = 1)
cout<<”Sunday”;
else if (d= =2 )
cout<<”Monday”;
else if (d= =3 )
cout<<”Tuesday”;
else if (d= = 4 )
cout<<”Wednesday”;
else if (d= = 5 )
cout<<”Thursday”;
else if (d= = 6 )
cout<<”Friday”;
else if (d= = 7 )
cout<<”Saturday”;
else
cout<<”Invalid Choice”;
}
Example 2:
void main()
{
char x;
clrscr();
cout<<”Enter a character”;
cin>>x;
switch(x)
{
case ‘#’: cout<<”it is hash”;
break;
case ‘/’ : cout<<”it is slash”;
break;
case ‘+’: cout<<”it is plus”;
break;
case ‘-’: cout<<”it is minus”;
break;
}
}
- Switch statement can be used only for test of equality, not for range.
- You can not compare two variables using switch, switch label must be a constant.
- Only integer and character variables can be used in switch. You can not use float/
double variables in switch.
- Always put a break statement after the last case statement in a switch.
o Loops
1. for loop
2. while loop
3. do while loop
o for loop
Syntax:
for (initialization; condition; increment / decrement)
{
statements;
}
Example:
void main()
{
int x;
for( x=1;x < = 10; x++)
cout<<”raj”;
}
Example:
for( x=10; x> =1; x - -)
{
cout<<”Raj”;
cout<<”Vicky”;
}
Example:
for (x =1; x< =15; x += 2)
cout<<”Vicky”;
Example:
int x=1;
for( ; x< =10; x++)
{
cout<<”Vicky”;
}
Example:
int x=1;
for( ;x< =10;)
{
cout<<”Raj”;
x++;
}
Example:
int x;
for(x =1 ; ; x++)
{
cout<<”Raj”;
}
Example:
int x, y;
for( x = 1,y = 10; x< = 10; x++, y--)
cout<<”Vicky”;
o while loop
Syntax:
while (condition)
{
statements;
}
Example:
int x= 1;
while (x <= 10 )
{
cout<<”Raj”;
x++;
}
Example:
int x = 10;
while (x >= 1 )
{
cout<<”Raj”;
x- -;
}
o do while loop
Syntax:
do
{
statatemets;
}while (condition);
Example:
int x=1;
do
{
cout<<”Raj”;
x++;
}while(x < = 10);
Example:
int x= 10;
do
{
cout<<”Raj”;
x - -;
}while( x >= 1);
o int x = 15;
while(x <= 10)
{
cout<<”Raj”;
x++;
}
o int x=15;
do
{
cout<<”Raj”;
x++;
}while(x < =10);
Nested loops
Example:
for(x=1;x < = 5; x++)
{
for(y=1;y < = 3; y++)
cout<<”Amit”;
}
Example:
int x, y;
x=1;
while ( x<=5)
{
y=1;
while(y < = 3)
{
cout<<”Amit”
y++;
}
x++;
}
Jump statement
1. goto
2. break
3. continue
o goto statement
Example:
void main( )
{
int x;
clrscr( );
xyz: …. label
cout<<”raj“;
cout<<”vicky“;
cout<<”enter a number”;
cin>>x;
if(x>=10)
goto xyz;
cout<<”vishwas “;
cout<<”harpreet “;
cout<<”ritesh “;
}
o break
Example:
void main( )
{
int x;
clrscr( );
for(x=1; x<=10; x++)
{
if(x = = 7)
break;
cout<<” raj “;
}
cout<<” vivek “;
}
o continue
Example:
void main( )
{
int x;
for( x=1; x<=10; x++)
{
if( x = =7)
continue;
cout<<” raj “;
}
cout<<” vivek “;
}
The exit( ) function
Example:
void main( )
{
int x;
clrscr( );
for( x=1; x<=10; x++)
{
if( x = =7)
exit( 0 );
cout<<”raj”;
}
cout<<” vivek “;
}
Example :
char x;
cout<<” enter a character “;
cin>>x;
Or x = getchar( );
Or x = getch( );
Or x = getche( );
Or [Link]( x );
cout<<x;
Or putchar( x );
Or putch(x);
Or [Link](x);
String i/o functions
Input Output Header File
gets( ) puts( ) …. stdio.h
[Link]( ) [Link]( ) …. iostream.h
Example:
char x[20];
cout<<” enter your name “;
cin>>x; …. Rajesh kapoor
cout<<x; …. Rajesh
cout<<x;
Or puts(x);
Or [Link](x, 20); …. Rajesh kapoor
o strcpy( )
Syntax:
Strcpy( targetstring, sourcestring);
Example:
char a[10];
char b[20];
char c[10] = “amit”; …. valid
a = “Rajeev”; …. Invalid
strcpy(a, “Rajeev”); …. valid
cout<<a; …. Rajeev
strcpy(b, a);
cout<<b; …. Rajeev
o strlen( )
Example:
int x;
char a[10] = "rajeev";
x = strlen(a);
cout<<x; .... 6
cout<<strlen(a); .... 6
cout<<strlen("Raj"); .... 3
o strcat( )
Example:
char a[20] = "vishal";
char b[10] = "arora";
strcat(a, b);
cout<<a; .... vishalarora
Example:
char a[20] = "vishal";
strcat ( a, "arora");
cout<<a; .... vishalarora
o strcmp( )
Example:
char a[20] = "abhijeet";
char b[20] = "abhijit";
if( strcmp (a, b) = = 0)
cout<<"strings are equal";
else
cout<<" strings are not equal";
o strrev( )
Example:
char a[10] = "vishal";
strrev (a);
cout<<a; …. lahsiv
Arrays
1. One dimensional Arrays
2. Two Dimensional Arrays
int x[5];
x[0] = 11;
x[1] = 13;
x[2] = 45;
x[3] = 13;
x[4] = 48;
11 13 45 13 48
0 1 2 3 4
int x[5] = {2, 5, 7, 9, 13};
int x[ ] = {2, 5, 7, 3};
int x[5] = {2, 1,7};
int x[ ]; …. invalid
char x[10] = "Rajeev";
char x[ ] = "Rajeev";
char x[10] = {'R', 'a', 'j', 'e', 'e', 'v',’\0’};
int x[10];
int i;
cout<<"enter 10 values";
for(i=0; i<=9; i++)
cin>>x[i];
char x[10];
cout<<"enter your name";
cin>>x;
cout<<x;
o Arrays of Strings
char a[5][20];
int i;
cout<<"enter 5 strings : ";
for(i=0; i<=4; i++)
[Link](a[i], 20)
Functions
Example:
void main( )
{
void display( ); .... declaration / prototype
cout<<"raj";
cout<<"amit";
display( ); .... calling
cout<<" vivek ";
cout<<" mohan ";
display( ); .... calling
cout<<" vishal ";
}
o Call by value
Example:
void main( )
{
int add ( int, int ); …. Declaration / Prototype
int x=10, y=20;
int z; Actual Parameters
clrscr( );
z = add(x, y); …. calling
cout<<" sum is"<<z;
z = add(x, 100); …. Calling
cout<<" sum is "<<z;
z = add (x); .... invalid
z = add(x, 2, 10); .... invalid
}
Example:
void main( )
{
void add(int, int); …. Declaration / prototype
int x, y;
cout<<"enter two numbers ";
cin>>x>>y;
add(x, y); …. calling
add(2, 5); …. calling
add(7, y, 8); ..... invalid
add(2); ..... invalid
}
Return statement
The return statement has two meanings
1. Returning control
2. Returning value
Default arguments
void main( )
{
int add( int x =100, int y = 200);
int a = 10, b = 20;
int c;
c = add(a, b);
cout<<" sum is"<<c; .... 30
c = add(a);
cout<<" sum is"<<c; .... 210
c = add( );
cout<<" sum is"<<c; .... 300
c = add( a, b, 10); .... invalid
}
Call by Reference
Example:
void main( )
{
void change(int );
int x = 10;
clrscr( );
cout<<x; …. 10
change(x); .... 100
cout<<x; .... 10
getch( );
}
void change (int n)
{
n = 100;
cout<<n;
return;
}
Example:
void main()
{
void change ( int &);
int x = 10;
clrscr( );
cout<<x; …. 10
change(x); …. 100
cout<<x; …. 100
getch();
}
void change(int &n)
{
n = 100;
cout<<n;
return;
}
Scope Rules : The scope for a function or a variable is determined by its place of
declaration. If a declaration occurs within a function then the variable / function declared
can be accessed inside the same function only and no where else. Such a function / variable
are called local variable / functions.
If there declarations appear outside all functions, they become available to all
functions in the file and their scope becomes file scope and they can be accessed from
anywhere in the file. Such variables / functions are called global variable / functions.
Auto: The storage specifier auto refers to automatic variable. A variable is declared
automatic as follows:
Register: A register declaration is an auto declaration. A register variable has all the
characteristics of an auto variable. The only difference between the two is that register
variables provide fast access as they are stored inside CPU registers rather than in
memory.
The register & auto can be applied only to local variables.
Extern: If a program is spread across files, then a global variable declared once
can’t be declared again for seprate files, rather you can put the global variables
declaration preceded by the keyword extern. The extern specifier tells the compiler that
the variable types & names that follow it have been declared elsewhere so that, fresh
memory is not allocated to these variables.
The lifetime of external varables is the life of the program.
Static: There can be static local and global variables. When a global variable is
declared static, it means that this variable is globally available for the very file it appears
in, from all other files of the program, it is hidden and hence cannot be accessed from
their . When static modifier applies to a local variable, it is initialized only when the very
first call to the function occurs & it is not destroyed when the function terminates.
Structures
Example: Tagname
struct student
{
int roll;
char name[20];
float marks;
};
void main( )
{
student o;
[Link] = 5;
strcpy ([Link], "Raj");
[Link] = 75;
student p = {7, "vivek", 78};
student m;
cout<<"Enter rollno, name and marks";
cin>>[Link]>>[Link]>>[Link];
cout<<[Link]<<[Link]<<[Link];
cout<<[Link]<<[Link]<<[Link];
cout<<[Link]<<[Link]<<[Link];
}
Example:
struct student
{
int roll;
char name[10];
float marks;
}o, p = {5, "Raj", 75}, q;
void main()
{
[Link]=5;
strcpy([Link], "Amit");
[Link] = 68;
cout<<[Link]<<[Link]<<[Link];
cout<<[Link]<<[Link]<<[Link];
}
Example:
struct
{
int roll;
char name[10];
float marks;
}o, p;
void main()
{
[Link] = 7;
strcpy([Link], "Vishwas");
[Link] = 78;
cout<<[Link]<<[Link]<<[Link];
}
o Structure Assignments
Example:
struct student
{
int roll;
char name[10];
float marks;
};
void main( )
{
student o, p;
[Link] = 5;
strcpy([Link], "Amit" );
[Link] = 75;
p = o; …. Valid
cout<<[Link]<<[Link]<<[Link];
}
Exmple:
struct one
{
int a;
};
struct two
{
int a;
};
void main( )
{
one o;
two p;
o.a = 5;
p = o; …. Invalid
p.a = o.a; …. valid
}
o Nested Structures
Example:
struct date
{
int dd, mm, yy;
};
struct employee
{
int ecode;
char ename[20];
float salary;
date doj;
};
void main( )
{
employee o = {123, "Ravi", 5000, {10, 8, 2005 } };
employee m;
cout<<"Enter employee code :";
cin>>[Link];
cout<<"Enter employee Name :";
cin>>[Link];
cout<<"Enter employee salary :";
cin>>[Link];
cout<<"Enter Date of joining :";
cout<<"Enter day";
cin>>[Link];
cout<<"Enter Month ";
cin>>[Link];
cout<<"Enter Year ";
cin>>[Link];
}
o Arrays of structures
Example:
struct student
{
int roll;
char name[10];
float marks;
};
void main( )
{
student x[5];
int i;
for(i=0; i<=4; i++)
{
cout<<"Enter Roll No :";
cin>>x[i].roll;
cout<<"Enter Name :";
cin>>x[i].name;
cout<<"Enter Marks :";
cin>>x[i].marks;
}
void main( )
{
xyz m;
cout<<"Enter five integers";
for(i=0; i<=4; i++)
cin>>m.a[i];
void main()
{
xyz add(xyz, xyz);
xyz o, p, q;
o.x = 5;
o.y = 7.5;
p.x = 9;
p.y = 3.8;
q = add(o, p);
cout<<q.x<<q.y;
}
o Typedefs
void main( )
{
typedef student stu;
student o; is same as stu o;
}
Example:
typedef struct student
{
int roll;
char name[10];
float marks;
}o, p;
void main()
{
student m; is same as o m; I s sane as p m;
Enums
Example:
enum weekday{sun, mon, tue, wed, thu, fri, sat};
day1 = mon;
day2 = fri;
int diff = day2 - day1;
cout<<diff; …. 4
Example:
enum boolean{false, true};
boolean check;
check = true;
Example:
enum boolean{false, true}check;
Example:
enum {false,true}check;
Example:
enum weekday{sun, mon, tue = 7, wed, thu = 15, fri, sat};
weekday day1, day2;
day1 = mon;
day2 = fri;
int x = day2 - day1;
cout<<x; …. 15
Classes
Example:
struct student
{
int roll;
char name[10];
float marks;
};
void main()
{
void input(student & );
void display (student );
student o, p;
input (o);
display(o);
input(p);
display(p);
}
void input (student &m)
{
cout<<”\n enter roll no., name & marks “;
cin>>[Link]>>[Link]>>[Link];
}
void display( student n )
{
cout<<[Link]<<[Link]<<[Link];
}
Syntax:
class <classname>
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
protected:
variable declarations;
function declarations;
};
Example:
class student
{
private:
int roll;
public:
char name[10];
protected:
float marks;
}o;
void main( )
{
[Link] = 5; …. invalid
strcpy ( [Link], “ raj “); …. valid
[Link] = 45; …. Invalid
}
Example:
class student
{
int roll;
char name[10];
float marks; …. Private by default
public:
void input ( )
{
cout<<”\n enter roll no. name & marks “;
cin>>roll>>name>>marks;
}
void display( )
{
cout<<roll<<name<<marks;
}
};
void main( )
{
student o, p;
[Link]( );
[Link]( );
[Link]( );
[Link]( );
}
void main( )
{
student o, p;
[Link]( );
[Link]( );
[Link]( );
[Link]( );
}
Example:
student : : input( )
student : : display( )
void main( )
{
employee m[5];
int i;
for( i =0; i<=4; i++)
{
m[i].input( );
m[i].disp( );
}
}
o Global class
class abc …. global class
{
public:
void disp( )
{
cout<<”trial message…..”;
}
};
void main( )
{
abc o; .... local object ( local to main) is valid
[Link]( ); …. valid
[Link]( ); …. valid
[Link]( ); …. invalid
}
void func1( )
{
abc n; …. local object (local to func1) is valid
[Link]( ); …. valid
[Link]( ); …. valid
[Link]( ); …. invalid
}
o Local class
void main ( )
{
class abc
{
public:
void disp( )
{
cout<<”trial message…..”;
}
};
abc m; …. invalid
void func1( )
{
abc n; …. invalid
}
Inline functions
Example:
void main( )
{
void square( int );
int x = 10;
clrscr( );
square(x);
square(3);
square(5);
}
Friend functions
1. Member functions: A member function can access any member (public,
private, protected) of the class without any object.
3. A friend function: A friend function can access any member (public, private,
protected) member of the class using an object.
Example:
class abc
{
int x, y;
public:
void input( );
void display( );
friend void calc(abc);
};
void calc(abc m)
{
cout<<m.x + m.y;
}
void main( )
{
abc o;
[Link]( );
[Link]( );
calc(o);
}
Example
class xyz;
class abc
{
int a, b;
public:
void input( )
{
cout<<”enter two numbers “;
cin>>a>>b;
}
void display( )
{
cout<<a<<b;
}
friend void calc(abc, xyz);
};
class xyz
{
int x, y;
public:
void get( )
{
cout<<”enter two numbers”;
cin>>x>>y;
}
void put( )
{
cout<<x<<y;
}
void main( )
{
abc p;
xyz q;
[Link]( );
[Link]( );
q,get( );
[Link]( );
calc(p, q);
}
Example:
int x;
int y;
class a
{
public:
int x;
void func(int i)
{
x = i; …. a::x = i;
::x = i; …. global x = i;
y = i; …. global y = i;
}
};
Nested classes
A class declared within another class is called nested class. The outer class is known
as enclosing class and the inner class is known as nested class.
Example:
Class outer
{
int a;
class inner
{
int b;
public :
int c;
void prn( )
{
cout<<b * c;
}
};
inner obl;
public:
inner ob2;
void second( )
{
cout<< ob2.c * ob 1.c;
cout<< a * a;
}
};
void main( )
{
outer x; …. valid
inner y; …. invalid
outer : :inner y; …. valid
}
Example:
class outer
{
int a;
class inner
{
int b;
public:
int c;
void prn( );
};
inner ob1;
public:
inner ob2;
void second( )
{
cout << a * a;
}
};
void main( )
{
abc o, p;
[Link]( );
[Link]( ); …. 10 20.7
[Link]( ); …. Garbage
}
Default Constructor
Example:
class abc
{
int x;
float y;
public:
abc( ) …. Default constructor
{
x = 10;
y = 20.7;
}
void display( )
{
cout<<x<<y;
}
};
void main( )
{
abc o, p, q;
[Link]( ); …. 10 20.7
[Link]( ); …. 10 20.7
[Link]( ); …. 10 20.7
}
Parameterized Constructor
Example:
class abc
{
int x;
float y;
public:
abc(int n , float m) …. Parameterized Constructor
{
x = n;
y = m;
}
void display( )
{
cout<<x<<y;
}
};
void main( )
{
abc o(2, 7.5), p(3, 9.8) , q(8 , 3.3);
[Link]( ); …. 2 7.5
[Link]( ); …. 3 9.8
[Link]( ); …. 8 3.3
abc z; ….. invalid
}
void main( )
{
abc o(2, 5.7) .... valid
abc p(5); .... valid
abc q; …. valid
[Link]( ); …. 2 5.7
[Link]( ); …. 5 20.7
[Link]( ); …. 10 20.7
}
Copy constructor
Example:
class abc
{
int i;
float j;
public:
abc(int x, float y) …. Parameterized Constructor
{
i = x;
j = y;
}
void display( )
{
cout<<i<<j;
}
abc(abc &m) …. Copy Constructor
{
i = m.i;
j = m.j;
}
};
void main( )
{
abc o(2, 7.5); .... parameterized constructor called
abc p = o; …. copy constructor called
Or
abc p(o); …. copy constructor called
}
Destructors
Example:
class abc
{
int x;
float y;
public:
void display( )
{
cout<<x<<y;
}
abc(int n, float m) …. Parameterized Constructor
{
x = n;
y = m;
}
~ abc( ) …. Destructor
{
cout<<”destructor at work“;
}
};
void main( )
{
abc o(2, 5.5)
[Link]( );
}
o Function Overloading
Example:
#include<iostream.h>
#include<conio.h>
void calcinterest(long, int, float);
void calcinterest(long, int);
void calcinterest(long);
void calcinterest(long, float);
void main( )
{
clrscr( );
calcinterest(5000);
calcinterest(5000, 3);
calcinterest(7000, 0.09f);
calcinterest(8000, 4, 0.11f);
}
o Constructor Overloading
Example:
class deposit
{
long int principal;
int time;
float rate;
float amt;
public:
deposit( );
deposit( long p, int t, float r);
deposit( long p, int t );
deposit( long p, float r);
void calcamt( );
void display( );
};
deposit::deposit( )
{
principal = 0;
time = 0;
rate = 0;
amt = 0;
}
deposit::deposit(long p, float r)
{
principal = p;
time = 2;
rate = r;
amt = 0.0;
}
void deposit::calcamt( )
{
amt = principal + (principal * rate * time) / 100;
}
void deposit::display( )
{
cout<<” principal amount :“<<principal;
cout<<” time :”<<time;
cout<<” rate : ”<<rate;
cout<<” total amount : “ <<amt;
}
void main( )
{
deposit d1, d2(2000, 2, 0.07f), d3(4000, 1), d4(3000, 0.12f);
[Link]( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
}
Inheritance
o Different forms of Inheritance
1. Single inheritance:
2. Multiple inheritance
x y Base classes
z Derived classes
3. Hierarchical inheritance
Base Class
z
Sub classes
x y z
4. Multilevel inheritance
Base class of y
x
z Sub class of y
5. Hybrid inheritance
(a) x
y z
(b)
a b
d e
Single inheritance
Syntax:
Class <derived_class_name>:<visibility mode> <base_class_name>
{
.
.
.
};
Example:
class A class A
{ {
….. …...
….. …..
}; };
class A
{
…..
…..
};
class B : private A
{
…..
…..
};
Multiple inheritance
Syntax:
class <derived_class_name> : <visibility_ mode> base1,
<visibility_ mode> base2,
<visibility_ mode> base3
{
…..
…..
};
Example:
class C: public A, private B
{
…..
…..
};
Visibility Modes
o Public visibility mode
Class a Class b
Private Private
X, Get( );
A, Input( );
Protected Protected
Y, Put( ); B, Output( );
Public
Public
C, Display( );
Z, Take( );
class a
{
…..
};
class b: public a
{
…..
};
Private Private
A, Input( );
X, Get( );
Protected Protected
B, Output( );
Y, Put( );
Public
Public C, Display( );
Z, Take( );
class a
{
….
….
};
class b : private a
{
….
….
};
Protected Protected
B, Output( );
Y, Put( );
Public
Public
C, Display( );
Z, Take( );
class a
{
….
};
class b : protected a
{
….
};
Example:
class a
{
private:
void func1( )
{
cout<<”this is func1”;
}
protected:
void func2( )
{
cout<<”this is func2”;
}
C, Display( ); public:
Y, Put( ); );
B,Output( void func3( )
Z, Take( );
{
cout<<”this is func3”;
func1( );
}
};
class b : public a
{
private:
void func4( )
{
cout<<”this is func4”;
}
protected:
void func5( )
{
cout<<“this is func5”;
}
public:
void func6( )
{
cout<<”this is func6 “;
func2( );
func4( );
func5( );
}
};
void main( )
{
b m;
m.func3( );
m.func6( );
m.func5( ); …. invalid
m.func4( ); …. invalid
m.func2( ); …. invalid
m.func1( ); …. invalid
}
void main( )
{
xyz k(9, 7.7, 23)
[Link]( );
[Link]( );
}
Pointers
A pointer is a variable that holds a memory address, usually the location of another
variable in memory.
Example:
int a = 257; a
int *p;
p = &a; 257
Or 91 92
int *p = &a; p
cout<<a; …. 257
cout<<&a; …. 91 9 1
cout<<p; …. 91 101 102
cout<<&p; …. 101
cout<<*p; …. 257
Example:
float a = 253.73; a
float *p;
2 5 3 .7 3
p = &a;
Or float *p = &a; 91 92 93 94
cout<<a; …. 253.73 p
cout<<&a; …. 91 9 1
cout<<p; …. 91
cout<<&p; …. 101 101 102
cout<<*p; …. 253.73
Pointer to a pointer
Example:
int a = 257;
int *p = &a; a
int **n = &p; 2 5 7
cout<<a; …. 257 91 92
cout<<&a; …. 91 p
cout<<p; …. 91
cout<<&p; …. 101 9 1
cout<<*p; …. 257
cout<<n; …. 101 101 102
cout<<&n; …. 201
cout<<*n; …. 91 n
cout<<**n; …. 257 1 0 1
cout<<&(*n); …. 101
cout<<&(**n); …. 91 201 202
Pointer arithmetic
Only two arithmetic operations (addition and subtraction) may be performed
on pointers. When you add 1 to a pointer, you are actually adding the size of
whatever the pointer is pointing at.
Example:
a
int a = 105;
int *p = &a;
a++;
91 92 p
cout<<a; …. 106
cout<<*p; …. 106
cout<<p; …. 91
101 102
(*p)++
cout<<a; …. 107 10 5
cout<<*p; …. 107
cout<<p; …. 91 9 1
p++;
cout<<a; …. 107
cout<<*p; …. ?
cout<<p; …. 93
Example:
float a = 123.75;
float *p = &a;
a = a + 3;
cout<<a; …. 126.75 a
cout<<*p; …. 126.75
cout<<p; …. 91 123.75
91 92 93 94
(*p) = (*p) + 2; p
cout<<a; …. 128.75
cout<<*p; …. 128.75 9 1
cout<<p; …. 91 101 102
p++;
cout<<a; …. 128.75
cout<<*p; …. ?
cout<<p; …. 95
0 1 2 3 4
21 5 73 7 28
91 93 95 97 99
cout<<a[0]; …. 21
cout<<a[1]; …. 5
cout<<&a[0]; …. 91
cout<<&a[1]; …. 93
cout<<a; …. 91
C++ interprets an array name as the address of its first element. That is, if ‘a’ is an
int array to hold 5 integers then ‘a’ stores the address of a[0], the first element of the
array. So we can say that ‘a’ is same as &a[0].
Example:
int *p;
p = &a[0]; Or p = a;
cout<<a; …. 91
cout<<p; …. 91
cout<<*a; …. 21
cout<<*p; …. 21
cout<<a + 1; …. 93
cout<<p + 1; …. 93
cout<<*( a + 1 ); …. 5
cout<<*( p + 1 ); …. 5
cout<<a[0] …. 21
cout<<p[0]; …. 21
cout<<a[1]; …. 5
cout<<p[1]; …. 5
cout<<1 + a; …. 93
cout<<1 + p; …. 93
cout<<*( 1 + a ); …. 5
cout<<*( 1 + p ); …. 5
cout<<1[a]; …. 5
cout<<1[p]; …. 5
a++; …. Error
p++; …. valid
Arrays of pointers
Example:
int a[5] = {2, 5, 71, 83, 9};
int *p[5] = {&a[0], &a[1], &a[2], &a[3], &a[4]};
0 1 2 3 4
2 5 71 83 9
101 103 105 107 109
0 1 2 3 4
101 103 105 107 109
201 203 205 207 209
cout<<a[0]; …. 2
cout<<p[0]; …. 101
cout<<&a[0]; …. 101
cout<<&p[0]; …. 201
cout<<a; …. 101
cout<<p; …. 201
cout<<*a; …. 2
cout<<*p; …. 101
cout<<*p[0]; …. 2
cout<<*(p[1]+1); …. 71
cout<<*( *p ); …. 2
cout<<p + 1; …. 203
cout<<*( p + 1 ); …. 103
cout<<*p + 1; …. 103
cout<<*(*( p + 1 ) + 2 ); …. 83
cout<<*( p + 2 ) + 1; …. 107
cout<<**p + 1; …. 3
cout<<**( p + 1 ); …. 5
char *p = ”Rajeev”;
cout<<p; …. Rajeev
cout<<p + 2; …. jeev
cout<<*p; …. R
cout<<*( p + 2 ); …. j
Arrays of strings
Example:
char n[5] [10] = {“Rajeev”,
”Amit”,
”Priya”,
”Vicky”,
”Himanshu”};
cout<<n[0]; …. Rajeev
cout<<n[1]; …. Amit
cout<<n[2]; …. Priya
cout<<n[3]; …. Vicky
cout< <n[4]; …. Himanshu
a = n[0]; …. Invalid
n[0] = n[3]; …. invalid
n[3] = a; …. invalid
cout<<p[0]; …. Rajeev
cout<<p[1]; …. Amit
cout<<p[2]; … Priya
a = p[0];
p[0] = p[3];
p[3] = a;
void main( )
{
student m = {2, ”Ravi”, 75};
student *p;
p = &m;
cout<<[Link]<<[Link]<<[Link];
cout<< p - > roll<< p - > name<< p - > marks;
p - > roll = 9;
strcpy( p - > name, ”Ravi kapoor”);
cout<<[Link]; …. 9
cout<<[Link]; …. Ravi kapoor
cout<<p - > roll; …. 9
cout<<p - > name; …. Ravi kapoor
}
void main( )
{
student o;
student *p = &o;
[Link](2, ”Raj”);
[Link]( ); …. 2 Raj
p - > display(); …. 2 Raj
p - > input(5, ”Vicky”);
p - > display( ); …. 5 Vicky
[Link]( ); …. 5 Vicky
}
this Pointer
Example:
class student
{
int roll;
char name[10];
public:
void input( );
void display( );
};
void student::input( )
{
cout<<”enter rollno, name”;
cin>> this - > roll>> this - > name;
}
void student::display()
{
cout<<this - > roll;
cout<<this - > name;
}
void main( )
{
student o, p;
[Link]( );
[Link]( );
[Link]( );
[Link]( );
}
File Handling
Input Device R
Program
A
Output Device
M
Example:
void main( )
{
int roll;
char name[10];
float marks;
clrscr( );
cout<<"Enter roll no, name and marks";
cin>>roll>>name>>marks;
cout<<roll<<name<<marks;
getch( );
}
ifstream obj;
[Link] ("[Link]");
ofstream obj;
[Link] ("[Link]");
Closing a File
[Link]();
[Link]();
Note: To use an object of ifstream / ofstream / fstream class, fstream.h file must be
included in program. When you include fstream.h file then there is no need of using
iostream.h file.
Input Device
R Backend
Program File
A (Disk)
Output
Device
M
while( ! [Link]( ) )
{
obj>>roll>>name>>marks;
cout<<roll<<name<<marks;
}
[Link]( );
}
Reading and Writing in one program
Example:
void main( )
{
char ch;
int roll;
char name[10];
float marks;
ofstream obj ( " [Link] " );
if( ! obj )
{
cout<<"file opening error";
return;
}
do
{
cout<<"Enter roll no, name and marks";
cin>>roll>>name>>marks;
obj<<roll<<name<<marks;
cout<<"do you want to enter more records( y / n )";
cin>>ch;
}while(ch = = 'y');
[Link]();
ifstream fin;
[Link](" [Link] ");
if( ! fin )
{
cout<<"file opening error";
return;
}
while(  )
{
fin>>roll>>name>>marks;
cout<<roll<<name<<marks;
}
[Link]( );
}
File Opening Modes
ios::in
ios::out
ios::ate
ios::app
ios::trunk
ios::nocreate
ios::noreplace
ios::binary
fstream obj;
[Link]( "[Link]", ios::in | ios::app | ios::nocreate );
Writng and Reading with one object
Example:
#include<fstream.h>
#include<conio.h>
void main( )
{
int roll;
char name[10];
float marks;
char ch;
fstream obj("[Link]", ios::in | ios::app);
if( ! obj )
{
cout<<"file opening error";
return;
}
do
{
cout<<"Enter roll no, name and marks";
cin>>roll>>name>>marks;
obj<<roll<<name<<marks;
cout<<"Do you want to enter another record( y / n )";
cin>>ch;
}while(ch = = 'y');
[Link]( 0 );
while( ! [Link]( ))
{
obj>>roll>>name>>marks;
cout<<roll<<name<<marks;
}
[Link]( );
}
Example(Reading):
struct student
{
int roll;
char name[10];
float marks;
};
void main( )
{
student o;
fstream obj("[Link]", ios::in | ios::binary)
if( ! obj )
{
cout<<"File opening error";
return;
}
while( ! [Link]( ) )
{
[Link] ((char *) &o, sizeof (student));
cout<<[Link]<<[Link]<<[Link];
}
[Link]( );
}
To set and examine the put pointer the following function are used:
Example:
[Link]( 30 );
[Link]( 30 );
int x;
x = [Link]( ); cout<<x;
x = [Link]( ); cout<<x;
char x[30];
[Link] (x, 30); …. For input
Or [Link] (x, 30, '#'); …. For input
The difference between get( ) and getline( ) is that getline( ) reads and removes the
delimiter character from the input stream if it is encountered which is not done by the get(
) function.
Local objects are defined within a function and can only be accessed within that function. For instance, in 'void main() { abc o; }', 'o' is a local object . Global objects are defined outside all functions and are accessible from any function in the file. For example, 'abc m;' defined globally can be accessed anywhere . Member objects, part of a class, are used within the scope of the class or through class instances, like 'inner ob1' within the 'outer' class, accessible via the class functions or objects .
Constructors are special member functions in C++ that initialize objects of a class. They have the same name as the class and do not return a value. Types of constructors include default constructors, which set default values for object attributes (e.g., 'abc() { x = 10; y = 20.7; }'), parameterized constructors that accept arguments to set specific initial values (e.g., 'abc(int n, float m)'), and copy constructors used to create a new object as a copy of an existing object (e.g., 'abc(abc &m)'). Constructors automate the initialization process when an object is created .
In C++, the scope resolution operator (::) is used to define member functions outside their class. It specifies that the function belongs to a particular class, allowing the function implementation to be separated from its declaration. For example, for a class 'student' with a function 'input', the implementation would begin with 'void student::input()'. This operator helps in distinguishing between members of a class and other global definitions or nested class members .
In C++, visibility modes in inheritance control accessibility of base class properties in derived classes. Public inheritance retains public and protected access, private inheritance makes all base class members private in the derived class, while protected inheritance keeps them protected. For example, with 'class B : private A', members of A become private in B, restricting access even in derived classes of B. These modes are crucial for expressing and maintaining encapsulation relationships, ensuring that derived classes use only necessary parts of a base class, preserving class integrity .
File handling in C++ is essential for reading from and writing to files, supporting persistent data storage. Different file opening modes include ios::in (for reading), ios::out (for writing), ios::app (for appending at the file's end), ios::binary (for binary file processing), and others. These modes define how a file can be accessed or modified. For example, using 'ofstream obj('student.txt');' in ios::out mode opens a file to write data to it, while 'ifstream obj('student.dat');' in ios::in mode can be used to read from a file .
Friend functions in C++ are functions declared with the keyword 'friend' inside a class and are not member functions of the class. They can access private and protected class members directly, acting as a bridge between non-member functions and the encapsulated data of a class. For instance, in a class 'abc', the friend function 'void calc(abc m)' can access private members 'x' and 'y' directly, offering controlled access and enhancing modularity .
Inline functions in C++ are defined with the 'inline' keyword preceding their declaration. The compiler attempts to expand them in place to reduce the overhead of a function call, especially critical in small, frequently-used functions. By substituting the function definition wherever the function is called, inline functions decrease function call overhead, enhancing execution speed. However, excessive use can increase binary code size due to function code duplication .
Pointers provide significant flexibility and efficiency when working with objects in C++. They facilitate dynamic memory allocation, allowing objects to be created and managed at runtime on the heap, which is useful when the number of objects is uncertain. Pointers can also be used to reference and manipulate objects' data efficiently, especially in large-scale applications where passing objects by value would be costly. For instance, using 'student *p = &o', one can access and modify the object's data through '*p', avoiding the duplication involved in copying the object's data .
Nested classes in C++ are used to logically group classes that are used only in one place, improving encapsulation and maintaining better class organization. They allow the inner class to access private members of the outer class, thus aiding in closely associating the inner class with its enclosing class's data and behavior. This association streamlines management of software components, reducing namespace pollution as inner classes are hidden from outside scope and are only accessible through their enclosing class .
Multiple inheritance in C++ allows a class to inherit from more than one base class, defined with syntax like 'class C: public A, private B'. It provides a way to combine functionalities from different classes. However, it poses challenges such as ambiguity, where a single derived class inherits more than one instance of the same base class variables or methods, leading to conflicts. This can be resolved using virtual inheritance, ensuring only one instance of the base class variables or functions is inherited .