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

C++ notes unit 3

The document provides an overview of derived data types in C++, specifically focusing on arrays, strings, and pointers. It explains the structure, declaration, initialization, and manipulation of single-dimensional and multi-dimensional arrays, as well as string operations and pointer usage. Additionally, it covers various advantages and disadvantages of arrays, along with examples and syntax for each concept discussed.

Uploaded by

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

C++ notes unit 3

The document provides an overview of derived data types in C++, specifically focusing on arrays, strings, and pointers. It explains the structure, declaration, initialization, and manipulation of single-dimensional and multi-dimensional arrays, as well as string operations and pointer usage. Additionally, it covers various advantages and disadvantages of arrays, along with examples and syntax for each concept discussed.

Uploaded by

ashwini m
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Unit III C++

Derived data types: The data-types that are derived from the primitive or built-in
data types. Array, String and Pointer are the derived data types.

Array:
A collection of related data items of similar data type stored in contiguous
memory locations.
 Elements of an array can be accessed using their indices.
 Indexing of an array starts from 0. It means the first element is stored at the
0th index, the second at 1st, and so on.
 Once an array is declared its size remains constant throughout the program.
 An array can have multiple dimensions.

Advantages:
o Code Optimization (less code)
o Random Access
o Easy to traverse data
o Easy to manipulate data
o Easy to sort data.

Disadvantages:
o Fixed size

Array types:
1. Single Dimensional Array
2. Multidimensional Array

Single Dimensional(1-D) array: An array with only one subscript is termed as


one-dimensional array or 1-D array. It is used to store list of values. All share a
common name (1-d array name) and are distinguishable by subscript values.

Declaration of One-dimensional Arrays:


Syntax:
data-type variable-name[size];

Where, data-type refers to any basic data type, variable-name refers to


array name and it identifier, size no. of data items.

Example:
int Arr[5];

Priya M R 1
Unit III C++
Here, Arr is declared to be an array of int type and of size five. Five contiguous
memory locations get allocated as shown below to store five integer values.

Each data item in the array Arr is identified by the array name followed by pair
of square brackets enclosing a subscript value. The subscript value ranges from 0
to 4, i.e., Arr[0] denotes first data item Arr[1] denotes second data item and so
on. Arr[4] denotes the last data item.

Initialization of One-dimensional Arrays:


Syntax:
data-type variable-name[size] = {value0, valuel, value2, . .};

where, data-type refers to the data type of the array elements. variable-name refers
to the name of the array. {value0, valuel,..., valuesize-1} are constant values. The
values {value0, valuel,..., valuesize-1} are called initializer-list for the array.

Example:
int a [5] = { 2, 5, 6, 8, 9 };

Memory locations of a get filled up as follows:

Example program:
#include<iostream>
Using namespace std;
int main (void)
{
int a [5]={2,5,6,8,9}, i;
cout << "The values in the array are: \n";
for (i = 0; i < 5; i++)
cout << "a[" << i << "] = " << a[i] << endl;
return 0;
}

Priya M R 2
Unit III C++
Output:
The values in the array are
a[0] = 2
a[l] = 5
a[2]= 6
a[3] = 8
a[4] = 9

Multidimensional Arrays:
An array with more than one subscript is called a multidimensional
array.
Example: arrays of two dimensions (2-d arrays), arrays of three dimensions (3-d
arrays), arrays of four dimensions (4-d arrays) and so on.

Two-dimensional Arrays (2-D arrays)


An array with two subscripts is termed as two-dimensional array. A
two-dimensional array enables us to store multiple rows of elements, in a table of
values or a matrix format.

Declaration of two-dimensional arrays:


Syntax:
data-t ype variable-name[rowsize][colsize];

Where, data-type refers to any valid data type, variable-name refers to the
valid identifier, rowsize indicates the no. of rows and colsize indicates the no. of
elements in each row.
rowsize and colsize should be integer constants. Total no. of locations
allocated will be equal to rowsize * colsize.
Each element in a 2-d array is identified by the array name followed by a
pair of square brackets enclosing its row-number, followed by a pair of square
brackets enclosing its column-number. Row-number ranges from 0 to rowsize – 1
and column-number ranges from 0 to colsize – 1.

Example:
int b[3] [3];

‘b’ is declared to be an array of two dimensions and of data type int. rowsize
is 3 and colsize is 3. Memory representation of ‘b’ array.
.

Priya M R 3
Unit III C++

Each data item in the array ‘b’ is identifiable by specifying the array name
‘b’ followed by a pair of square brackets enclosing row number, followed by a
pair of square brackets enclosing column number.
b[0] [0] refers to data item in the first row and first column.
b[0] [1] refers to data item in the first row and second column.
b[2] [2] refers to data item in the third row and third column.
b[2] [0] refers to data item in the third row and first column.

Initialization of two-dimensional arrays:


Syntax:
data-type variable-name [rowsize] [colsize]={initializer-list};

