0% found this document useful (0 votes)
20 views68 pages

C++ Data Types and Variable Management

The document provides an overview of data types in C++, including fundamental, derived, and user-defined types, along with their sizes and ranges. It covers variable declaration, initialization, literals, constants, operators, and control statements, illustrating each concept with examples. Additionally, it explains input/output operations, comments, and the use of the cout and cin objects.

Uploaded by

modichore301
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views68 pages

C++ Data Types and Variable Management

The document provides an overview of data types in C++, including fundamental, derived, and user-defined types, along with their sizes and ranges. It covers variable declaration, initialization, literals, constants, operators, and control statements, illustrating each concept with examples. Additionally, it explains input/output operations, comments, and the use of the cout and cin objects.

Uploaded by

modichore301
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Datatypes

Fundamental Derived User Defined


(1) char – 1 byte (1) array (1) class
(2) int – 2 bytes (2) function (2) structure
(3) float – 4 bytes (3) pointer (3) union
(4) double– 8 bytes (4) reference (4) enumeration
(5) void - (5) constant

 Declaring and Initializing variables


int x;
x = 10; Or int x = 10;

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

Or char name[10] =” 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

 Data type modifiers


(1) signed
(2) unsigned
(3) short
(4) long

Size ---- 2bytes


int x
Range --- -32768 to +32767

unsigned int x size --- 2 bytes

Range --- 0 to 65535

signed int x …. same as int


short int x …. same as int
signed short int x …. same as int;
short x …. same as int
singed short x …. same as int
unsigned short int x …. same as unsigned int
unsigned short x …. same as unsigned int

long int x size 4 bytes

Range -2147483648 to +2147483647


singed long int x …. same as long int
signed long x; …. same as long int

unsigned long int x size 4 bytes

Range 0 to 4294967295

unsinged long x …. same as unsigned long int

float size 4 bytes

Range 3.4 * 10-38 to 3.4 * 1038 - 1


double size 8 bytes

Range 1.7 * 10-308 to 1.7 * 10308 – 1

long double size --- 10 bytes

Range 3.4 * 10–4932 to 3.4 * 104932 – 1

 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;

 The cout object


cout is an object of ostream class
Example:
int a = 10;
char b = ‘n’ ;
float c = 25.75;
cout << a; …. 10
cout << b; …. n
cout << c; …. 25.75
cout <<d; …. Error
cout << “a”; …. a
cout << “b”; …. b
cout <<a<<b<<c; …. 10n25.75
cout <<“the value of a is “ << a ;
cout <<“the value of b is “ <<b ;
cout <<“the value of c is “ << c;

 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)

Operand 1 Operand 2 Result


int int int
int float float.
float double double
int double double
long double float long double
long double double long double

 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

 Increment / Decrement Operators


+ +, - -
a+ + or ++a …. a = a +1
a - - or --a …. a=a-1

int a = 5, b= 7, c;

Post Increment / Decrement


c = a + b ++ ;
cout << c << b; …. 12 8
c = a + b- - ;
cout << c << b; …. 12 6
cout << a + +; …. 5
cout << a ; …. 6

Pre Increment / Decrement


c = a + (+ + b)
cout << c << b; …. 13 8
c = a + (- - b);
cout<<c<<b; …. 11 6
cout << + + a ; …. 6
cout << a; …. 6
 Conditional Operators (? : )
int a = 5, b = 7, c = 91, d;
d = (a > 5 ? 10 : 20 )
cout << d ; …. 20
d = ( a >= 9 ? ( b != 71 ? 10 : 20) : ( c = = 91 ? 100 : 200));
cout<<d; …. 100
int marks = 45;
marks >= 40 ? cout<<”passed” : cout<<”failed”;

 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

 Input and output operators


>> …. input operator
<< …. output operator

 A sample c++ program

# 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;
}

 Control Statement in c++

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”;
}

o Switch Case Statement


Example:
void main( )
{
int d;
clrscr( );
cout<<”Enter a number between 1 and 7:”;
cin>>d;
switch(d)
{
case 1: cout<<”Sunday”;
break;
case 2: cout<<”Monday”;
break;
case 3: cout<<”Tuesday”;
break;
case 4: cout<<”Wednesday”;
break;
case 5: cout<<”Thursday”;
break;
case 6: cout<<”Friday”;
break;
case 7: cout<<”Saturday”;
break;
default: 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);

 Difference between loops

o for(x = 15; x< =10; x + +)


cout<<”Raj”;

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 “;
}

 Single Character I / O Functions

