C++ program for student details using array of objects

Array of Objects in C++

Array of Object is similar to creating array or integer, character or any primitive data types.

Example

Array of integer is

int age[5]={1,2,3,4,5};

Similar way array of Student is

Student s[5]={studentObj1,studentObj2,studnetObj3,studentObj4,studentObj5};

Student is class Name

s is array of objects of 5 elements

To initialize student object two methods are used here

  1. Initialize student object from constructor
  2. Create a function to get input from user to initialize student object.

Example: C++ program for student details using array of objects

  1. Create a class name student
  2. Declare necessary fields for student as name,age and rollno as a private member of class.
  3. In public section create constructor to initialize value from it
  4. also create a show function to show/ print user data.

To copy local array variable name to Student class name strcpy() is used

Result

Get User Input for Student Objects

  1. create a class student
  2. declare fields of student as private data member
  3. create a function getStudent() to get input from user and assign it to student data members
  4. create a function showStudent() to show student object details to user.
  5. create a main method and define size of student object
  6. loop student object to take input from user
  7. loop student objcet to show student object details from array of object.

Output

Read More

  1. Constructor in C++
  2. Know more about C++

Categories C++

Single and Multidimensional Arrays in C++

Arrays is a kind of data structure that can store a elements of the same type.

Arrays stores the elements in a contiguous memory locations.

Array is a collection of variables of the same type.

 For example: we want to declare 100 integer variable

Instead of declaring 100 individual variables, such as

int number0, number1,number2,number3, … …., number99;

you declare one integer array variable such as

int number[100];

here number[100] is an integer array of size 100, means this array can store 100 integer value.

Array indexing starts from index 0 to n-1.

Means first integer number store in array number[0], second integer number store in array number[1], third integer number store in array number[2], and so on. Here 100th  number store in array numbers[99].

Array in Cpp
Array In C++

Declaring Arrays

Syntax of declare an array in C:

Data_type  arrayName [ arraySize ];

This is called a single-dimensional array.

The arraySize must be an integer constant greater than zero.

datatype can be any valid C data type.

Example: write a program to create integer array and store 5 integer number and print.  

Output

Array example in cpp
Element Position in Array

Description : In the above program,   “int  num[5]” array can store 5 element in a contiguous memory locations from index 0 to 4.         

Example: Write a program to take 5 number from user and store integer number in integer array and print.  

Output

Another way to Initialize Array

 We can also initialize array by this way:

int num[5] = { 54 , 4,  13,  2,  17 };

above integer array num[5], stores five numbers. Where num[0] store 54, num[1] store 4….. , & num[4] store 17.

Output

Multi-dimensional Arrays 

C++  programming language also support multidimensional arrays.

Syntax of multidimensional array declaration:

Data_type    array_name[size1][size2]…[sizeN];

For example, if we want to creates a three dimensional integer array −

int  num[5][10][4];

Two-dimensional Arrays

The simplest form of multidimensional array is the two-dimensional array.

If we want to declare a two dimensional integer array of size [x][y] ( where x is a  number of rows and y is a number of columns ) you would write something as follows −

 int  a[3][4];

In the above line we have created two-dimensional integer array ”a” with 3 rows and 4 columns.

Two Dimensional (2d array)
Two Dimensional Array

Initializing Two-Dimensional Arrays

In a C++ programming language  Multidimensional arrays may be initialized by specifying bracketed values for each row.

For example we want to create an integer array with 3 rows and each row has 4 columns.

Above the nested braces indicates the intended rows.

The following initialization is equivalent to the previous example −

int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};

which indicate the nested braces for intended row, are optional.

Accessing Elements of Two-Dimensional Array

Create a two-dimensional array of size 3*3 and  nested loop is used to handle a two-dimensional array −

Output

Example: Write a program to create 3*3 matrix and take all elements of matrix as an input from user and print it.

Output

CPP Program to Addition of Two Matrix

Example: Write a program to add two matrix.