Where, data-type refers to any basic data type. variable-name refers to array
name. rowsize indicates the no. of rows, colsize indicates the no. of columns of the
array. initializer-list is a comma separated list of values of type data-type or
compatible with data-type.
If the no. of values in initializer-list is equal to the product of rowsize and
colsize. The first rowsize values in the initializer-list will be assigned to the first
row, the second rowsize values will be assigned to the second row of the array and
so on.

Example:
int matrix[2][3]={10,20,30,40,50,60};

Since colsize is 3, the first 3 values of the initializer-list are assigned to the
first row and the next values are assigned to the second row.
10 20 30
40 50 60

We can also initialize like:


int matrix[2][3]={{10,20,30},
{40,50,60}};

int matrix[2][3]={{10,20,30},{40,50,60}};

Priya M R 4
Unit III C++
Example program:
#include<iostream>
using namespace std;
int main ()
{
int a[2][2] = { 1, 2, 3 , 4 } ;
int i, j;
cout << "Matrix a: \n";
for (i= 0 ; i < 2; i++)
{
for (j =0; j < 2; j++)
cout <<"\t" << a[i][j];
cout << "\n ";
}
return 0;
}

Output:
Matrix a:
12
34

Three-dimensional (3-D) array:


An array with three subscripts is called as Three dimensional array. It
enables to form a group of tables.

Declaration of Three-dimensional (3-D) array:


Syntax:
data-type variable-name[size1][size2][size3];
Where, data-type refers to any basic data type. variable-name refers to array
name. size1 indicates the no. of tables, size2 indicates the no. of rows, size3
indicates the no. of columns of the array.

Example:
int a[2][2][3];
‘a’ is declared to be a 3-d array. It can accommodate two tables of values, each
table having two rows and three columns. Each element in the array is identified by
the array name ‘a’, as follows:
a[0][0][0] indicates data item in first table, first row, first column.
a[1][0][0] indicates data item in second table, first row, first column.
a[1][1][2] indicates data item in second table, second row, third column.

Priya M R 5
Unit III C++
Initialization of Three-dimensional (3-D) array:
int b[2] [2] [2] = {{{1,2},{3,4}},{{5,6},{7,8}}};

Output:
Table1
12
34

Table2
56
78

String:
A sequence of characters terminated by the special character ’\0’.

Declaration of string:
char s[20];

Variable ‘s’ is a character type, which holds 20 characters.

Initialize of string:
Example1:
char strl[5] = {'a', 's', 'd', 'f', '\0'};

Here, strl is declared to be a string variable with size five. The initializer-list
consists of comma separated character constants. Null character '\0 is explicitly
listed.

Example2:
char str2[5]= {"asdf"};

Here, str2 is also declared to be a string variable of size five. The initializer-
list consists of a string constant. Null character '\0' will be automatically appended
to the end of string by the compiler.

Example program:
#include <iostream>
using namespace std;
int main ()
{
char s1[10], s2[10]={"Welcome"};
cout << "Enter a string into s1\n";

Priya M R 6
Unit III C++
cin >> s1;
cout << "s1 = " << s1 << "\n";
cout << "s2 = "<<s2;
return 0;
}

String Manipulations:
The most commonly performed operations over strings are
1. Finding the length of a string
2. Copying one string to another string
3. Concatenation of two strings
4. Comparing two strings
5. Searching substring in a string
String manipulation built-in functions are declared in the header file
string.h.
Finding the length of a string:
strlen(): it is used to find length of a string. It defines no. of characters
excluding the null character \0.
The prototype of strlen () is as follows:
int strlen (s );

Argument ‘s’ represents a string. It can be a string constant or a string variable.


The function returns an integer value, which is the length of the string.

Example:
char s[20] = { "Welcome to India" };
int l;
l = strlen(s);

‘l’ collects the length of s. ‘l’ has 16.

Copying one string to another string:


Strcpy(s1,s2): This method make a copy of string s2 to string s1.

The prototype of strcpy( ) is as follows:

strcpy(s1,s2);

Copies string contained in sl to s2. sl can be string constant or a string variable.


But s2 should be a string variable and it should be large enough to collect the string
in sl.
Priya M R 7
Unit III C++
Example:
chat sl[20]= {"abcd"}, s2[20] ;
strcpy (s2,sl);

As a result of this, sl gets copied to s2. s2 now contains "abcd".

strcpy (s1, "XYZ");

Here the string constant "XYZ" gets copied to sl. sl now contains "XYZ".

Comparing two strings:


strcmp(s1,s2): This method is used to compare two strings.

The prototype of strcmp() is as follows:


int strcmp (sl, s2);

sl and s2 represent two strings being compared. s1 and s2 can be a string


constant or a string variable. The function returns the numerical difference
between the first non-matching pair of characters of sl and s2.
It returns a:
 Positive value when sl is alphabetically greater than s2.
 Negative value when sl is alphabetically lower than s2.
 Zero ‘0’ when sl and s2 are equal.