Input Output Header File

getchar( ) putchar( ) …. stdio.h


getch( ) putch( ) …. conio.h
getche( ) …. conio.h
[Link]( ) [Link]( ) …. Iostream.h

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<<” enter your name “;


gets(x); …. Rajesh kapoor
Or [Link](x, 20);

cout<<x;
Or puts(x);
Or [Link](x, 20); …. Rajesh kapoor

 String Handling Functions


1. strcpy( )
2. strlen( )
3. strcat( )
4. strcmp( )
5. strrev( )

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

o One Dimensional Arrays


int a, b, c, d. e;
cout<<"enter first no.";
cin>>a;
cout<<"enter second no.";
cin>>b;
.
.
.

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];

cout<<"the entered values are";


for(i=0; i<=9; i++)
cout<<x[i];

char x[10];
cout<<"enter your name";
cin>>x;
cout<<x;

o Two Dimensional Arrays


int a[3][4]; 0 1 2 3
a[0][0] = 2;
a[0][1] = 5; 0 2 5 7 3
.
. 1 9 8 13 12
a[1][0] = 9; 2 11 15 20 23
a[1][1] = 8;
.
.
a[2][0] = 11;
a[2][1] = 15;
a[2][2] = 20;
a[2][3] = 23;

int a[2][3] = {2, 1, 7, 3, 1, 8};


int a[ ][ ]; .... invalid
int a[ ][ ] = {2, 1, 7, 4}; .... invalid
int a[2][ ] = {2, 1, 7, 4}; …. invalid
int a[ ][3] = {2, 7, 3, 9, 15, 12};
int a[3][4]= {5,2,7,3,4,9,6,5};
int a[3][4] = {{5,2,7},{3,4},{9,6,5}};
int x[3][4];
int i, j;
cout<<"enter 12 values";
for(i=0;i <=2; i++) .... rows
{
for(j=0; j<=3; j++) .... columns
cin>>x[i][j];
}

cout<<"entered values are";


for(i=0; i <=2; i ++)
{
for(j=0; j<=3; j++)
cout<<x[i][j];
}

o Arrays of Strings

char a[5][20];
int i;
cout<<"enter 5 strings : ";
for(i=0; i<=4; i++)
[Link](a[i], 20)

cout<<"entered strings are :";


for( i=0;i <=4; i++)
[Link](a[i], 20);

Functions

Predefined(library) Functions User Defined Functions


1. strcpy( )
2. gets( )
3. getch( )
4. clrscr( ) Call by value Call by reference
5. strrev( )
6. pow( )

Three important steps to create a function.


1. Declaration (Prototype)
2. Definition
3. Calling

Example:
void main( )
{
void display( ); .... declaration / prototype
cout<<"raj";
cout<<"amit";
display( ); .... calling
cout<<" vivek ";
cout<<" mohan ";
display( ); .... calling
cout<<" vishal ";
}

void display( ) …. Definition


{
cout<<"rishabh";
cout<<"rohit";
cout<<" kunal ";
return; .... optional
}

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
}

int add(int a, int b) …. Function Definition


{
int c;
c = a + b;
return c; Formal Parameters
}

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
}

void add( int a, int b) …. Function definition


{
int c;
c = a + b;
cout<<"sum is "<<c;
return; .... optional
}

 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
}

int add( int x, int y)


{
int z;
z = x + y;
return z;
}

 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;
}

 Passing Arrays to Functions


void main( )
{
void change(int [] );
int a[10];
int i;
clrscr( );
cout<<"Enter 10 numbers :";
for(i=0; i<=9; i++)
cin>>a[i];
change(a);
cout<<"Values are :";
for(i=0; i<=9; i++)
cout<<a[i];
}
void change(int x[] )
{
int n;
for(n=0; n<=9; n++)
x[n] = x[n] + 5;
return;
}

 Scope Rules and Storage Class Specifiers

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.

Storage Class Specifies and Variables


Four storage class specifies in C++ are auto, register, extern, static.

Auto: The storage specifier auto refers to automatic variable. A variable is declared
automatic as follows:

Auto type variable-name


Example:
Auto int x;
By default variables in a function are auto unless specified otherwise. The auto
variable is automatically created when the function (that define the auto variable) is called
and automatically destroyed when the function terminates.

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;
}

for(i=0; i<=4; i++)


{
cout<<x[i].roll<<x[i].name<<x[i].marks;
}
}

o Arrays Inside structures