Firstly, ask from user order of matrix( number of rows and column).

Then take the elements of matrix from user as a input and print the resultant matrix

For example, if a user input order as 3,3, i.e., three rows and three columns and

First matrix                      

1          2          3
4          5          6
7          8          9

Second matrix:

9          8          7
6          5          4
3          2          1

then the output of the program (addition of the two matrices) is:

10        10        10
10        10        10
10        10        10

Matrix addition program in C++

Output

Matrix multiplication in CPP

Example: Write a program to multiply two matrix. Firstly, ask from user order of matrix( number of rows and column). Then take the elements of matrix from user as a input and print the resultant matrix.

Read More

Functions in C++

Categories C++

File Handling in C++

File In a computer system files are used to store the necessary information / data stored. There are mainly two types of files:

  1. Text file
  2. Binary file

Text file. It stores information/data in ASCII characters. In text files, each line of text is terminated with a special character known as EOL (End of Line) character.

Binary file. It contains the data/information in the same format as it is held in memory. In binary files, no delimiters or EOF are used for a line for terminate the line

Classes for file stream operation

By using stream classes we can perform different operation such as read a file or write a file. There are some stream classes:

  • ofstream: This stream class is used to write on files
  • ifstream: This stream class is used to read from files
  • fstream:  This stream class is used to both read and write from/to files.

Modes  of  file

Mode

Description

ios::in

open file for reading only

ios::out

open file for writing only

ios::binary

Open file in a binary mode.

ios::ate

Set the initial position at the end of the file.
If the value of flag is not set to any value, then the by default initial position is the beginning of the file.

ios::app

All output operations are performed at the end of the file.

ios::trunc

If the file opened for output operations,then its previous content is deleted and replaced by the new one.

Opening a file:There are two ways for open a file:-

OPENING FILE USING CONSTRUCTOR

OPENING FILE USING open()

Example: Write a program to open a file using constructor & write a character in a file using write() function

Output

Note: In the above program, we are opening a file x.txt which is exists in an E drive with the help of ofstream class object (f).

After that we will enter character (x) in a console and and write the entered character in a file using wrire() function.   Then we will close a file by using close () function.

Use of read() and write() function 

“read () and write()” functions are used  to performs the reading and writing operation in a file in a binary format.

The format of read() and write() function are as follows:  

read( (char*)&p , sizeof(p) );  

write( (char*)&p , sizeof(p) );           

These function receives two argument. The first argument is the address of the variable P and the second argument is the size of variable P in byte.

Example: Write a program to open a file using open () function & write a character in a file using write () function.

Output

Note: In the above program, we are opening a file x.txt which is exists in an E drive with the help of ofstream class object (f).

After that we will enter character (x) in a console and write the entered character in a file using wrire() function.  

Then we will close a file by using close () function.       

Example: Write a program read a character in a file using read () function.

Output

Note: In the above program, we are opening a file x.txt which is exist in a E drive.

After that we will read a  character (a) from a file “x.txt” and write that character in a console.     

Example: Write a program write and read a character in a file using read () & write () function. Use ifstream and ofstream class.

Output

Note: In the above program, we are opening a file x.txt which is exists in a E drive with the help of ofstream class object (f).

After that we will enter character (s) in a console and write the entered character in a file using wrire() function.

Then we will close a file by using close () function.    

Again we will open a x.txt file with the help of ifstream class object (f1) and read a character (s) from a file and write that character in a console.     

 Example:  Write a program to write and read a character in a file using read () & write () function. Use fstream class.

Output

Example: Write a program to write a string in a file using write () function.

Output

Example:  Write a program to read a string in a file using  read() function.

Output

Note:  Assume in a file “x.txt”, ”this is my book” is written. Then read () function will read only first string (this) or first 50 character string.

Example: Write a program to write and read a integer data in a file using read() & write() function. use ifstream and ofstream class.

Output

Example: Write a program to write in a file using  ofstream object.

Output

Example: Write a program to write and read in a file using ofstream & ifstream object.