Example1:
char s1[20]={ "abc"}, s2[20]={ "aac"};
int i;
i = strcmp (sl, s2);

i gets 1 since the numerical difference between the first non-matching


pair 'b' of s1 and 'a' of s2 is 1.

Example2:
char sl[20]={"aac"}, s2[20]={"abc"}:
int i;
i = strcmp (s1, s2);

i gets -1 since the numerical difference between the first non-matching


pair 'a' of s1 and 'b' of s2 is 1.

Priya M R 8
Unit III C++
Example3:
char sl[20]={"abc"}, s2[20]={"abc"}:
int i;
i = strcmp (s1, s2);

i gets ‘0’ since both string s1 and s2 values are equal.

Concatenation of two strings:


strcat(sl, s2): this method is used to combine values of two strings.

The process of appending one string to the end of another string is called
concatenation of two strings.

The prototype of strcat( ) is as follows:


strcat(sl, s2);

Appends s2 to sl. s2 can be a string variable or a string constant. But s1


should be a string variable and the size of sl should be large enough to store the
concatenated string.

Example:
char sl[10] = {"abc"}, s2[10] = {"xyz"}:
strcat (sl, s2) ;
now s1 value is "abcxyz".

Searching substring in a string:

strstr(str1, str2): Returns a pointer to the first occurrence of string str2 in


string str1. The default value of starting position is 0.

Syntax:
char *strstr (const char *s1, const char *s2);

where, s1 is the main string to be examined. s2 is the sub-string to be


searched in string.
It returns a pointer point to the first character of the found s2 in s1 otherwise
a null pointer if s2 is not present in s1.

Priya M R 9
Unit III C++
Example:
char sl[10] = {"Object Oriented"}, s2[10] = {"Or"};
int p=strstr (sl, s2) ;

In this example, string is found, now p variable is 7.

Pointer:
Pointer is a variable, it is also known as locator or indicator that points to an
address of another variable.

Declaration of pointer variable:


Syntax:
data-type *var_name;

Where, data-type can be any basic data-type, var_name is a pointer variable


name. Asterisk(*) is used to declare a variable as a pointer.

Example:
int *ptr;

‘ptr’ is declared to be a pointer variable of int type.

Pointer operators: two special operators known as pointer operators. They are &
and *.
& stands for ‘Address of’ and it is used retrieve the address of a variable.
* stands for 'value at address’ and it is used to access the value at a location
by means of its address. Asterisk(*) is called as dereference operator.

Example:
int number=30;
int ∗p;
p=&number;

Pointer ‘P’ stores the address of number variable. The pointer variable and the
referring variable data type should be same.

Priya M R 10
Unit III C++
Example Program:
#include <iostream>
using namespace std;
int main()
{
int number=30;
int ∗p;
p=&number; //stores the address of number variable
cout<<"Address of number variable is:"<<&number<<endl;
cout<<"Address of p variable is:"<<p<<endl;
cout<<"Value of p variable is:"<<*p<<endl;
return 0;
}

Output:
Address of number variable is: 0x7ffccc8724c4
Address of p variable is: 0x7ffccc8724c4
Value of p variable is: 30

Pointer Arithmetic
Pointer arithmetic operators are:
1. Incrementing and Decrementing Pointers
2. Addition of Constant to Pointers
3. Subtraction of Constant from Pointers
4. Subtraction of Two Pointers of the Same Type
5. Comparison of Pointers
6. Assigning one pointer to another pointer.

o Incrementing and Decrementing Pointers


Incrementing the pointer:
Example: ptr++
1. if ptr is an integer pointer which points to the address 1000. If the
size of the integer is 4 bytes, then the ptr will point to the location
1004 because each time ptr is incremented, it will point to the next
integer. This operation will move the pointer to next memory
location without impacting actual value at the memory location.
2. If ptr points to a character whose address is 1000, then pointer point
to the location 1001 because next character will be available at 1001.

Priya M R 11
Unit III C++

Decrementing the pointer:


Example: ptr--
1. if ptr is an integer pointer which points to the address 1000. If the
size of the integer is 4 bytes, then the pointer will be decremented by
4, and the pointer will now hold the address 996.
2. If ptr points to a character whose address is 1000, after pointer
decrement, pointer point to the location 999.

o Addition of Constant to Pointers


We can add integer values to Pointers and the pointer is adjusted
based on the size of the data type it points to.
For example, if an integer pointer (ptr) stores the address 1000 and
we add the value 5 to the pointer, it will store the new address as:
ptr + 5

1000 + (5 * 4(size of an integer)) = 1020

o Subtraction of Constant from Pointers


We can subtract a constant from Pointers.
For example, if an integer pointer (ptr) stores the address 1000 and we
subtract the value 5 from the pointer, it will store the new address as:

Priya M R 12
Unit III C++
ptr - 5

1000 - (5 * 4(size of an integer)) = 980

o Subtraction of Two Pointers of the Same Datatype