Example:
struct xyz
{
int a[5];
float b[5];
};

void main( )
{
xyz m;
cout<<"Enter five integers";
for(i=0; i<=4; i++)
cin>>m.a[i];

cout<<"Enter five floats";


for(i=0; i<=4; i++)
cin>>m.b[i];
}

o Functions and Structures


Example:
struct xyz
{
int x;
float y;
};

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;
}

xyz add (xyz m, xyz n)


{
xyz r;
r.x = m.x + n.x;
r.y = m.y + n.y;
return r;
}

o Typedefs

typedef int amount;

int x; is same as amount x;

typedef amount price;

int x; is same as amount x; is same as price x;

o Typedefs and structures


Example:
struct student
{
int roll;
char name[10];
float marks;
};

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};

weekday day1, day2;


day1 = wed; …. valid
day2 = 7; …. Invalid

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]( );
}

 Class methods (functions) definition


1. Inside the class definition
2. Outside the class definition
o Outside the class definition
Example:
class student
{
int roll;
char name[10];
float marks;
public:
void input( );
void display( );
};

void student : : input ( )


{
cout<<”\n enter roll no., name & marks “;
cin>>roll>>name>>marks;
}
void student : : display( )
{
cout<<roll<<name<<marks;
}

void main( )
{
student o, p;
[Link]( );
[Link]( );
[Link]( );
[Link]( );
}

:: …. scope resolution operator


<classname> : : <member name> .… full name or qualified name

Example:
student : : input( )
student : : display( )

 Arrays inside the class


Example:
class student
{
int roll;
char name[10];
float marks[5], total, avg;
public:
void input( );
void calc( );
void display ( );
};

void student : : input ( )


{
cout<<”\n enter roll no. “;
cin >> roll ;
cout<<” \n enter name “;
cin >>name ;
cout<<”\n enter marks in 5 subjects “;
for ( int i = 0; i<= 4; i++ )
cin>>marks [i] ;
calc( );
}
void student::calc( )
{
total = 0;
for( int i = 0; i < = 4; i ++)
total = total + marks[i];
avg = total/5;
}
void student : : display( )
{
cout<<”roll number is : ”<<roll;
cout<<”name is :“<<name;
cout<<”marks are :”;
for ( int i = 0; i<= 4; i++ )
cout<<marks [i] ;
cout<<”total marks are :”<<total;
cout<<”average marks are : “<<avg;
}
void main( )
{
student o, p;
[Link]( );
[Link]( );
[Link]( );
[Link]( );
}
 Arrays of objects
Example:
class employee
{
int ecode;
char ename[10];
public:
void input( )
{
cout<<”\n enter ecode & ename “;
cin>>ecode>>ename;
}
void disp( )
{
cout<<ecode<<ename;
}
};

void main( )
{
employee m[5];
int i;
for( i =0; i<=4; i++)
{
m[i].input( );
m[i].disp( );
}
}

 The scope rules & classes

o Global class
class abc …. global class
{
public:
void disp( )
{
cout<<”trial message…..”;
}
};

abc m; …. global object is valid

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 o; .... object(local to main) is valid


[Link]( ); …. valid
}

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);
}

inline void square (int m)


{
cout<<m * m;
}

 Friend functions
1. Member functions: A member function can access any member (public,
private, protected) of the class without any object.

2. Non-member functions: A non-member function can access only public


member of the class using an 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 abc :: input( )


{
cout<<” enter two numbers: “;
cin>>x>>y;
}
void abc::display( )
{
cout<<x<<y;
}

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;
}

friend void calc(abc , xyz);


};

void calc(abc m , xyz n)


{
cout<<m.a + m.b + n.x + n.y;
}

void main( )
{
abc p;
xyz q;
[Link]( );
[Link]( );
q,get( );
[Link]( );
calc(p, q);
}

 The scope resolution operator (::)


Example:
int x =10;
void main( )
{
int x = 20;
clrscr( );
cout<<x; …. 20
cout<<::x; …. 10
{
int x =30;
cout<<x; …. 30
cout<<::x; …. 10
}
cout<<x; …. 20
cout<<::x; …. 10
}

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 outer :: inner :: prn( )


{
cout<< b * c;
}

 Constructors & destructors


Example:
class abc
{
int x;
float y;
public:
void init( )
{
x = 10;
y = 20.7;
}
void display( )
{
cout<<x<<y;
}
};

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
}

 Implicit & Explicit call to the constructor

abc o(9, 2.8); ….. Implicit call


