0% found this document useful (0 votes)
0 views

CH 3-Programming in C++

Uploaded by

sakshikamble8516
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

CH 3-Programming in C++

Uploaded by

sakshikamble8516
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 115

CH.

3 : Programming in C++
• Introduction :-
• The C++ Program is made up of sequence of characters. The characters are the
most basic building blocks of the C++ language.
• Characters set is a set of valid characters recognized by a language. A character
represents any letter ,digit, or any other sign.
• The C++ character set consists of upper and lower case letters, digits, special
characters and white spaces. The letters and digits together constitute the
alphanumeric set.
• Token is a sequence of characters from the character set of C++, which is
identified by the complier.
• Keywords are used for specific purposes in C++ and compiler can interprets these
words.
Data Types :-
• A data type determines the type and the operations that can be
performed on the data.
• A data type is defined as, “the set/collection of values and the set of
operations that operate on those values “.
• In short , data type is analyzed as follows :
Data Type = Permitted Data values + Operations
• The various data types provided by C++ are built-in data types,
derived data types and user defined data types ,As shown Fig. :
Hierarchy of C++ Data Types :-
1. Built-In Data Types
• The basic (fundamental) data types provided by c++ are integral, floating point and void data type.
Among these data types, the integral and floating-point data types can be preceded by several type
modifiers. These modifiers (also known as type qualifiers) are the keywords that alter either size or range
or both of the data types. The various modifiers are short, long, signed and unsigned. By default the
modifier is signed.
• In addition to these basic data types, ANSI C++ has introduced two more data types namely, bool and
wchar_t.
• Integral Data Type: The integral data type is used to store integers and includes char (character) and int
(integer) data types.
• Char: Characters refer to the alphabet, numbers and other characters (such as {, @, #, etc.) defined in the
ASCII character set. In C++, the char data type is also treated as an integer data type as the characters are
internally stored as integers that range in value from -128 to 127. The char data type occupies 1 byte of
memory (that is, it holds only one character at a time).
The modifiers that can precede char are signed and unsigned. The various character data types with their
size and range are listed in Table.
Int: Numbers without the fractional part represent integer data. In C++, the int data type is used to store integers
such as 4, 42, 5233, -32, -745. Thus, it cannot store numbers such as 4.28, -62.533. The various integer data
types with their size and range are listed in Table.
• Floating-point Data Type: A floating-point data type is used to store
real numbers such as 3 .28, 64. 755765, 8.01, -24.53. This data type
includes float and double’ data types. The various floating -point data
types with their size and range are listed in Table.
Void: The void data type is used for specifying an empty parameter list to a function and return type for
a function. When void is used to specify an empty parameter list, it indicates that a function does not
take any arguments and when it is used as a return type for a function, it indicates that a function does
not return any value. For void, no memory is allocated and hence, it cannot store anything. As a result,
void cannot be used to declare simple variables, however, it can be used to declare generic pointers.

Bool and wchar_t : The boo1data type can hold only Boolean values, that is; either true or false, where
true represents 1 and false represents O. It requires only one bit of storage, however, it is stored as an
integer in the memory. Thus, it is also considered as an integral data type. The bool data type is most
commonly used for expressing the results of logical operations performed on the data. It is also used as
a return type of a function indicating the success or the failure of the function.

In addition to char data type, C++ provides another data type wchar_t which is used to store 16- bit
wide characters. Wide characters are used to hold large character sets associated with some non-
English languages.
2. User-defined Data types : -
• User has the facility in the programming languages to create data
types according to his/her own needs.
• The data types defined by user according to his/her requirements
known as user-defined data types.
i. Enumerated :-
o In C++ , enumerated data type helps in enhancing the reliability of
the code.
o Enumerations are a way of defining constants.
o Syntax :-
enum tag {member1,member2,-------,membern};
o Here, enum is the keyword and tag is the name of enumeration and
member1,member2,------------member are identifiers which
represents integer constant values. The member should be unique.
Once, the enumeration is defined then variable or object of that type
is defined.
o Syntax :-
enum tag{member1,member2,--------} Variables;
OR
enum tag{member1, member2-------}object_name;
o Here, all members take integer values starting with zero i.e. member1
is assigned 0,member2 is assigned 1 ………and so on.
• For example :-
• enum colors {black,green,red,yellow,blue};
• Enum colors background;
• Here,
• black+=0,green=1,red=2………
• Enumeration variables are particularly useful as flags to indicate
various options are to identify various conditions. It increases clarity
of the program. If we want to have blue colors for the background, it
is easier to understand with,
• background = blue Than with background =4;
• It makes program more readable.
Structure :-
o In ‘C’ structure is a collection of data items of different data types.
o In C++ structure is a collection of variables of different data types in a
single name.
o Syntax :-
struct name of structure
{
data members;
functions
}
o For example,
struct student
{
private ;
char name[20];
long phone;
public :
void display(void)
{
cout<<phone;
}
} ;
o By default members of the C++ structure are public.
• For example,
struct student s;
printf(“%ld”,s.phone); // Invalid
• We cannot print phone like this, we have to invoke public function
display to print phone i.e. Instead of printf statement we can write,
• s.display();
iii. Union:-
• Union in C++ is a user defined data type that uses the same memory as
other objects from a list of objects. At an instance it contains only a single
object.
• Syntax :-
union tag
{
member1;
member2;

member n;
} objectname;
• For example :-
union example
{
int a;
char b;
float c;
}e;
• There are three elements of different types int, char and float respectively. Here, int
takes two bytes memory, char takes one byte memory and float takes four bytes.
• Union allows the same storage is shared with its members .
• Hence, Total memory required is four bytes.
• Unions are very useful for applications involving multiple members, where values need
not be assigned to all members at one time .
• Whereas , in case structure for same example , memory required is 2+1+4= 7 bytes to
store its contents.
iv. Class :-

• C++ also permits to define another user-defined data type known as


class which can be used, just like any other basic data type ,to declare
variables.
• The class variables are known as objects, which are the focus of
object oriented programming.
• Generally, class is used in C++ instead of struct.
• Class is a user define data type with data elements and functions.
• Differentiate between a class and a structure in C++ :-
• There is not much difference between a class in C++ and a structure in
C++.
• Everything which is defined in structure in C++ is also applicable to
the classes in C++.
• The two differences are :
• The keyword class is used instead of struct.
• All the members in a class are by default private.
• For example :
• Class student
{
int roll; By default both are private
char name[20];
public:
void getdata(void);
void putdata();
};
iii. Derived Data Types :
Data types that are derived from the built-in data types
are known as derived data types.
The various derived data types provided by C++ are
arrays, junctions, references and pointers
• Array:-
• An array in C++ is a collection of fixed-size finite number of objects, data value
that belong to the same type
• An array is a collection of data storage locations.
• Each of the locations of an array in C++ holds same type of data.
• An array is a set of elements of the same data type that are referred
to by the same name.
• The storage location is called an element or component of the array.
• The individual element within the array is called subscript .
• All the elements in an array are stored at contiguous (one after another) memory
locations and each element is accessed by a unique index or subscript value.
• The subscript value indicates the position of an element in an array.
• In C, array size is exact same length of the string constant.
• For example,
char string[5] = “abcde”; //valid in C

• But in C++, the array size is one larger than the number of characters present in the
string.
• Here,”\0” is treated as a one character.
• For example :-
char string[5] = “abcde”; //Invalid in C++
char string[5] = “abcd”; //valid in C++
• Functions :
• A Function is a discrete block of statements that perform certain task.
• Once, a function has been written to play a particular role it can be
called upon repeatedly throughout the program.
• Function is the named part of a program that can be declared before
its use, such a declaration is known as a function prototype it ends
with semicolon.
• Syntax : return_type function_name(parameters);
• For example : int max(int x, int y);
• Pointers :-
• A variable in C++ that holds a memory address is called a pointer.
• This address is usually the location of another variable in memory.
• If one variable contains the address of another variable, the first
variable is said to point to the second.
• A pointer declaration consists of a base type, an *(asterisk) and the
variable name.
• Syntax :- datatype *ptvar;
• Where, ptvar is pointer variable.
• For example : float *I; //float pointer
• Program: Write a program which demonstrates the declaration of pointer.
• #include<iostream.h>
using namespace std;
main()
{
int l=2; Output :-
Address of l = 6242
int *m; Value of l = 2

m = &l;
printf(“\n Address of l = %u”,m);
printf(“\n Value of l = %d”, *m);
}
Accessing variable through its
pointer:-
• Once, pointer has been assigned the address of a variable then we can
access the value of the variable using the pointer. If the above program ,we
add a statement , c = *m
• Where, c is int and it access value of address
*m=30; //30 assigned to l through indirection
• In addition to this c++ also have constant pointer declaration and pointer to
constant declaration.
• For example;
• int *const m = “xyz”; //Constant pointer
• int const *m = &l; //pointer to a constant
• In constant pointer we cannot change address of ‘m’ and in pointer to a
constant, the contents of ‘l’ cannot change.
void pointer :-
• void pointer used to point the other data type of variable in C++.
• If we define,
int *m;
float *l;
m=&l; //results in compilation error.
• For such type compatibility void pointers are used.
• For example,
• void *v;
int *i;
float *f;
v=&i;
v=&f;
Here, void pointer v will hold pointer of any type.
void Data Type:-
• The void data type also known as empty data type. void is used for
following two purposes:-
• If the function is not having any arguments, functionname(void);
• To specify the return type of function when function is not returning
any value.
• Void functionname(void);
Operators in C++ can be classified into 6 types: Increment and Decrement Operators
++ increases the value of the operand by 1
Arithmetic Operators -- decreases it by 1
Assignment Operators
Relational Operators 2. C++ Assignment Operators
Logical Operators Operator Example Equivalent to
Bitwise Operators = a = b; a = b;
Other Operators += a += b; a = a + b;
1. C++ Arithmetic Operators -= a -= b; a = a - b;
Operator Operation *= a *= b; a = a * b;
/= a /= b; a = a / b;
+ Addition %= a %= b; a = a % b;

- Subtraction
3. C++ Relational Operators
* Multiplication Operator Meaning Example
== Is Equal To 3 == 5 gives us false
/ Division != Not Equal To 3 != 5 gives us true
> Greater Than 3 > 5 gives us false
Modulo < Less Than 3 < 5 gives us true
Operation >= Greater Than or Equal To 3 >= 5 give us false
%
(Remainder after
division) <= Less Than or Equal To 3 <= 5 gives us true
4. C++ Logical Operators 5. C++ Bitwise Operators
Operator Example Meaning Operator Description

Logical AND. & Binary AND


expression1 True only if
&& && all the | Binary OR
expression2 operands are
true. ^ Binary XOR

Binary One's
Logical OR. ~
Complement
expression1 True if at
|| || least one of
expression2 the operands << Binary Shift Left
is true.
>> Binary Shift Right

Logical NOT.
True only if
! !expression
the operand
is false.
• Unary Operators :- -, ++, --, sizeof, !
• Conditional Operator :-
• This is the only ternary operator used in C and C++. It is defined as (?:) where
the first symbol is ? and second is : (colon).
• Syntax :
• condition expression? expression 1 : expression 2;
• The condition expression is evaluated first and if true then expression1 is
evaluated otherwise expression2 is evaluated.
• For example,
mfloat a = 15;
float b,c;
(a<20)?b =50 :c=100;
All these above operators are valid in C and C++.
6. Other C++ Operators The scope resolution operator ( :: ) is used for several reasons.
For example: If the global variable name is same as local
Operator Description Example
variable name, the scope resolution operator will be used to
sizeof
returns the size of data
type
sizeof(int); // 4 call the global variable. It is also used to define a function
outside the class and used to access the static variables of class.
returns value based on string result = (5 > 0) ?
?:
the condition "even" : "odd"; // "even"

represents memory &num; // address of


C++ has two types of memory management operators:
&
address of the operand num

new
accesses members of
. struct variables or class s1.marks = 92; delete
objects
new operator: It is used for dynamic storage allowance. The
used with pointers to new operator allows you to create objects of any type.
-> access the class or struct ptr->marks = 92;
variables
pointer variable = new datatype;
<< prints the output value cout << 5;

>> gets the input value cin >> num;


delete operator: The C++ delete operator is used to release
memory space when the object is no longer required. Once a
new operator is used, it is effective to use the corresponding
deletion operator to free up memory.

delete pointer variable;


New Operators in C++ :-
• C++ have some other new operators also. These are:-
Operator Meaning
endl Line feed Operator
setw Field with Operator
new Memory allocation operator
delete Memory release operator
:: Scope resolution Operator
::* Pointer to member declaration
->* Pointer to member operator
.* Pointer-to-member operator

C++ also provides new meaning of some built-in operators. This is Operator Overloading.
1. Scope Resolution Operator(::) :-

• The scope resolution operator is denoted by a pair of colons(::). It


is use to access global variable even if the local variable have the
same name as global.
• When the same function name is used for many classes, then this
complexity is solved by using scope resolution operator to indicate
the class with which the function is associated.
Example :- Simple scope resolution operator.
• #include<iostream.h>
using namespace std;
int a=10;
int main()
{
int a=15;
cout <<“\n Local a=” <<a<<“Global a=”<<::a;
::a=20;
cout<<“\n Local a=” <<a<<“Global a=”<<::a;
}
Output :-
Local a=15 Global a=10
Local a=15 Global a=20
Note :-
• Suppose in a C program, there are two variables with the same name
‘a’. One is global (outside a function) and local (inside a function). We
attempt to access the variable ‘a’ in the function, we always access
the local variable (priority to local).
• C++ allows the flexibility of accessing both the variables using scope
resolution operator (::).
Example :- Use of scope resolution operator for
class :-
• #include<iostream.h> Void T::putdata()
using namespace std; {
cout<<“a=”<<a<<endl;
class T cout<<“b=”<<b<<endl;
{ }
int a,b; Void main()
{
public : T a;
void getdata(); a.getdata();
void putdata(); a.putdata();
}
}; OUTPUT :
Void T::getdata() 10 20 //input
a = 10
{
b = 20
cin>>a>>b;
}
2. Memory Dereferencing Operators :-
• C++ uses pointers to access class members i.e. data and functions.
• There are 3 memory dereferencing operators are :-
i) ::* This declare a pointer to a member of class,
For example:- void (T::*P1) (int) = T::f1;
Here, class is T. The above definition says that the member function to
which P1 points will return nothing but requires int argument. It also
initialise the pointer P1 to the address of the function f1 of class T.
ii) .* To access a member using object name and a pointer to that
member.
For example:-
T 01;
(01 .*P) (3) //Call function through pointer
iii)->* To access a member using a pointer to the object and a pointer
to that member.
For example :
T 01;
01 *p;
p -> *f1(2);
3. Memory Management Operator:-
• For dynamic memory allocation, C++ provides new operator.
• In C, we have malloc() and calloc() functions for dynamic allocation.
• For dynamic deallocation, C++ provides delete() operator, which is same as
free() function in C.
i) new operator :The new operator is used to allocate the memory.
syntax : ptr_var = new datatype;
For example :
char *P;
P = new char[5]; //reserves 5 bytes of contiguous memory of characters
int *x;
x = new int //allocate 2 bytes for integer
• delete operator : The delete operator deallocates or frees the
memory allocated by new.
• Syntax : delete ptr_var;
• The ptr_var is the pointer to a data object which is created by new.
• For example, delete P;
delete x;
• If the array is allocated by new, then to free it we use the following
syntax : delete[size] ptr_var;
• If the size is not specified then entire array get deleted .
• For example, delete [] a;
• Program for new and delete operators :-
• #include<iostream.h>
#include<string.h>
using namespace std;
void main()
{
char *x;
x = new char[10];
cout<<“Enter String”;
cin>>x;
cout<<“\n The string is :” <<x<<endl;
delete x;
}
Output :-
The string is : COMPUTER
4. Insertion and Extraction Operators :-
• In C++, cin and cout operators are used for input and output operations
respectively.
• C++ language I/O operators can be used by including ‘iostream’ header file in
the program.
• Extraction operator (>>) : is used to read data from a standard input device to
the memory items.
• Insertion Operator (<<) is used to write data from memory to a standard output
device.
• In C++, the input stream uses ‘cin’ object to read data and the output stream
uses ‘cout’ object to display data on the screen. The cin and cout are
predefined stream for input and output of data.
• The data type is identified by these functions using operator overloading of the
operators <<(insertion operator) and >>(extraction operator).
• Example :
• #include <iostream .h>
• using namespace std ;
• int main()
• { int size; // variable declaration
• int *arr = new int[size]; // creating an array
• cout<<"Enter the size of the array : ";
• std::cin >> size;
• cout<<"\nEnter the element : ";
• for(int i=0;i<size; i++)
• {
• cin>>arr[i] ;
• }
• cout<<"\nThe elements that you have entered are :";
• for(int i=0;i<size;i++)
• {
• cout<<ar[i]<<“,”r
• }
• delete arr; // deleting an existing array.
• return 0;
• }
Insertion Operator
Extraction Operator