The Subtraction of two pointers can be done only when both pointers
are of the same data type. The subtraction of two pointers gives the number
of elements present between the two pointers.

Example:
int x = 5, y = 7;
int *p = &y;
int *q = &x;
p - q;

if ‘p’ is stored in memory location 1000 and ‘q’ is stored in memory


location 1004, then p - q = -4, this will subtract the address.

o Comparison of Pointers
We can perform a comparison between the two pointers using the
relational operators(>, <, >=, <=, ==, !=). We generally use this operation
to check whether the two-pointer as pointing to the same memory location
or not.

Example:
int arr[5];
// declaring pointer to array name
int *ptr1 = &arr;
// declaring pointer to first element
int *ptr2 = &arr[0];
ptr1 == ptr2; // Both point to same memory location
Priya M R 13
Unit III C++
o Assigning one pointer to another pointer.
Example:
int n=10; // a variable
int *ptr1= &n; // a pointer to that variable
int *ptr2; // another pointer

ptr2=ptr1;

Pointer ptr1 assigning to pointer ptr2. Both pointers pointing to the same
location.

Managing Console I/O Operations

C++ stream:
A stream is a sequence of bytes. It 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.
The source stream that provides data to the program is called the input
stream and the destination stream that receives output from the program is called
the output stream as shown in figure.

Fig: Data streams

C++ stream classes:


o The C++ I/O system contains a hierarchy of classes that are used to define
various streams to deal with both the console and disk files.
o These classes are called stream classes.
o These classes are declared in the header file iostream.

Priya M R 14
Unit III C++

Fig: Stream classes for console /O operations

As in figure above ios is the base class for istream(input stream) and
ostream(output stream) which are base classes for iostream(input/output stream).The class ios is
declared as the virtual base class so that only one copy of its members are inherited by
the iostream.
The class ios provides the basic support for formatted and unformatted
input/output operations.The class istream provides the facilities for formatted and unformatted
input while the class ostream(through inheritance) provides the facilities for formatted output.
The class iostream provides the facilities for handling both input output streams.Three
classes namely istream_withassign, ostream_withassign and iostream_withassign add assignment
operators to these classes.
Stream classes for console operations:

Priya M R 15
Unit III C++
Unformatted I/O Operations: Unformatted I/O is used to read and write data as a
stream of bytes without any format.
Unformatted I/O Operations are:
1. cin and cout
2. get( ) and put( )
3. getline( ) and write( )

cin and cout:


cout: The cout object is an ostream class predefined object. It is connected to the
standard output device, which is usually a display screen. The cout is used in
combination with the stream insertion operator (<<) to show the output on a
console.
Syntax: cout used to display statement
cout <<″string″;
Statement mentioned in double quotes is displayed on screen.

cout used to display variable value:


cout << iteml <<item2 <<....<< itemN;
The items item1 through itemN may be variables or constants of any basic
type.

Example:
int x=10;
cout<<″Welcome″; // display Welcome on screen
cout<<″x=″<<x; // display x=10 on screen

cin: The cin is a predefined object of istream class. It is connected with the
standard input device, which is usually a keyboard. The cin is used in
combination with stream extraction operator (>>) to read the input from a
console.
Syntax:
cin >> variable1>>variable 2>>…..>> variableN;

variable1, variable2. ...are valid C++ variable names that have been declared
already. This statement will cause the computer to stop the execution and read
input data from the keyboard.

The operator >> reads the data character by character and assigns it to the
indicated location. The reading for a variable will be terminated at the encounter of
a white space character.

Priya M R 16
Unit III C++
Example:
int code;
cin >> code;

Data is given as input:


42580
The operator will read the characters upto 8 and the value 4258 is assigned to code

Example program:
#include <iostream>
using namespace std;

int main()
{
int x;
cout << "Enter x value:" << endl;
cin>>x;
cout<<"x="<<x;
return 0;
}

Output:
Enter x value: 100
x=100

get( ) and put( ):


get( ): get() is a member function of istream class. It is used to read single
character from keyboard.
There are two types of get() functions:
get(char *) and get(void)
prototype can be used to fetch a character including the blank space, tab and
newline character.
The get(char *) version assigns the input character to its argument.
The get(void) version returns the input character.
Since this function is member of input Stream classes, these must be invoked using
cin object.

Priya M R 17
Unit III C++
Example:
The get(char) version is used as follows
char c;
cin.get( c ); //get a character from the keyboard and assigns it to ‘c’.

The get(void) version is used as follows


char c;
c= cin.get();

The value returned by the function get() is assigned to the variable c.

put(): The function put() is a member of ostream class. It is used to read single
character. Since this function is member of output Stream classes, these must be
invoked using cout object.
Example:
cout.put(‘x’);
displays the character x and
cout.put(ch);
displays the value of variable ch.

Example program:
#include <iostream.h>
using namespace std;
int main()
{
char c;
cout<<”Enter a character: \n”;
cin.get(c);
cout<<”Character is:\n”;
cout.put(c);
return 0;
}