abc o = abc(9, 2.8) ….. Explicit call

 Constructor with default arguments


Example:
class abc
{
int x;
float y;
public:
abc( int n = 10, float m = 20.7)
{
x = n;
y = m;
}
void display( )
{
cout<<x<<y;
}
};

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
}

 Some points about constructors


1. Constructor is a function having the same name as its class.
2. Constructors are called automatically when the objects of the class are declared.
3. Constructors are used to initialize the object of the class type with legal initial value.
4. Constructors do not return a value but arguments can be passed to the constructors.

 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]( );
}

 Function overloading and Constructors overloading

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);
}

void calcinterest(long p, int t, float r)


{
float amt;
cout<<”principal amount “<<p;
cout<<”time “<<t;
cout<<”rate “<<r;
amt = ( p * t * r) / 100;
cout<<”interest amount “<<amt;
}

void calcinterest(long p, int t)


{
float amt;
cout<<”principal amount “<<p;
cout<<”time “<<t;
cout<<”rate : 0.08”;
amt = (p * t * 0.08 ) / 100;
cout<<”interest amount : “ <<amt;
}
void calcinterest(long p )
{
float amt;
cout<<”principal amount “<<p;
cout<<”time : 2 years”;
cout<<”rate : 0.08”;
amt = (p * 2 * 0.08 ) / 100;
cout<<” interest amount : “ <<amt;
}

void calcinterest(long p, float r)


{
float amt;
cout<<” principal amount “<<p;
cout<<” time : 3 years”;
cout<<” rate : ”<<r;
amt = ( p * 3 * r ) / 100;
cout<<” interest amount : “ <<amt;
}

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, int t, float r)


{
principal = p;
time = t;
rate = r;
amt = 0.0;
}

deposit::deposit( long p, int t )


{
principal = p;
time = t;
rate = 0.08;
amt = 0.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:

Base class / Super class


x

y Sub class / derived class

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

y Sub class of x and


Base class of z

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 B : public A class B : protected 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
{
…..
};

o Private visibility mode


class a class b

Private Private
A, Input( );
X, Get( );

Protected Protected
B, Output( );
Y, Put( );

Public
Public C, Display( );
Z, Take( );

class a
{
….
….
};

class b : private a
{
….
….
};

o The protected visibility mode


class a class b
Private Private
X, Get( );
A, Input( );

Protected Protected
B, Output( );
Y, Put( );

Public
Public
C, Display( );
Z, Take( );

class a
{
….
};

class b : protected a
{
….
};

Access through objects Inheritable


Private No No
Protected No Yes
Public Yes Yes

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
}

o Constructors and inheritance


Example:
class abc
{
int a;
float b;
public:
abc (int x, float y)
{
a = x;
b = y;
}
void display( )
{
cout<<a<<b;
}
};

class xyz : public abc


{
int n;
public:
xyz (int p, float q, int r): abc (p, q)
{
n = r;
}
void out( )
{
cout<<n;
}
};

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

 Pointers and arrays


Example:
int a[5] = {21, 5, 73, 7, 28};

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

 Pointers and strings


Example:
char name[10] = ”Rajeev”;
char *p = &name[0] Or p = name;
cout<<name; …. Rajeev
cout<<p; …. Rajeev
cout<<*p …. R
cout<<*name; …. R
cout<<( p + 2 ); …. jeev
cout<< name + 2; …. jeev
cout<<*( p + 2 ); …. j
cout<<*( name + 2); …. j

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

char *p[5] = {n[0], n[1], n[2], n[3], n[4] };


cout<<p[0]; …. Rajeev
cout<<p[1]; …. Amit
cout<<p[2]; …. Priya
cout<<p[3]; …. Vicky
cout<<p[4]; …. Himanshu

 Swapping the Strings


Example:
char a[10];

a = n[0]; …. Invalid
n[0] = n[3]; …. invalid
n[3] = a; …. invalid

strcpy(a, n[0]); …. valid


strcpy(n[0], n[3]); …. valid
strcpy(n[3], a); …. valid

char *p[5] = { “Rajeev”,


”Amit”,
”Priya”,
”Vicky”,
”Himanshu”};

cout<<p[0]; …. Rajeev
cout<<p[1]; …. Amit
cout<<p[2]; … Priya

 Swapping the Strings using Pointers


Example:
char *a;

a = p[0];
p[0] = p[3];
p[3] = a;

 Pointers and Functions