Output

Note: In the above program, statement (f1>>a) will read only string “aaaa” from a file.  If we will again read string using ifstream object f1 then for example

Output

Find End Of File (EOF)

We can find the end of file by using the eof() function.

The eof() function returns the non-zero value when end of file is detected, otherwise eof() function returns zero.

Example:  Write a program to write and read in a file & display the content of file. Use eof() function.

Output

Note: In the above program, statement               

Initially function eof() return zero and condition will be true.

Then we will read a data from a file and print it in a console.

When function eof() detect the end of file then it will return non-zero value and then condition will be false and while loops terminates. 

 FILE POINTERS AND THEIR MANIPULATION

In a C++ file pointer is used to point to the reading or writing locations within a stream. There are  following member functions of file pointer

FunctionDescription

seekg()

moves pointer to a specified location in write mode

seekp()

moves  pointer to a specified location in read mode

tellp()

gives current position of the pointer  for write

tellg()

gives current position of the pointer for read

Use of tellg()and tellp() functions

tellg() – gives current position of the pointer  for write

tellp() – gives current position of the pointer for read    

Example: Write a program to show the use of tellg() & tellp() function.  

Or

Write a program to show the present position of input and output pointer using tellg() & tellp().

Output

Use of seekg()and seekp() functions

Function

Description

seekg()

moves pointer to a specified location in write mode

seekp()

moves pointer to a specified location in read mode

seekg() and seekp() function have a  two arguments. Their  format is fellows:-  

  seekg( offset , pre_position );  

seekp( offset , pre_position ); 

first argument specifies the number of bites the file pointer is to be shifted from the pre_position of the pointer.        

The pre_position may have one of the following possible values:-     

pre_position

Description

ios :: beg

Beginning of the file

ios :: cur

Current position of the file pointer

ios :: end

End of the file

File Pointer With Its Arguments in a seekg() function

Seek Option

Working

seekg(0,ios :: beg );

Go to the beginning of the file.

seekg(0,ios :: cur );

Rest at the current position.

seekg(0,ios :: end );

Go to the end of the file.

seekg(n,ios :: beg );

Shift file pointer to n+1 byte in the file.

seekg(n,ios :: cur );

Go front by n byte from current position.

seekg(-n,ios :: cur );

Go back by n byte from the present position.

seekg(-n,ios :: end );

Go back by n byte from the end of position.

Example: Write a program to enter text and again second time re-enter text from beginning position and replace the first word and display the content after 10 byte of the file pointer from the beginning of the file. 

Or

Write a program to show the use of seekp() and seekg() function.

Output

Note: In the above program, first, we write statement “aaaa bbbb cccc” then we  will shift the output  file pointer by using seekp() function  (f.seekp(0, ios :: beg);)at the beginning of the file and again write statement ”xxxx” in place of “aaaa”. 

Now the new statement/new content of file is “xxxx bbbb cccc”.

During reading file first we move the input file pointer 10 byte in a forward direction by using seekg() function (f1.seekg(10, ios :: beg);)   then we will read file till end of file.

Example: Write a program using seekg() to achive the following:   

  •  To move the pointer by 15 position.
  • To go backward by 20 byte from the end.
  • To go byte 50 in the file.

First code is

Second code is

Third is

Example:  Write a program to copy the content of one file into another file.

Output

Use of put() and get() function

get()” is a member function of the class fstream. This function reads the single character from a file.

“put()” function is a member of fstream class. The put() function write a single character in the file.

Example: Write a program to write and read the characters in a file using put() & get() function.

Output

Example: Write a program to write and read five characters in a file using put() & get() function.

Output

Use of fail() function

“fail()” stream state member function is used to check whether a file has been opened for input or output successfully or not.

 It returns the non-zero value if an operation is unsuccessful(or file is not opened) and return zero when it is open.

Output

Note: In the above program, fail() return 0 when file is open and condition will be true after that we can perform operation and return non-zero  value  when file is not open and condition will be false.