Priya M R 18
Unit III C++
getline() and write() functions
getline(): The getline() function reads a whole line of text that ends with a newline
character. This function can be invoked by using the object cin as follows:
Syntax:
cin.getline(line,size);
This function call invokes the function getline() which reads character input
into the variable line. The reading is terminated as soon as either the newline
character ‘\n’ is encountered or size-1 characters are read. The newline character is
read but not saved. Instead it is replaced by the null character.

For example consider the following code:


char name[20];
cin.getline(name,20);

Assume that we have given the following input through key board:
Object Oriented
This input will be read and assigned to the character array name.

Write(): The write() function displays an entire line.


Syntax:
cout.write(line,size)
The first argument line represents the name of the string to be displayed and
the second argument size indicates the number of characters automatically when
the null character is encountered. If the size is greater than the length of line, then
it displays beyond the bound of line.
Example:
char line[30]={″Object Oriented Programming″};
cout.write(line,30);

Output:
Object Oriented Programming

Example program:
int main()
{
int size = 20;
char city[20];
cout<< "Enter city name: \n";
cin.getline (city, size);
cout << "City name is: ";
cin.getline(city, size);
return 0;}

Priya M R 19
Unit III C++
Formatted I/O Operations: Formatted I/O operations involve reading or writing
data in a specific format.
Different ways of formatting the output are:
1. ios class functions and flags.
2. Manipulators

ios class functions and flags:


The ios class contains a large number of member functions and flags that
helps to format the output in a number of ways .
ios format functions are:
1. width()
2. precision()
3. fill()
4. setf()
5. unsetf()
1. width(): This method is used to specify field size for displaying an output
value.
Syntax:
cout.width (w);
where w is the field width (number of columns). The output will be printed in a
field of w characters wide at the right end of the field. The width() function can
specify the field width for only one item (the item that follows immediately).
After printing one item (as per the specifications) it will revert back to the
default.
Example:
cout.width (5);
cout << 543<< "\n";
Output:
5 4 3

2. precision(): The precision method is used to set the number of the decimal
point to a float value.
Syntax:
cout.precision(d);
where d is the number of digits to the right of the decimal point.
Example:
cout.precision (3);
cout << sqrt(2) << "\n";
cout << 3.14159 << "\n";
cout << 2.50032 << "\n";

Priya M R 20
Unit III C++
Output:
1.141 (truncated)
3.142 (rounded to the nearest cent)
2.5 (no trailing zeros)

3. fill(): The fill method is used to set a character to fill in the blank space of a
field.
Syntax:
cout.fill(ch);
Where ch represents the character which is used for filling the unused
positions.
Example:
cout.fil1(*);
cout.width(10);
cout << 5250 << "\n";

Output:
* * * * * * 5 2 5 0

4. setf(): The setf method is used to set various flags for formatting output. The
setf(), a member function of the ios class.
Syntax:
cout.setf(argl , arg2);

The arg1 is one of the formatting flags defined in the class ios. The
formatting flag specifies the format action required for the output.
The arg2, known as bit field specifies the group to which the formatting flag
belongs.
Table(1) shows the bit fields, flags and their format actions. There are three
bit fields and each has a group of format flags which are mutually exclusive.

Table(1): Flags and bit fields for setf() function

Priya M R 21
Unit III C++

Examples1:
cout.setf(ios::left, ios::adjustfield);
cout.setf(ios::scientific, ios::floatfield);

Example2:
cout.fi11(*);
cout.setf(ios::left, ios:: adjustfield);
cout.width(15);
cout << "TABLE 1" << "\n";

Output:
T A B L E 1 * * * * * * * *

Table(2): Flags that do not have bit fields

Example:
cout.setf(ios::showpoint); // The flags without bit fields
cout.setf(ios::showpos); // The flags without bit fields
cout.precision (3);
cout.setf (ios::fixed, ios::floatfield);
cout.setf (ios::internal, ios::adjustfield);
cout.width(10);
cout << 275.5 << "\n";

Output:
+ 2 7 5 . 5 0 0

Priya M R 22
Unit III C++
5. unsetf(): The unsetf method is used To remove the flag setting.
Syntax:
unsetf(arg1);

The arg1 specifying the flags to be cleared.

Example:
cout.setf (ios::hex, ios::basefield ); // set hex as the basefield
cout.setf (ios::showbase); // activate showbase
cout << 100 << '\n';
cout.unsetf(ios::showbase ); // deactivate showbase
cout << 100 << '\n';

Output:
0x64
64

Managing Output with Manipulators


The header file iomanip provides a set of functions called manipulators
which can be used to manipulate the output formats.
Example: two or more manipulators can be used as a chain in one statement as
shown below:
cout << manip1 << manip2 <<manip3 <<item1;
cout << manip1 << item1 <<manip2 << item2;

This kind of concatenation is useful when we want to display several


columns of output.

Table(3): Manipulators and their meaning