Example:
void main( )
{
void change(int *, int *);
int a=10, b=20;
clrscr( );
cout<<a<<b; …. 10 20
change(&a, &b); …. 100 200
cout<<a<<b; …. 100 200
getch( );
}

void change(int *n, int *m)


{
*n = 100;
*m = 200;
cout<<*n<<*m;
}

 Returning pointers From Functions


Example:
void main( )
{
int * biggest(int, int);
int a = 10, b = 20, *p;
p = biggest (a, b);
cout<<”Biggest value is :”<<*p;
}
int * biggest(int x, int y)
{
if (x > y)
return &x;
else
return &y;
}

 Pointers and Structures


Example:
struct student
{
int roll;
char name[10];
float marks;
};

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
}

 Pointers and Classes ( Pointers to Objects)


Example:
class student
{
int roll;
char name[10];
public:
void input(int x, char n[10])
{
roll = x;
strcpy(name, n);
}
void display()
{
cout<<roll<<name;
}
};

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( );
}

 Opening and Closing files

Ifstream: Declare an object of ifstream class to read a file.

ofstream: Declare an object of ofstream class to write a file.


fstream: Declare an object of fstream class to perform both the operations i.e. read
and write.

o Files can be opened in two different ways:


1. Using constructor
2. Using open function

1. Opening File Using Constructor

ifstream obj ("[Link]");


ofstream m ("[Link]");

2 Opening File using open function

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

 Writing into file


Example:
void main( )
{
int roll;
char name[10];
float marks;
char ch;
ofstream obj ("[Link]");
if( ! obj )
{
cout<<"File Opening Error";
return;
}
do
{
cout<<"Enter rollno, 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]();
}

 Reading from a file


Example:
void main( )
{
int roll;
char name[10];
float marks;
ifstream obj;
[Link](" [Link] ");
if( ! obj )
{
cout<<"file Opening Error";
return;
}

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( ![Link]( ) )
{
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

 Opening file using the object of fstream class

fstream obj( "[Link]", ios::in | ios::out );

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]( );
}

 read( ) and write( ) functions

 Reading and Writing Structures


Example (Writing) :
struct student
{
int roll;
char name[10];
float marks;
};
void main( )
{
student o;
char ch;
fstream obj ("[Link]", ios::app | ios::binary)
if( ! obj )
{
cout<<"File opening error";
return;
}
do
{
cout<<"Enter rollno, name and marks:";
cin>>[Link]>>[Link]>>[Link];
[Link]( (char *) &o, sizeof (student) );
cout<<"Do you want to enter another record ( y / n )";
cin>>ch;
}while(ch = = 'y');
[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]( );
}

 Reading and Writing Class Object


Example:
class student
{
int roll;
char name[10];
float marks;
public:
void input( );
void display( );
};
void student ::input( )
{
cout<<"Enter rollno, name and marks:";
cin>>roll>>name>>marks;
}
void student::display( )
{
cout<<roll<<name<<marks;
}
void main( )
{
student o;
char ch;
fstream obj("[Link]", ios::out | ios::in);
if( ! obj )
{
cout<<"File opening error";
return;
}
do
{
[Link]( );
[Link] ((char *) &o, sizeof (student) );
cout<<"Do you want to enter another record( y / n )";
cin>>ch;
}while(ch = = 'y');
[Link](0);
while( ! [Link]( ))
{
[Link]((char *) &o, sizeof (student));
[Link]( );
}
[Link]( );
}

 File Pointers and Random Access


Every file maintains two pointers called get_pointer and put_pointer which tells the
current position in the file where writing or reading will take place. These pointers help to
attain random access in file.
To set and examine the get_pointer the following functions are used:

seekg( ) used with ifstream objects


tellg( ) used with ifstream objects

To set and examine the put pointer the following function are used:

seekp( ) used with ofstream objects


tellp( ) used with ofstream objects

Example:
[Link]( 30 );
[Link]( 30 );
int x;
x = [Link]( ); cout<<x;
x = [Link]( ); cout<<x;

ios::beg refers to beginning of file


ios::cur refers to current position in file
ios::end refers to end of file

[Link] (30, ios::beg);


[Link] (-5, ios::end);
[Link] (-2, ios::cur);

[Link] (40, ios::beg);


[Link] (-5, ios::end);
[Link] (15, ios::cur);

 get( ) and getline( ) functions

char x[30];
[Link] (x, 30); …. For input
Or [Link] (x, 30, '#'); …. For input

Or [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.

Common questions

Powered by AI

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 .

You might also like