C++

C++ Data Structures

C++ Data Structures

OPENING A FILE :-

  • A file should be opened before you will read from it or write to it. Each of two the ofstream or fstream object could even be utilized to open a file for writing however the ifstream object is used to open a file for reading purpose only.
  • This is the standard syntax for open ( ) function :

void open (const char *filename, ios::openmode mode);

  • The first argument decides the name and site of the file to be opened and then the second argument of the open ( ) member function characterizes the mode wherein the file should be opened.
  • You can join two or more of those values by ORing them together. For instance suppose you need to open a file in write mode and want to truncate it in case it already exists. And following will be the syntax :
  • ofstream outfile;

outfile.open (“file.dat”, ios::out | ios::trunc);

  • fstream afile;

afile.open (“file.dat”, ios::out | ios::in);

CLOSING A FILE :-

  • When a C++ program closes it consequently closes flushes all the streams then freeing all the allocated memory and shut every one of the accessible files. But it is consistently an incredible practice that a programmer should close all the opened files before program termination.
  • This is the standard syntax for close ( ) function

void close ( );


C++ Exception Handling :

 

  • The process of changing system error messages into user friendly error message is termed as exception handling. This is one of the amazing feature of C++ to handle run time error and maintain normal flow of C++ application.
  • An exception is an event which happens during the execution of a program that spoil the traditional flow of the programs instructions.
  • Exceptions are runtime deviation that a program encounters during execution. It is a circumstance where a program has an unusual condition and therefore the section of code containing it can’t handle the problem /matter. Exception involves situations like division by zero or accessing an array outside its bound or running out of memory then so on.

In order to handle these exceptions the exception handling mechanism is used which identifies and affect such condition. 

Exception handling system consists of following parts :

  • Find the problem (Hit the exception)
  • Inform about its occurrence (Throw the exception)
  • Receive error information (Catch the exception)
  • Take proper action (Handle the exception)

 

  • The process of changing system error messages into user friendly error message is termed as exception handling. This is one of the amazing feature of C++ to handle run time error and maintain normal flow of C++ application.
  • An exception is an event which happens during the execution of a program that spoil the traditional flow of the programs instructions.
  • Exceptions are runtime deviation that a program encounters during execution. It is a circumstance where a program has an unusual condition and therefore the section of code containing it can’t handle the problem /matter. Exception involves situations like division by zero or accessing an array outside its bound or running out of memory then so on.

In order to handle these exceptions the exception handling mechanism is used which identifies and affect such condition. 

Exception handling system consists of following parts :

  • Find the problem (Hit the exception)
  • Inform about its occurrence (Throw the exception)
  • Receive error information (Catch the exception)
  • Take proper action (Handle the exception)

Why exception handling

 

  1. Segment of error handling code from normal code : In traditional error handling codes there are consistently if else conditions to deal with errors. These conditions and the code to handle errors get involved with the normal flow. This makes the code less comprehensible and maintainable. The code for error handling becomes separate from the normal flow with try catch blocks.
  2. Functions or Methods can deal with any exceptions they pick : A function can throw various exceptions but may decided to handle a number of them. The other exceptions which are thrown but not caught can be managed by caller. But if the caller picks to not catch them then the exceptions are handled by caller of the caller. In C++ a function can define the exceptions that it throws using the throw keyword. The caller of this function should deal with the exception during a number of way (either by specifying it again or getting it).
  3. Grouping of error types : In C++ both basic types and objects are often thrown as an exception. We can make an order of exception objects and group exceptions in namespaces or classes then categorize them according to their types.

 

We use Data structures in C and C++ to store heterogeneous data i.e. data of a different kind. Consider all data associated with a book kept in a library. The librarian will associate the following attributes to a book.

name

author

publisher

year

ISBN number

subject

type

We can defined all these in a data structure as shown below and also use typedef to create an alias for it:

enum Type {paperback, hardcopy, ebook};
struct bookRecord
{
  string name;
  string author;
  string publisher
  int year;
  string ISBN_Number;
  string subject;
  Type t;
};

typedef struct bookRecord BOOK;

The formal syntax to define a structure in C++ is 
struct [structure tag] {
   member definition;
   member definition;
   ...
   member definition;
} [one or more structure variables];

You can access any member of a structure by member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You can pass a structure as a function argument in same way as you pass any other variable or pointer. 

You can define pointers to structures in very similar way as you define pointer to any other variable as follows. For e.g.

BOOK bookSc
BOOK *bk;

You can assign address of a struct to pointer of its kind as shown below:

bk = &BookSc;

to access any field in BookSc, we can now use -> opertor on pointer
bk->name; //To get access to name of BookSc

You can create alias to any data type in C++ by using keyword typedef. We have already used it above to create alias for Book Record.

Let us combine all these concepts in a program for practical understanding. Save the following code in a file say demoStruct.cpp.