Note: The Definition of manipulators is same as ios class function and also flags.
Refer the same.

Priya M R 23
Unit III C++
Example1:
cout << setw(10) << 12345;

This statement prints the value 12345 right-justified in a field width of 10


characters.
1 2 3 4 5

Example2:
cout<< setw(5) << setprecision (2) << 1.2345
<<setw(10) << setprecision(4) << sqrt (2)
<<setw(15) << setiosflags (ios::scientific) << sqrt (3);
<< endl;

This will print all the three values in one line with the field sizes of 5, 10,
and 15 respectively. Each output is controlled by different sets of format
specifications.

User Defined Data Type:


Class Definition:
A class is a user-defined data type, which holds its own data members and
member functions, which can be accessed and used by creating an instance of that
class.
A class is a way to bind the data and functions together. The class
declaration describes the type and scope of its members.
Syntax:
class class-name
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};

Where, class is the keyword. The class-name is any user-defined name. The
body of a class is enclosed within braces and terminated by semicolon. The class
body contains the declaration of variables and functions. These functions and
variables are collectively are called class members.
The private class members can be accessed only from within class. Public
members can be accessed from outside the class. The default visibility mode is
private.
Priya M R 24
Unit III C++
The variables declared inside the class are known as data members and the
functions are known as member functions.

Example:
class item
{
int number;
float cost;
public:
void getdata(int a, float b);
void putdata(void);
};

Item is the class name. The class item contains two data members and two
function members. The number and cost are data members are declared as private
by default, and getdata() and putdata() functions are declared as public. The
function getdata() can be used to assign values to the member variables number
and cost, and putdata() for displaying the their values.

Instance variable:
Instance Variables are declared inside a class and are used to store values in
an object. Each object has its own copy of instance variables.
Instance variable creation, Syntax:
data-type variable-name1, variable-name2,…., variable-nameN;
Where, data-type can be any basic data-type. Variable-name can be any
valid identifier. List of variables are separated by comma.
Example: int a,b,c;
In this, variables a,b,c are declared as int type.

Example: instance variable declared inside class


class data
{
// creating instance variables
public:
char name[30];
int age;
};
int main()
{
// Creating an object x of the class data
data x,y;
return 0;
}

Priya M R 25
Unit III C++
In this example, ‘x’ and ‘y’ are objects of data class. ‘Name’ and ‘age’ are
instance variables of class data. Data members can be declared within the class as
public, private, or protected data. Each object has its own copy of instance
variables. As shown in figure below.

x y
Name Name
age age

Member Methods:
A member function in C++ is a function that is part of a class. It is used read,
manipulate, or display all types of data members of the class. Member functions are
also known as methods.
Member Functions can be declared within the class as public, private, or
protected functions.
There are mainly two ways to define Member Function in C++.
1. Definition within the Class
2. Definition outside the Class

Defining Member Function within the Class:


When a definition of function is short, we can define function within the
class. Member functions can access all the data members and other member
functions of the same class.
Syntax:
return-type function-name(parameter-list)
{
Statements;
}
Where, return-type can be any basic data-type, function-name can be any
valid identifier, parameter-list is the list of variables declaration separated by
comma or empty parameter.

Example:
class info
{
void display()
{
cout<<″Object Oriented Program″;
}
};
In this example, display() is a member function of info class. Which is define
inside the class.

Priya M R 26
Unit III C++
Defining Member Function outside the Class:
We can define the member function outside the class using the scope
resolution operator (::). While using this method we need to ensure that the
function is declared within the class.
Syntax:
return_type class_name::function_name (parameter-list)
{
// definition of the function
}

Where, return-type can be any basic data-type, class-name is name of the


class where the function is declared.
Scope resolution operator(::) indicates that this function belongs to particular
class. While defining outside the class, specifying class name is must, because
same function name can be declare or define in more than one class.
function-name can be any valid identifier, parameter-list is the list of
variables declaration separated by comma or empty parameter.

Example:
class Circle
{
int size;
public:
void printSize(int s);
};
void Circle :: printSize(int s)
{
cout<< s <<endl;
}

In this example, Circle is the class, printSize() is the member function


declared inside the class and defined outside the class.

Object:
Object is an instance of a class. All the members of the class can be accessed
through object.
A class provides the blueprints for objects, an object is created from a class.

Syntax:
class-name object-name1,object-name2,….,object-nameN;

Priya M R 27
Unit III C++
Where, class-name is name of the class which has declared previously.
Object-name is the name of any valid identifier, objects are separated by comma.
The objects listed is belongs to particular class. When the object is created memory
is allocated for the data members of particular class.

Example:
Circle C1, C2;
In this example, Circle is a class-name. C1 and C2 are the objects of Circle
class.

Accessing Members:
Accessing a data member depends on the access control (public, private and
protected) of that data member.
If it’s public, then the data member can be easily accessed using the direct
member access (.) operator with the object of that class.
If, the data member is defined as private or protected, then we cannot access
the data variables directly.