>> Variables Memory Variables <<

cin cout

Input Output
Devices Devices

Fig. : Insertion and Extraction Operators


• The >>(extraction) operator in C++ is used with the cin statement .
• The operator >> is also called as get from operator.
• For example :-
• int x;
• Cin>>x;
• In above example, the >> (extraction) operator extracts a value such
as 40 from the keyboard and assigns it to the variable x, as shown in
Figure:
40
cin >> 40

Extraction i
Operator

Keyboard
Fig. :- Extraction Operator
Input Device
• The << (insertion) operator in C++ is used with the cout statement, which is used
to send the result to an output device (monitor).
• The << operator is used to insert the contents of a variable on its right to the
object on its left.
• The operator << also called as put to operator.
• For example :
int avg = 10;
Cout<<“Average is :”<<avg<<endl;
• In the above example, the << operator first sends the string Average is: to cout.
• Next, the content of the variable avg is sent to cout and finally the keyword endl is
sent, which transfers the control to the end of the line, as shown in Fig. :-
Monitor Insertion
Object Operator
Average is: << avg

Fig. : Insertion Operator


• The << and >> operators for shifting are overloaded in ostream and
istream class respectively.
• The general syntax for reading the data from the keyboard is:
• cin >> var1, >> var2, >>………>>varn;
where, var1 and var2 are any, C++ predefined vaiables.
• This statement in the program will make the compiler to wait for the input
data from the keyboard.
• The operator >> reads the data character by character and assigns it to the
indicated location.
• The reading for the variable will be terminated at the encounter of a
white space or a character that does not match with destination type.
• The general syntax for displaying data on screen is:
• cout <<data1<<data2<<…………………..<<datan;
Keywords :-
• The keyword implements specific C++ language features.
• Keywords are explicitly reserved identifiers and cannot be used as
name for the program variables.
• It is mandatory that all the keywords should be in lowercase letters.
• The keywords are reserved words, predefined by the language and
user cannot change.
• Keywords are used for specific purposes in C++ and compiler can
interprets these words.
• Table shows the list of keywords which are common in C and C++
language :