#include <iostream>
#include <string>
 
using namespace std;

enum BookType {paperback, hardcopy, ebook} type;

struct bookRecord
{
    string title;
    string author;
    string publisher;
    int year;
    string ISBN_Number;
    string subject;
    BookType type;
};

typedef struct bookRecord BOOK;


void displayBook(const BOOK *bookptr );

int main() 
{
   BOOK Book1;        // Declare Book1 of type Book
   BOOK Book2;        // Declare Book2 of type Book
   
   // Create Book 1 record 
   Book1.title =  "5G Overview";
   Book1.author =  "William Stalling"; 
   Book1.subject = "Wireless";
   Book1.publisher = "Pearson";
   Book1.ISBN_Number = "1234567";
   Book1.year = 2021;
   Book1.type = hardcopy;

   // Create Book 2 record 
   Book2.title = "Let us C";
   Book2.author = "Yashwant Kanitkar"; 
   Book2.subject = "Programming";
   Book2.publisher = "BPB";
   Book2.ISBN_Number = "3434343";
   Book2.year = 2020;
   Book2.type = paperback;
 
   // Print Book1 info, passing address of structure
   displayBook( &Book1 );

   // Print Book2 info, passing address of structure
   displayBook( &Book2 );

   return 0;
}//end main()


// This function accept pointer to structure as parameter.
void displayBook(const BOOK *book ) 
{
   cout << "Book title : " << book->title <<endl;
   cout << "Book author : " << book->author <<endl;
   cout << "Book subject : " << book->subject <<endl;
   cout << "Book publisher : " << book->publisher <<endl;
   cout << "Book ISBN number : " << book->ISBN_Number <<endl;
   switch (book->type)
   {
      case paperback: 
          cout << "Book Type : paperback"<<endl;
          break;
      case hardcopy: 
          cout << "Book Type : hardcopy"<<endl;
          break;
      case ebook:    
          cout << "Book Type : ebook"<<endl;
          break;      
   }
   cout<<endl;
}///end printBook()

Now compile and run the code. You can see it displays two book records we created in main().

(base) 9:09:39:~ % g++ structDemo.cpp

(base) 9:09:41:~ % ./a.out           

Book title : 5G Overview

Book author : William Stalling

Book subject : Wireless

Book publisher : Pearson

Book ISBN number : 1234567

Book Type : hardcopy

Book title : Let us C

Book author : Yashwant Kanitkar

Book subject : Programming

Book publisher : BPB

Book ISBN number : 3434343

Book Type : paperback

C++ classes and objects :-

Class is a data type that is user defined which holds its own data member and member function. In other words we can say class is collection of data member and member function which can accessed and use by creating object of that class.

A class represents group of similar objects. It is also a way to bind data describing an entity and its associated function together.

Syntax:-
class classname
{

};

Classes are needed to represent real world entities. To describe a real world entity we need two different things. One is characteristics and the other is function.

Class definition :- 
class classname{
private:
…
…
protected:
…
…
public:
…
…
};
By default class members are private.
Class Method’s definition :-
Member functions are often defined in two places:
Outside class definition
Syntax: 
class-name::function-name

Inside class definition
Example:-
class area
{
public:
int getarea( )
{
return side*side;
}
};

Object :-

An object is an instance of a class. Whenever class is defined, no memory is allocated but when object is initialized memory is allocated of that class.

Once a class has been created then we can create variable of that type (class type) by using following syntax which is named object.

Syntax:-
class_name variable_name;

We can create any number of objects belonging to that class by declaring one object in one statement. This statement are written in main( ) function.

The objects can also be defined by putting their name directly after the closing brace of the class.

C++ Inheritance :-

It is a procedure of inheriting properties and behaviours of existing class into a new class.

The prime advantage of inheritance is code reusability.

In the concept of inheritance, the existing class is called as the base class and the new class which is inherited is called as the derived class.

The idea of inheritance achieves the IS - A relationship. For example mammal IS- A animal and cat IS- A mammal hence cat IS- A animal as well and so on.

We can save our time and money by reusing classes. And also it is faster development and easy to extend. It is capable of showing the inheritance relationship and its transitive nature which provides closeness along with actual world problems.

Need of Inheritance :-

  1. It is used to represent real world relationship.
  2. It provides reusability.
  3. It supports transitivity.

There are five types of inheritance :-

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Multiple Inheritance 
  4. Hierarchical Inheritance
  5. Hybrid Inheritance

Single Inheritance :- In single inheritance a subclass inherits from one base class.

Syntax :-
class A 
{
…
};
class B : public A
{
…
};

Multilevel Inheritance :- It is transitive in nature. In this type of inheritance we’ll deriving a class from already derived class.

Syntax :-

class A 
{
…
};
class B : public A
{
…
};
class C : public B 
{
…
};