Syntax:
Object-name.member-name;

Where, object-name is name of the created object. Member-name can be


data members name or member functions name of the particular class.

Example:
data d1;
d1.x=10;
d1.set(10,20);

In this example, d1 is the object of data class. ‘x’ is the data member of data class.
set() function is the member function of data class. These data members are
accessed using object name and dot(.) operator.

Example:
class data
{
public:
int x,y;
void set(int x1,int y1) //function define inside the class
{
x=x1;
y=y1;
}
Priya M R 28
Unit III C++
void display( ); // function declaration
};
void data::display( ) // function defined outside the class
{
cout<<″x=″<<x<<endl;
cout<<″y=″<<y<<endl;
}

int main()
{
data d1,d2; // Creating an object x and y of the class data
d1.set(10,20); //Accessing the member function
d2.x=100; //Accessing the data member
d2.y=200;
d1.display( );
d2.display( );

return 0;
}

Access specifiers
Access specifiers or Access Modifiers in a class are used to assign the accessibility to the
class members, i.e., they set some restrictions on the class members. There are three access
specifiers:
1. Public
2. Private
3. Protected.

Inside the class all these access specifier can be used, the keywords and followed by colon.

1. Public access specifier:


The public access specifier is used to specify that a class member can be
accessed from anywhere, both inside and outside the class. This means that any
function or object can access the public members of the class. The public
members of a class are typically used to represent the interface of the class.
Example program:
#include<iostream>
using namespace std;

class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
Priya M R 29
Unit III C++
}
};
int main()
{
Circle obj;
obj.radius = 5.5;

cout << "Radius is: " << obj.radius << "\n";


cout << "Area is: " << obj.compute_area();
return 0;
}

Output:
Radius is: 5.5
Area is: 94.985

In the above program, the data member radius and function compute_area() is
declared as public so it could be accessed anywhere and thus was allowed
access from inside main() using object name with the direct member access
operator (.).

2. Private access specifier:


The class members declared as private can be accessed only by the member
functions inside the class. They are not allowed to be accessed directly by any
object or function outside the class. Only the member functions or the friend
functions/ friend class are allowed to access the private data members of the
class.
By default, all members of a class are private if we don't specify an access
specifier.
Example program:
#include<iostream>
using namespace std;

class Circle
{
// private data member
private:
double radius =1.5;

// public member function


public:
double compute_area()
Priya M R 30
Unit III C++
{ // member function can access private
// data member radius
return 3.14*radius*radius;
}

};
// main function
int main()
{
// creating object of the class
Circle obj;
cout << "Area is:" << obj.compute_area();
return 0;
}

Output:
Area is: 7.065

In this program, radius is a private variable, we cannot access inside main() like
Obj.radius=1.5;
Will get error.

3. Protected access specifier:


The protected access specifier is used to specify that a class member can be
accessed from within the class and its derived classes. This means that any
function or object outside the class hierarchy cannot access the protected
members of the class.
Example program:
#include <iostream>
using namespace std;
// base class
class Parent
{
// protected data members
protected:
int id_protected;

};

Priya M R 31
Unit III C++
// sub class or derived class from public base class
class Child : public Parent
{
public:
void setId(int id)
{
// Child class is able to access the inherited
// protected data members of base class
id_protected = id;
}
void displayId()
{
cout << "id_protected is: " << id_protected << endl;
}
};
int main()
{
Child obj1;
obj1.setId(81);
obj1.displayId();
return 0;
}

Output:
id_protected is: 81

In this program, id_protected is declared as protected access specifier in


the base class, it is access directly in derived class.

Table1: Accessibility of members

Priya M R 32
Unit III C++
this pointer
this is a keyword that refers to the current instance of the class. Usages of
this keyword are:
 It can be used to pass current object as a parameter to another method.
 It can be used to refer current class instance variable.
 It can be used to declare indexers.

Syntax:
this->members;

Where, this is the keyword, it is an implicit pointer. To access members of the


class through pointer we need to use ->(arrow).
->(arrow) is the member selection operators, used to access members of a
class. Members are data members of the class.

Example:
this->x;

Here, this is the keyword which points to current object. ‘x’ is the data member of
the class.

Example program:
#include<iostream>
using namespace std;

/* local variable is same as a member's name */


class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print()
{
cout << "x = " << x << endl;
}
};

Priya M R 33
Unit III C++
int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}

Output:
x = 20

In this program, this->x represents to current object obj.

Friend function
 It is used to access all private and protected members of the class.
 It is a non-member function or ordinary function of a class.
 A friend function of a class is declared inside the class and defined outside
that class.
 They are declared using the keywords friends.

Syntax:
function declared inside the class:
friend return_type function_name (arguments);

Where, friend is the keyword, return-type is any basic type, function-


name can be any valid identifier, and argument should be object.

function define outside the class:


return_type function_name (arguments)
{
}