auto default float return union


break do for shortsigned unsigned
case double goto sizeof void
char else int staticstruct volatile
const enum long switch while
continue extern register typedef

Table : Keywords common to C and C++


• Table :- Keyword Specific to C++
asm inline template using
bitand new this virtual
bitor namespace throw Wchar_t
catch operator true
class private try
delete protected typeid
friend public typename

New Keywords in C++ :-


• C++ uses some additional keywords which are supporting new features
in C++.
bool false true
const_cast mutable typeid
dynamic_cast namespace typename
explicit reinterpret_cast using
export Static_cast Wchar_t
Type Casting in C++ :-
• In C++, there are two types of type casting i.e. implicit type casting and explicit type casting.
1. Implicit Type Conversion:-
• This is also known as automatic type conversion. It is done by the compiler on it’s own. There is no external
trigger required by the user to typecast a variable from one type to another.
• This occurs when an expression contains variables of more than one type. So, in these scenarios automatic
type conversion takes place to avoid loss of data. In automatic type conversion, all the data types present in
the expression are converted to data type of the variable with the largest data type.
• For example :
short a=2000;
int b;
b=a;
• Here, the value of a has been promoted from short to int and we have not had to specify any typecasting
operator. This is known as a Standard Conversion.
• Standard conversions affect fundamental data types and allow conversions such as the conversions between
numerical types(short to int , int to float, double to int……) , to or from bool, and some pointer conversions.
• Some of these conversions may imply a loss of precision, which the compiler can signal with a warning.
• The warning can be avoided with an explicit conversion.
2. Explicit Type Conversion :-
• Explicit type conversion is also known as type casting.
• It is user defined type conversion.
• In explicit type conversion, the user converts one type of variable to
another type.
• Explicit type conversion can be done using Cast operators.
Conversion using Cast Operator :-
• Cast operator is an unary operator which forces one data type to be
converted into another data type.
• There are four types of casting in C++, i.e. Static Cast, Dynamic Cast,
Const Cast and Reinterpret Cast.
1. Typeid Operator :-
• The typeid operator returns an identifier for an object, which can be
compared to other type and printed appropriate message. We have to
include the header file<typeinfo.h> to use the results of the operator.
• #include<typeinfo.h>
• We can use typeid for classes and objects both.
• For example :-The function test the condition that an object is of type
x.
• if(typeid(object) == typeid(x))
cout<<“object is x”;
• The typeid operator returns an object of class type_info, which has a
member function called name. This function returns a null terminated
character string.
cout<<(typeid(objectname).name()) ;
2. static_cast operator :
It is used for type casting,(any type conversion). It also allow to cast
a pointer of a derived class to it’s base class.
The Syntax is:
static_cast <data type> (object name)
For example:
1. int a=10;
float b = static_cast <float> a;
2. Class x class y:public x
{
{ …………………..
};
……………. X * P1 = new x;
}; Y * P2 = static_cast<y*>
P1
3. dynamic _cast operator :
• It is used type casting same as static_cast operator but at runtime.
• It is used with pointers and references to objects.
• Syntax is :-
dynamic_cast <data type> (object name)
Here, objectname is base class object.
• Example :-
void f1(employee *P)
{
manager *m;
m = dynamic_cast <manager*>(P);
if(m)
{
…………………
…………………
}
}
4. const_cast operator :-
• This type of casting manipulates the const attribute of the passed object.
• It is either override or removed.
• For example :
• class x
{
………………………
};
const x *P1 = new x;
x *P2 = const_cast <x*> (P1);
5. reinterpret_cast operator :-
• This is used for pointer casting i.e. a pointer type change to any other type.
• For example :-
int i;
float f;
int *p1;
float *p2;
p1 = reinterpret_cast<int*>i;
p2 = reinterpret_cast<float *>f;
Reference Variable :-
• A reference variable is an alias or alternative name for a previously defined variable.
• For example :
int a = 20;
int &b = a; //& is a reference operator
2132 <- value
20 <- Value
a <- Variable
b <- reference to a
Manipulating a reference to an object allows manipulation of the object itself. This is because no
separate memory is allocated for a reference.
• A reference to a variable is created using the address of operator (&).
• When the & operator is used in the declaration, it becomes the reference operator .
• A reference variable is declared as follows :
• Datatype &ref_var_name = variable_name;
• Where, ref_var_name is name of reference variable.
• In above example, a is an integer variable whose address(l-value) is 2132 which is initialize to 20.
• In the second statement, ‘b’ is a reference to ‘a’.
• If we manipulate the value of b(say 10), then the value of the memory location 2132 gets changed or in other
words the value of ‘a’ changes.
• Ex. Program for reference variable
• #include<iostream.h>
using namespace std;
void main ()
{
int p=50;
int *a = &p;
int &b = *a;
cout<<“*a=”<<*a<<“b=”<<b<<endl;
int x = 10;
int &y = x;
x = x + 10;
Cout<<“x=“<<x<<“y=”<<y<<endl;
}
OUTPUT:-
*a = 50 b = 50
X = 20y = 20
Reference and Function Call :-
• We can use reference variable in passing arguments to functions. When we
use pass by reference mechanism, the function receives the l-value of the
argument rather than the copy of the passed argument.
• Program :- Use of reference in function arguments.
#include<iostream.h> int main()
using namespace std; {
int x=10,y=20;
void swap(int &a, int &b) swap(x,y) ;
{
int temp; cout<<“x=”<<x<<
temp = a; “y=”<<y;
}
a = b;
Output :-
b = temp; x=20 y=10
}
• Here, x and y are alias of a and b respectively. So one location we
have two names as shown in below :
• before call at call
x 10 a 10 X is reffering same location as a