Categories C++

Exception Handling

In C++ programming, an exception is an abnormal condition that arises/occurs in a source code during run time.  

Or

 Exception is a run time error.  

Example:

Output

When we try to compile this program we will receive an error message because value of 100/a (100/0) is infinite and it can’t be possible to save and print infinite value.    

Handle Exception in C++

In a C++ programming language whenever an exceptional condition is arises it can be handled by the three keywords: try, catch and throw.

The Keyword try:  Any code or statement that we want to monitor for an exception must be put inside the try block.

Syntax for try block:

   Example:  

In an above statement we have written try block.

Inside the try block we have placed a code (b=100/a) in which exception may occur.

Value of “ a” can be any integer value there is no problem but if the value of variable “a” is  zero then error will generate because  100/a (100/0) is infinite and it can’t be possible to save and print infinite value.             

The Keyword throw: If the exception occurs within try block it is automatically thrown by system or it can be manually thrown by using “throw” keyword. Syntax for throw:

throw    (excep);    

when excep is throw catch statement associated with the try block is handle this exception.

The Keyword catch: When the exceptional condition is arises within the try block it is thrown by the keyword throw and catch by the catch statement associated with the try block.

 Syntax for catch block:

Note: If there is no exception within the try block then catch block will never execute.

Example:   Write a program to show exception.

Output

 
Calling show method of Shape
Shape is no defined
Calling show method of Circle
Showing a Circle
Calling show method of Rectangle
Showing a Rectangle
Calling show method of Square
Showing a Square
Calling show method of Triangle
Showing a Triangle

 Example:   Write a program to throw an exception when a =0 otherwise perform division.

Output

Example:   Write a program to throw an exception when a =1 otherwise perform subtraction of x and y.

Output

Multiple Catch Block

In a C++ programming we can define multiple catch statement for a single try block. Syntax for multiple catch is:  

Example:   Write a program to throw multiple exception and defined multiple catch statement.

Output

Default catch()

In a C++ exception handling  it is also possible to define single or default catch block for one or more exception of different types.

In such a situation, a single catch block can  catch exception thrown by multiple throw statement.  

Example:   Write a program to throw multiple exception and defined multiple catch statement.

Output

Categories C++

Template in C++

In  C++ programming language, Template is used to declare a group of function or class in a generic manner.

Generic  means that that can process all types of data.

By using template a single function can defined for a group of functions, it is called as a “function template”.

Similarly, when template is associated with classes are known as class template.

Advantage of function template:  It avoid unnecessary repetition of source code.

Using template we can create a single function that can process any type of data .

It can accept data of any type such as int, float, long etc.

    Syntax for declare class template:                       

“template” is a keywords.

“template class <t>”  statement tells the compiler the following class declaration can use the template data type.

Here T is a variable of template type. It is used to define variable of template (generic) type.

Within the angle bracket <> we declare a variable of template.

We can declare one or more variable separated by comma.

“template” always be global and should not be local means template cannot be declared inside of function or class.                       

T  k;     Where , k is variable of type template. 

  Normal Template Function Declaration

Syntax for Template Function

template class < T > type function_name() { // code
}

Example:   Write a program to perform constructor overloading and pass different data type argument.

Output

In the above program we have created three overloaded constructor, first accept integer data as argument and second accepts float data as argument and third constructor accepts character data as argument.

This approach has following disadvantages

  • Re-defining the same function separately for each data type. It increases the requires more time.  
  • Size of program is increased. Hence, occupies more memory.  
  • If constructor/function contains bug, it should be correct in every constructor/function. 

Example:   Write a program to create constructor and pass different data type as argument using  template.

Output

In the above program we have created a class “xyz” and one constructor it can accept all data type because, constructor contains the variable of template T.

Normal Template  Function Declaration

Syntax for Template Function

template class < T > type function_name() { // code
}

Example:   Write a program to define normal template function.

Output

Example:   Write a program to find the square of different data type using template.

Output