To define friend function outside the class, no need to specify the friend
keyword, class name and scope resolution operator (::). Like normal
function we can define friend function.

Priya M R 34
Unit III C++
Characteristics of a Friend function:
 The function is not in the scope of the class to which it has been declared
as a friend.
 It cannot be called using the object as it is not in the scope of that class.
 It can be invoked like a normal function without using the object.
 It cannot access the member names directly and has to use an object name
and dot membership operator with the member name.
 It can be declared either in the private or the public part.

Example program:
#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box()
{ length=0;}
friend int printLength(Box); //friend function
};
int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}

Output:
Length of box: 10

In this program, printLength() is a friend function, which is declared inside the


class and define outside the class. This function access the private variable
‘length’ of the class. This function contains argument ‘b’ which is an object of
Box class. Calling the friend function is like normal function.

Priya M R 35
Unit III C++
Constructor:

 It is a special method that is automatically called when an object of a class


is created.

Characteristics of Constructors:
 The name of the constructor is the same as its class name.
 Constructors are mostly declared in the public section of the class.
 Constructors do not return values.
 A constructor gets called automatically when we create the object of the
class.

Types of constructors
1. Default constructor
2. Parameterized constructor
3. Copy constructor

1. Default Constructor
A default constructor is a constructor that doesn’t take any argument.
It has no parameters. It is also called a zero-argument constructor. When the
object is created default constructor is invokes implicitly.

Syntax: Defining inside the class


className()
{
// body_of_constructor
}

Defining outside the class


className::className( )
{
// constructor definition
}

Here, classname and function name should be same, no return type and
no parameter.
Example Program:
#include <iostream>
using namespace std;
class Employee
{

Priya M R 36
Unit III C++
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main()
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}

Output:
Default Constructor Invoked
Default Constructor Invoked

In this example, Employee() is the default constructor of Employee class,


it is invoked when the object is created.

2. Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It
is used to provide different values to distinct objects.
These arguments help initialize an object when it is created.

Syntax: Defining inside the class


className(parameters…)
{
// body_of_constructor
}

Defining outside the class


className::className(parameters…)
{
// constructor definition
}

Here, classname and function name should be same, no return type and
but contains parameters.

Priya M R 37
Unit III C++
Example program:
#include <iostream>
using namespace std;
class Employee
{
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
Employee(int i, string n)
{
id = i;
name = n;
}
void display()
{
cout<<id<<" "<<name<<" "<<endl;
}
};
int main()
{
Employee e1 =Employee(101, "Sonoo"); //creating an object of Employee
Employee e2=Employee(102, "Nakul");
e1.display();
e2.display();
return 0;
}

Output:
101 Sonoo
102 Nakul

In this example, Employee() is the parameterized constructor of


Employee class, it contains ‘id’ and ‘name’ as parameters, the values is
passed and invoked when the object is created.

Priya M R 38
Unit III C++

3. Copy Constructor
A member function known as a copy constructor initializes an item using
another object from the same class

Syntax: Defining inside the class


className(ClassName &obj)
{
// body_of_constructor
}

Defining outside the class


className::className(ClassName &obj)
{
// constructor definition
}

Here, classname and function name should be same, no return type and
but contains parameters as reference to an object of the same class.

Example program:
#include <iostream>
using namespace std;
class A
{
public:
int x;
A(int a) // parameterized constructor.
{
x=a;
}
A(A &i) // copy constructor
{
x = i.x;
}
};
int main()
{
A a1(20); // Calling the parameterized constructor.
A a2(a1); // Calling the copy constructor.
cout<<a2.x;
return 0;
}
Priya M R 39
Unit III C++
Output:
20

In this example, A(A &i) is the copy constructor, which has object as
parameter. A a2(a1); is calling the copy constructor, in this passing object ‘a1’ as
parameter value.

Destructor:
Destructor is an instance member function that is invoked automatically
whenever an object is going to be destroyed.

Syntax: defining the destructor within the class:


~ class-name()
{
// some instructions
}

Characteristics of a Destructor
 A destructor is also a special member function like a constructor. Destructor
destroys the class objects created by the constructor.
 Destructor has the same name as their class name preceded by a tilde (~)
symbol.
 It is not possible to define more than one destructor.
 The destructor is only one way to destroy the object created by the constructor.
Hence, destructor cannot be overloaded.
 It cannot be declared static or const.
 Destructor neither requires any argument nor returns any value.
 It is automatically called when an object goes out of scope.
 Destructor release memory space occupied by the objects created by the
constructor.
 In destructor, objects are destroyed in the reverse of an object creation.

Example program:
#include <iostream>
using namespace std;
class Test
{
public:
// User-Defined Constructor
Test()
{
Priya M R 40
Unit III C++
cout << "\n Constructor executed";
}
// User-Defined Destructor
~Test()
{
cout << "\nDestructor executed";
}
};
main()
{
Test t;

return 0;
}

Output
Constructor executed
Destructor executed

Priya M R 41

You might also like