y 20 b 20 y

after execution

10 y

20 x
Classes And Access Specifiers :-
• Access specifiers are used to restrict (limits) the accessibility of class
members.
• Access specifiers defines how the members of the class can be accessed.
• Each member of a class is associated with an access specifiers.
• The access specifiers of a member control its accessibility as well as
determines the part of the program that can directly access the member of
the class.
• In the class declaration syntax, the keyword private , public and protected
are known as access specifiers (also known as visibility modes).
• An access specifier specifies the access rules for members following it until
the end of the class or until another access specifier is encountered.
• When a member is declared private, it can be accessed only inside the class .
• While a public member is accessible both inside and outside the class.
• Protected members are accessible both inside the class in which they are declared as
well as inside the derived classes of the same class.
• Once, an access specifier has been used, it remains in effect until another access specifier
is encountered or the end of the class declaration is reached.
• An access specifier is provided by writing the appropriate keyword (private , public or
protected) followed by a colon ‘:’.
• Note that :-
• The default access specifier of the member of a class is private.
• i.e. ,If no access specifier is provided in the class definition, the access specifier is
considered to be private.
• In C++, We can set the access of a class’s members using the access specifiers. We can
make members private (visible only to code in the same class), protected (visible only
inside the same class and classes derived from it.) ,or public(visible to code inside and
outside the class).
• By default, all the class has private access.
• The general syntax of a class declaration that uses the private and public access
specifiers are given below :-
• Class ClassName
• For example :-
{
class book
private : {
//Declarations of private //private by default
// members appear here …. char title[30]; // variable
declaration
public :
float price;
//Declarations of public public :
// members appear here …. void getdata(char [], float);
}; //function declaration
void putdata();
};
• In above example, a class name book with two data
members title and price and two member functions getdata()
and putdata() is created. As no access specifier is provided
for data members, they are private by default, whereas, the
member functions are declared as public. It implies that the
data members are accessible only through the member
functions while the member functions can be accessed
anywhere in the program.
Defining Data Members And Member Functions :-
• All the variables inside the class are called data members. These variables are of any basic data
type, derived data type, user defined data type or objects of other class.
• Any function declare inside a class is called a member function of that class. Only the member
functions can have access to the private data members and private functions. By default all
members of class are private.
• The general syntax of a class declaration is shown below :-
class class _name
{
private:
variable declarations;
function declarations;
public :
variable declarations;
function declarations;
};
class : Name
• Private area
Data members