Multiple Inheritance :- In multiple inheritance a subclass inherits from multiple base classes.

Syntax :-

class A1
{
…
};
class A2
{
…
};
class B : public A1, public A2
{
…
};

Hierarchical Inheritance :- In hierarchical inheritance many sub class inherits from single base class.

Syntax :-
class A
{
…
};
class B1 : public A
{
…
};
class B2 : public A
{
…
};

Hybrid Inheritance :-

Syntax :-
class A
{
…
};
class B : public A
{
…
};
class C
{
…
};
class D : public B, public C
{
…
};

C++ Overloading :-

In C++ overloading occurs when an equivalent operator or function name is used with different signatures.

Both operators and functions can be overloaded. Various definitions must be distinguished by their signatures (otherwise which to call is ambiguous).

  • Note that signature is the operator or a function name and the ordered list of its argument types.
  • E.g. sum(int, long) and sum(long, int) have different signatures.
  • E.g. add(const Base &) and add(const Derived &) have different signatures even if Derived is -a Base.
  • Most specific match is employed to select which one to call.

Tips on overloading :-

  1. Use virtual overriding when you wish to substitute different subtypes polymorphically.
  2. Use overloading when you wish to provide related interfaces to similar abstractions.
  3. Use different names when the abstraction differ.

Operator Overloading :-

To assign more than one operation on a same operator known as operator overloading.

To achieve operator overloading we have to write a special function known as operator( ).

Syntax :-
return_type operator op (arg list)
{
Body;
}

You can write operator( ) in two ways -

  1. Class function
  2. Friend function

Following is the list of operators that can’t be overloaded-

  1.  .
  2.  ::
  3.  ?:
  4.  sizeof( )

There are mainly two sorts of operator overloading :

  1. Unary Operator Overloading :- An operator which contain only one operand is called unary operator overloading.
  2. Binary Operator Overloading :- An operator which contain two operands is called binary operator overloading.

Function Overloading :- 

Function overloading is a feature of C++ where we have more than one function with the same name and different types of parameters then it is known as function overloading.

C++ Polymorphism :-

Polymorphism is derived from two Greek words i.e. poly and morphs and poly means ‘many’ , morphs means ‘forms’.

The technique of representing one form in multiple forms is called as polymorphism. Here one form represent original form or original method always consist in base class and multiple forms represents overridden method which consist in derived classes.

We can take an example to understand this - 

One person have different different behaviors like suppose if you are in class room that time you behave like a student but when you are in market at that time you behave like a customer.

Basically there are two sorts of polymorphism :

  1. Static polymorphism :- Static polymorphism is also known as early binding and compile time polymorphism. In static polymorphism memory are going to be allocated at compile time.

    The overloaded member functions are selected for calling by matching arguments both type and number. This information is understood to the compiler at the compile time and is able to pick the appropriate function for a particular call at the compile time itself.
  2. Dynamic polymorphism :- Dynamic polymorphism is also known as late binding and run time polymorphism. In dynamic polymorphism memory are going to be allocated at run time.
  3. Virtual function :-  When we use an equivalent function name in both the base and derived classes, the function in base class is stated as virtual using the keyword virtual preceding its normal declaration. 

    When a function is formed virtual, C++ determines which function to use at run time based on the type of object pointed to by the base pointer rather than type of the pointer.

    C++ Abstraction :-
    Abstraction in C++ isn’t new concept it is oops concept which is employed to hide background detail and show only essential features. Data abstraction may be a procedure of representing the essential features without including implementation details.

    The main advantage of abstraction is it reduces code complexity.

    Abstract class :-

     Abstract class is a class which contains a minimum of one Pure Virtual function in it.

    Some of the characteristics of abstract class are :

  4. Abstract class can’t be instantiated but pointers and references of abstract class type are often created.
  5. Abstract class may have normal functions and variables in conjunction with a pure virtual function.
  6. Abstract classes are usually used for up - casting in order that its derived classes can use its interface.
  7. The classes that inheriting an abstract class should carry out all pure virtual functions alternatively they’re getting to become abstract too.

C++ files and streams :-

  • So long we are using iostream standard library which gives us cin and cout methods for reading from standard input and writing to plain output respectively.
  • To read and write from a file we need another standard C++ library called fstream which characterizes three new data types:
  • Ofstream
  • Ifstream
  • Fstream

FSTREAM :- 

  1. Ofstream :- This type of data represents the output file stream and is utilized to create files and to write down information to files.
  2. Ifstream :- This type of data basically represents the input file stream and is employed to read information from files.
  3. Fstream :- It addresses the file stream generally and has the ability of both ofstream and ifstream which infers it can create files then write information to files and read information from files.

Note:- To perform file processing in C++ main header files <iostream> and <fstream> must be included in your C++ source file.