Class Template With More Parameter

In C++ programming, class template can contain one or more parameter of generic data type.

The argument is separated by comma with template declaration.

Syntax for class template with more than one parameter:

template < class T1, class T2 > class name_of_class {
}

Example:   Write a program to define a constructor with multiple template variables.

Output

Example:   Write a program to exchange the value of two variable. Use Template variable as function argument.

Output

Overloading of Template Function

In a C++ programming language, like a function & constructor we can also override the template.

If we create more than one function with same name and one function take template type data as a argument and another function takes primitive data type as a argument then it overrides the function which takes template data as an argument.

Output

In the above program we have created two function (show ()) with same name.

One function take template type data as a argument and another function takes integer data type as a argument then it overrides the function which takes template data as an argument.

Categories C++

Abstract Class in C++

In a C++ programming language , a class that contains at least one pure virtual function is called  abstract class.

This  pure virtual function is a function is declared within base class and defined by derived class.

Like a other class abstract class can also contains normal function.

We can not create object of an abstract class,Any attempt to so will result in an error, but we can create reference to an abstract class.  

Output

Description: In the above program, we have declared a pure virtual function “show()” in a base class A which is defined by derived class B. 

Because class A contain a pure virtual function therefore class A is an abstract class.  

Abstract class can also contain a normal member   function (in this program member function is display() ).

Categories C++

Virtual Function in C++

In a C++ programming language, A virtual function is a member function that is declared and defined within a base class and redefined by a derived class even if the number and type of argument are matching.  

Rules for Virtual Function: 

  • A virtual function may be declared as friend for another class.  
  • Constructor cannot be declared as virtual, but destructor can be declared as virtual.
  • Like other function virtual function can return a value. 

Example:   Write a program to declare virtual function and executes the same function defined in base & derived class.

Or

Write a program to use pointer for both base and derived class and call the member function. Use virtual keyword. 

Or 

Write a program to create a virtual function.

Output

Note: In the above program ‘a ‘is an object of base class A and ‘b’ is an object of derived class B.

The pointer variable ‘p’ point to the base class. In the statement “p = &a;” the address of object ‘a’ is assigned to pointer ‘p’.

Then the pointer calls the member function of class A.

Similarly, in the statement “p = &b;” the address of object ‘b’ is assigned to pointer ‘p’.

Then the pointer calls the member function of class B.

Pure Virtual Function

In a C++ programming language, A pure virtual function is a function which is declared within base class and defined by derived class.

We can declare a pure virtual function by using “virtual” keyword.

Any normal function cannot be declared as pure function. Syntax for declaration of pure virtual function: 

virtual type function _name(parameter list)= 0;    

Example:    virtual void show () =0;     

Example:   Write a program to create a pure virtual function.

Output

Description: In the above program, we have declared a pure virtual function “show ()” in a base class A which is defined by derived class B.

Categories C++

Function Overriding in C++

In a C++ programming language, it the base and derived both class has a function with same name and same parameter then derived class overrides the base class definition.

Such function’s are called overridden function and this process is called function overriding.   

Output

Note: In the above program, class A & B both has a function (show ()) with same name and same parameter list.

When we call a show () function of base class A then show () function of derived class overrides the show () function of base class.

Categories C++

Constructor and Destructor Calling in C++

In a C++ programming language constructor are called from base class to derived class and destructor are called reverse of constructor means from derived class to base class.                                                                                                                      

Example:   Write a program to show the sequence of execution of constructor and destructor.

Output

Categories C++

Virtual Base Class in C++

In a C++ programming language to overcome the ambiguity problem occurred due to multipath inheritance we use “virtual” keyword.

By using the “virtual” keyword we can declares the specified class virtual. 

When a class declared as virtual, then the compiler takes necessary precaution to avoid the duplication of member variable.

We can make a class virtual if it is a base class and is used by more than one derived classes as their base class. 

Example:   Write a program to declare virtual base classes. Derive a class using two virtual base class.

Output

Categories C++