Function members

Public area

Data members

Function members

Fig. :- Data Members and Member Function


• Member functions of a class are defined in following two ways :-
1. Inside the class function.
2. Outside the class.
• In both ways, only syntax of definition of member function changes but body of function (code) is remain same.
1. Inside the class Definition :-
• Functions which are defined inside the class are similar to normal functions and they are handle automatically and inline functions.
• Normally, function which are small are define inside the class :
• Example of student class :
• class student
{
int roll;
char name[20] ;
public:
void getdata() //definition of a member function
{
cin>>roll>>name;
}
void putdata() //definition of member function
{
cout<<roll<<name;
}
2. Outside the Class :-
• The functions are define after the class declaration, however the prototype
of function should be appear inside the class i.e. declaration only(not
definition). Since, the function is defined outside the class, there should be
some mechanism to know the identity of function to which class they
belong we have to use scope resolution operator(::) to identify the function
belongs to which class.
• We can also have a function with the same name and same argument list in
different classes, since the scope resolution operator will resolve the scope
of the function.
• The general syntax is :
• return_type class_name :: function_name(argument list if any)
•{
……………………………….. // body of function
•}
• Example :-
class student
{
…………………………………..
…………………………………..
public:
void getdata(); //declaration of member function
…………………………………………
……………………………………......
};
void student :: getdata()
{
…………………………
}
• Program for class declaration and creation of objects.
• #include<iostream.h>
using namespace std;
class date
{
private :
int d;
int m;
int y;
public :
void get(int Day, int Month, int Year);
void display(); //declaration
};
void date :: get(int Day, int Month, int Year) //definition
{
d=Day;
m=Month;
y=Year;
}
void date::display() //definition Output:-
{ Birth Date of the first child : 26-3-1968
cout<<d<<“-”<<m<<“-”<<y<<endl; Birth Date of the second child : 15-9-1978
} Birth Date of the third child : 12-3-1992
int main()
{
date d1, d2, d3; //date objects d1, d2 & d3
d1.get(26, 3, 1968); //call member function
d2.get(15, 9, 1978);
d3.get(12, 3, 1992);
cout<<“Birth Date of the first child :”; Note :
d1.display(); • A member function can call another member function directly.
cout<<“Birth Date of the second child :”; • No memory is allocated till the point you defined objects of that class.
d2.display();
cout<<“Birth Date of the third child :”;
d3.display();
}
Arrays And Array of Objects :-
• The array of variables of class data type is called Array of objects.
• An array of objects is an array of a class type is also known as an array
of objects.
• An array of objects is declared in the same way as an array of any
built-in data type.
• The syntax for declaring an array of objects is as follows :
• class_name array_name[size];
• Example :
• class student
{
int roll;
char name[20] ;
public :
void getdata();
void putdata();
};
If we create object of class student,
student s; //single object
The array of objects is created as :
student s[100] ; //array of student
Here, the array of s contains 100 objects.
We can also have the array of different categories of the student,
student sc[10];
student open[30];
student obc[20];
• The array of sc contains 10 objects, the array of open contains 30 objects, and
the array of obc contains 20 objects.
• The behavior and attributes of each object is define is class where the
identifier name is same but values are different.
• For example , Identifier roll has values 100,101………
• The array of object is stored in memory as same as how multidimensional
array are stored. The space is required only for data item of the class. The
array of student is representing in Fig.
• We have discussed how single object access the data items on member
function. In same way, using array of objects we can access members of class
(using dot) .
• For example, student[i].getdata();
• Here, we can input the ith element data of student array.
• For example, student[i] .putdata();
• Hence, we can display the ith element of the student array.
Fig. : Storage for Data Items in Array of Objects

Roll
Student[1]
Name

Roll
Student[2]
Name
Roll
Student[3]
Name
|
|
|

Roll
Student[99]
Name
void putdata(void)
• Program for array of objects. {
• #include<iostream.h> cout<<“roll :”<<roll<<endl; 3. Student Information
cout<<“name”<<name<<“\n”; Enter roll : 202
using namespace std;
} Enter name : Anita
class student roll : 200
int main()
{ { name : Nirali
int roll; int i; roll : 201
student s[3]; //array of size 3 name : Prajakta
char name[20]; roll : 202
for(i=0;i<3;i++)
public : name : Anita
{
void getdata(void); s[i].putdata();
void putdata(void); }
}; return 0;
}
void student :: getdata(void)
Output :
{ 1. Student Information
cout<<“Enter rollno :”; Enter roll : 200
cin>>roll; Enter name : Nirali
2. Student Information
cout<<“Enter name :” ;
Enter roll : 201
cin>>name; Enter name : Prajakta
}
Usage of Namespace :-
• Consider a situation, when we have two persons with the same name, Seema, in the same class.
• Whenever, we need to differentiate them definitely we should have to use some additional
information along with their name, like either the area, if they live in different area or their
mother’s or father’s name, etc.
• Same situation can arise in the C++ applications.
• For example :- We might be writing some code that has a function called abc() and there is
another library available which is also having same function abc(). Now the compiler has no way
of knowing which version of abc() function we are referring to within the code.
• A namespace is designed to overcome this difficulty and is used as additional information to
differentiate similar functions, classes, variables etc. with the same name available in different
libraries. Using namespace, we can define the context in which names are defined. A namespace
defines a scope.
• A namespace is a declarative region that provides a scope to the identifiers(names of the types,
function, variables etc. ) inside it.
• Namespaces are used to group related names and to avoid clashes between similar names in
different parts of large programs.
• Defining a Namespace :
• A namespace definition begins with the keyword ‘namespace’ followed by
the namespace name as follows :-
• namespace namespace_name
{
//code declaration……..
}
To call the namespace enabled version of either function or variable we use ,
name ::code //code could be variable or function
• Program for namespace accept
• #include<iostream.h>
using namespace std;
//first namespace
int main()
namespace space_one {
{ //calls function from first name space
void func() space_one::func();
// Calls function fron second name space
{
space two::func();
cout<<“Inside space_one”; return 0;
} }
}
OUTPUT :
Inside space_one
//second namespace Inside space_two
namespace space_two
{
void func()
{
cout<<“Inside space_two”;
}
}
Managing Console I/O :-

• C++ defines its own object oriented I/O systems; it has its own object
oriented way of handling data input and output.
• These Input/Output operations are carried out using different stream
classes and their related functions.
• Until now we have used the object of the istream class (cin) and
object of ostream class until (cout); with operators >> and <<
respectively.
• For formatting purpose we use different streams and their functions
in C++.
C++ Streams :-
• A stream is sequence of bytes.
• Stream acts either as a source from which the input data can be
obtained or as a destination to which the output data can be sent.
• In C++, to manage the data flow we have different stream classes,
• Fig. shows stream classes for console I/O.
ios

istream streambuf ostream

istream.withassign ostream.withassign

iostream

iostream.withassign
#include<iostream.h>
1. istream class :
• It is a derived class of ios and hence, inherits the properties of ios.
• It defines input functions such as get(), getline() and read().
• In addition, it has an overloaded member function, stream extraction
operator >>, to read data from a standard input device to the memory
items.
2. ostream class :
• It is a derived class of ios and hence inherits the properties of ios.
• It defines output functions such as put() and write().
• In addition, it has an overloaded member function, stream insertion
operator <<, to write data from memory to a standard output device.
• cerr object is of ostream class used for displaying error messages.
3. iostream class :-
• It is derived from multiple base classes, istream and ostream, which
are inturn inherited from class ios.
• It supports both input and output stream operations.
• These classes istream_withassign, ostream_withassign and
iostream_withassign add the assignment operators to their parent
classes.
Usage of Manipulators :
• Manipulators are the functions used in Input/Output statement.
• All the manipulators are defined in header file iomanip.h.
• We can use chain of manipulator that is one or more manipulators in
statement.
Table : Manipulators
Manipulators Equivalent I/O function
setw() width()
setprecision() precision()
setfill() fill()
setioflags() setf()
resetioflags() unsetf()
1. Setting of field width :
• setw() is used to define the width of field necessary for the output for a
variable .
• For example: setw(5); This function will reserve 5 digits for a number.
setw(5);
cout<<123;
Output : 1 2 3

2. Setting precision for float nos :


• We can control number of digits to be displayed after decimal point for float
numbers by using setprecision() function.
• setprecision(2);
• This function will display only two digits after a decimal point.
• For example :
setprecision(2);
cout<<3.14159;
Output : 3.14
3. Filling of unused positions :
• Filling of unused positions of the field can be done by using setfill().
• setfill(“*”);
• Here, unused positions will be filled by using * sign.
• setw(5);
setfill(‘$’);
cout<<123; $ $ 1 2 3
• Output :
4. setbase() :
• It is used to show the base of a number , for example :
setbase(10);
• It shows that all numbers are decimal numbers.
1----------------------1
2----------------------4
3----------------------9
4----------------------16
Let justify
flags should be set
setf(arg1, arg2);

From where which type of flat


5. Flags :-
• C++ defines some format flags for standard input and output, which
can be manipulated with the flags(), setf() and unsetf() functions.
• The flags() function either return the format flags for the current
stream or sets the flags for the current stream to be f.
• Syntax : fmtflags flags();
Formatfmtflags
required flags(fmtflags
flag(arg1)f) ; Bit field(arg2)
Left justified output ios::left ios::adjustfield
Right justified output ios::right ios::adjustfield
Scientific notation ios::scientific ios::floatfield
trignometrc-sin,cos
Fixed point notation ios::fixed ios::floatfield
Decimal base ios::dec ios::basefield
Octal base ios::oct ios::basefield
Hexadecimal base ios::hex ios::basefield
6. setf() and unsetf() :
• Setf() function can also be used with only one argument.
• Argument will be as follows :
arg1 Use
ios::showcase It helps to use base indicator an output.
ios::uppercase It helps to use uppercase letters.
ios::skipws It skips (blank) white spaces from input
ios::showpoint() It helps to display trailing zeros.
ios::showpos() It helps to display +sign for number.

• The function unsetf() is used to clear the given flags associated


with the current system.
• Syntax : void unsetf(fmtflags flags);
7. endl :
• This manipulator used in an output statement, causes a linefeed to be
inserted.
• It has the same effect as using the new line character “\n” .
• For example :
cout<<“a=”<<a<<endl
<<“b=”<<b<<endl
<<“c=”<<c<<endl;
• If we assume value of variable as 2215, 181 and 17 the output will :
a= 2 2 1 5

b= 1 8 1

c= 1 7
• Program :Program to display student data.
#include<iostream.h>
void student:: read_data()
using namespace std; {
class student int i;
cout<<“Enter student name :”;
{ cin>>name;
int marks[5]; cout<<“Enter 5 subject marks :”
int total = 0; for(i=0;i<5;i++)
{
char name[20]; cin>>marks[i];
public : total = total + marks[i];
}
void read_data();
void display(); }
};
void student:: display_data()
{ Output :-
cout<<“\n Name :”<<name; Enter student name : Rama
cout<<“\n Marks in 5 subjects :” ; Enter 5 subjects marks : 20
for(int i=0; i<5; i++) 50
cout<<“\t”<<marks[i]; 30
60
cout<<“Total=”<<total;
40
} Name : Rama
int main() Marks in 5subjects : 20 50 30 60
{ 40
student s; Total = 200
s.read_data();
s.display_data();
return 0;
}
• Program : Program to declare class account having data members
principle,rate_of_interest, no_of_years. Accept this data for one object and find out
simple interest.
#include<iostream.h>
using namespace std;
class account
{
private :
int p, n, r;
float si;
public :
void getdata()
{
cout<<“Enter Principle, Rate _of_interest and number_of_years :\n ”;
cin>>p>>r>>n;
}
void calculate()
int main()
{ {
si = (p*n*r)/100; account a;
a.getdata();
} a.calculate();
void display() a.display();
return 0;
{
}
cout<<“simple Interest = ”; Output :
cout<<si; Enter Principle, Rate_of_interest and
number_of_years :
} 5400 12 5
}; Simple Interest : 3240
• Program: Program to declare a class rectangle having data members length
and breadth. Accept this data for one object and display area and perimeter
of rectangle.
void rectangle::accept()
#include<iostream.h> {
cout<<“Enter length and breadth :”;
using namespace std; cin>>len>>bred;
Class rectangle }
void rectangle::calculate()
{ {
private : area = len * bred;
peri = 2*(len + bred);
int len,bred,area,peri; }
public : void rectangle::display()
{
void accept(); cout<<“Area of rectangle :”<<area;
void calculate(); cout<<“\n Perimeter of
Rectangle :”<<peri;
void display(); }
};
int main()
{ Output :-
Enter length and breadth : 9 5
rectangle r1; Area of rectangle : 45
r1.accept(); Perimeter of Rectangle :28
r1.calculate();
r1.display();
return 0;
}
• Program : Program to declare a class book having data members as title
and author. Accept this data for five books and display this accepted data.
Void book :: accept()
#include<iostream.h> {
cout<<“Enter Title of the book :”<<endl;
using namespace std; cin>>title;
cout<<“\n Enter author name :”<<endl;
class book cin>>auth;
{ }
void book::display()
private : {
cout<<“Book Name :”<<title;
char auth[20]; cout<<“\n Author :” << auth;
}
char title[50]; int main()
public : {
int i;
void accept(); for(i=0;i<5;i++)
{
void display(); b[i].accept();
b[i].display();
}b[2]; }
return 0;
}
• Program to display book information using class object.
#include<iostream.h>
using namespace std; void book :: getdata()
class book
{
cout<<“Enter Book number :”;
{
cin>>bookno;
int bookno; cout<<“Enter book name :”;
char bookname[20]; cin>>nbookname;
char author[20] ; cout<<“Enter Author name :”;
float price; cin>>author;
public : cout<<“Enter Book Price”;
void getdata(); cin>>price;
void display(); }
};
void book::display() Output :
{ Book number : 2504
Book name : C++
cout<<“Book number :”<<bookno<<endl; Author : Bharambe
Price : 120.29 Rs.
cout<<“Book name :”<<bookname<<endl;
cout<<“Author :”<<author<<endl;
cout<<“Price”<<price<<endl;
}
int main()
{
book b;
b.getdata();
b.display();
}
Type Casting Explicit Type Casting or Explicit Type Conversion
Implicit Type Casting or Implicit Type Conversion It is also known as the manual type casting in a program.
It is manually cast by the programmer or user to change from
It is known as the automatic type casting. one data type to another type in a program. It means a user
It automatically converted from one data type to another can easily cast one data to another according to the
without any external intervention such as programmer or user. requirement in a program.
It means the compiler automatically converts one data type to It does not require checking the compatibility of the variables.
another. In this casting, we can upgrade or downgrade the data type of
All data type is automatically upgraded to the largest type one variable to another in a program.
without losing any information. It uses the cast () operator to change the type of a variable.
It can only apply in a program if both variables are compatible
with each other. Syntax of the explicit type casting
int main () (type) expression;
{
short x = 200; int num;
int y; num = (int) 4.534; // cast into int data type
y = x; cout << num;
cout << " Implicit Type Casting " << endl;
cout << " The value of x: " << x << endl;
cout << " The value of y: " << y << endl;
}
int main ()
{
// declaration of the variables
int a, b;
float res;
a = 21;
b = 5;
cout << " Implicit Type Casting: " << endl;
cout << " Result: " << a / b << endl; // it loses some
information

cout << " \n Explicit Type Casting: " << endl;


// use cast () operator to convert int data to float
res = (float) 21 / 5;
cout << " The value of float variable (res): " << res << endl;

return 0;
}
Manipulators are helping functions that can modify the • ends: It is also defined in ostream and it inserts a null
input/output stream. It does not mean that we change the character into the output stream. It typically works with
value of a variable, it only modifies the I/O stream using std::ostrstream, when the associated output buffer needs to
insertion (<<) and extraction (>>) operators. be null-terminated to be processed as a C string.
• flush: It is also defined in ostream and it flushes the output
Manipulators are special functions that can be included in the stream, i.e. it forces all the output written on the screen or
I/O statement to alter the format parameters of a stream. in the file. Without flush, the output would be the same, but
Manipulators are operators that are used to format the data may not appear in real-time.
display.
To access manipulators, the file iomanip.h should be included in
the program.
Types of Manipulators There are various types of
manipulators:
Manipulators without arguments: The most important
manipulators defined by the IOStream library are provided
below.
• endl: It is defined in ostream. It is used to enter a new
line and after entering a new line it flushes (i.e. it forces
all the output written on the screen or in the file) the
output stream.
• ws: It is defined in istream and is used to ignore the
whitespaces in the string sequence.
Manipulators with Arguments: Some of the manipulators are setw () is a function in Manipulators in C++:
used with the argument like setw (20), setfill (‘*’), and many The setw() function is an output manipulator that
more. These all are defined in the header file. If we want to use inserts whitespace between two variables. You must enter
these manipulators then we must include this header file in our an integer value equal to the needed space.
program. For Example, you can use following manipulators to Syntax:
set minimum width and fill the empty space with any character setw ( int n)
you want: std::cout << std::setw (6) << std::setfill (’*’); As an example,
Some important manipulators in <iomanip> are: int a=15; int b=20;
• setw (val): It is used to set the field width in output cout << setw(10) << a << setw(10) << b << endl;
operations.
• setfill (c): It is used to fill the character ‘c’ on output stream. setfill() is a function in Manipulators in C++:
• setprecision (val): It sets val as the new value for the It replaces setw(whitespaces )’s with a different character. It’s
precision of floating-point values. similar to setw() in that it manipulates output, but the only
• setbase(val): It is used to set the numeric base value for parameter required is a single character.
numeric values. Syntax:
• setiosflags(flag): It is used to set the format flags specified setfill(char ch)
by parameter mask. Example:
• resetiosflags(m): It is used to reset the format flags specified int a,b;
by parameter mask. a=15; b=20;
cout<< setfill(‘*’) << endl;
cout << setw(5) << a << setw(5) << a << endl;
setprecision() is a function in Manipulators in C++:
It is an output manipulator that controls the number of digits to Reference Variable :- Example
display after the decimal for a floating point integer.
Syntax: #include <iostream>
setprecision (int p) using namespace std;
Example:
float A = 1.34255; int main()
{
cout <<fixed<< setprecision(3) << A << endl; int x = 10;

setbase() is a function in Manipulators in C++: // ref is a reference to x.


The setbase() manipulator is used to change the base of a int& ref = x;
number to a different value. The following base values are
supported by the C++ language: // Value of x is now changed to 20
• hex (Hexadecimal = 16) ref = 20;
• oct (Octal = 8) cout << "x = " << x << '\n';
• dec (Decimal = 10)
// Value of x is now changed to 30
Reference Variable :- When a variable is declared as a x = 30;
reference, it becomes an alternative name for an existing cout << "ref = " << ref << '\n';
variable. A variable can be declared as a reference by putting
‘&’ in the declaration. return 0;
}
In C++, there are three access specifiers: Member function defined inside the class:-
Member function inside the class does not require to be
public - members are accessible from outside the class but declared first here we can directly define the function. class
within a program. You can set and get the value of public student
variables without any member function. { public:
};
private - members cannot be accessed (or viewed) from
outside the class. Only the class and friend functions can access int rollno;
private members. char name[20]; char class[20];
char branch[20]; //Data Members
protected - members cannot be accessed from outside the
class, however, they can be accessed in inherited classes. void getdata() //Member Function defined inside the clas
{
Defining Member Functions:- cout<<”enter rollno”; cin>>rollno; cout<<”enter name”;
Member functions are the functions, which have their cin>>name; cout<<”enter branch”; cin>>branch;
declaration inside the class definition and works on the data }
members of that class. The definition of member functions can
be inside or outside the definition of class. If the member
function is defined inside the class definition it can be defined
directly, but if its defined outside the class, then we have to use
the scope resolution operator along with class name along with
function name.
Member function defined outside the class:-
The syntax for declaring an array of objects is
In this case we must first declare the function inside the class
class_name array_name [size];
and then define the function outside the class using scope
resolution operator. Defining a Namespace:
class student A namespace definition begins with the keyword namespace
{ public: followed by the namespace name as follows:
}; namespace namespace_name
int rollno; {
char name[20]; char class[20]; // code declarations i.e. variable (int a;)
char branch[20]; //Data Members method (void add();)
void getdata(); void putdata(); classes ( class student{};)
void student::getdata() // Use of scope resolution }
operator Example, you might be writing some code that has a function
{ called xyz() and there is another library available which is also
cout<<”enter rollno”; cin>>rollno; cout<<”enter name”; having same function xyz(). Now the compiler has no way of
cin>>name; cout<<”enter branch”; cin>>branch; knowing which version of xyz() function you are referring to
} within your code.
Array of Objects: - A namespace is designed to overcome this difficulty and is used
Like array of other user-defined data types, an array of type as additional information to differentiate similar functions,
class can also be created. The array of type class contains the classes, variables etc. with the same name available in different
objects of the class as its individual elements. Thus, an array of libraries.
a class type is also known as an array of objects. An array of The best example of namespace scope is the C++ standard
objects is declared in the same way as an array of any built-in library (std) where all the classes, methods and templates are
data type. declared. Hence while writing a C++ program we usually
include the directive using namespace std;
ios class is topmost class in the stream classes hierarchy. It is
the base class for istream, ostream, and streambuf class.

istream and ostream serves the base classes for iostream class.
The class istream is used for input and ostream for the output.

Class ios is indirectly inherited to iostream class using istream


and ostream. To avoid the duplicity of data and member
functions of ios class, it is declared as virtual base class when
inheriting in istream and ostream as

class istream: virtual public ios


{
};
class ostream: virtual public ios
{
};
The ios class: The ios class is responsible for providing all input
and output facilities to all other stream classes.
The istream class: This class is responsible for handling input
stream. It provides number of function for handling chars,
strings and objects such as get, getline, read, ignore,
putback etc..

You might also like