Category: CPlusPlus Tutorial

  • C++ Exception Handling

    An exception is an event or an error that arises during the execution of a program i.e. during runtime. The occurrence of an exception in a program disrupts the normal flow of instructions.

    So to handle such errors, we use exception handlers. If we do not handle the exception properly then the program may terminate. We can catch an exception through exception handling and our program will not completely terminate.

    The main advantage of exception handling is to ensure that even when an exception occurs, the program’s flow doesn’t break.

    C++ Exception Handling Keywords

    C++ provides three keywords to perform exception handling. They are:

    • try: The try block identifies the block of code for which the exception will be activated. It is followed by a catch block.
    • catch: The catch indicates the cathching of an exception where you want to catch the error accuring in the program.
    • throw: throw keyword is used to throw an exception when a problem arises in a program.

    try/catch in C++

    Assume that the block of code will cause an error and you want to catch that exception. The try and catch block will help you to do that. You place a code inside the try block which you think causing the problem and catch the statement to catch the exception.

    The syntax for try and catch:

    try 
      {
        // Exception code
      } catch (ExceptionType1 e1) {
        // Catch block
      } catch (ExceptionType2 e2) {
        // Catch block
      } catch (ExceptionType3 e3) {
        // Catch block
      }

    We can place a multiple catch statement on different types of exceptions that may arise by try block code.

    Example: C++ try/catch

    Use of try, catch and throw keywords in a C++ program.

    #include <iostream>
    using namespace std;
    
    double division(int x, int y)
    {
      if (y == 0)
        throw "Division by Zero attempted.";
    
      return (x / y);
    }
    
    int main()
    {
      int a = 11;
      int b = 0;
      double c = 0;
    
      try
      {
        c = division(a, b);
        cout << c << endl;
      }
    
      catch (const char *ex)
      {
        cerr << ex << endl;
      }
    
      return 0;
    }

    Output:

    Division by Zero attempted.


    C++ Standard Exceptions

    C++ provides a list of standard exceptions defined in <exception> class that we can use in a program.

    c++ exception handling

    These exceptions and descriptions are listed in the table below.

    ExceptionDescription
    std::exceptionThis is an exception and the parent class of all standard C++ exceptions.
    std::bad_allocThis can be thrown by a keyword new.
    std::bad_cast This can be thrown by dynamic_cast.
    std::bad_exceptionA useful device for handling unexpected exceptions in C++ programs.
    std::bad_typeidAn exception thrown by typeid.
    std::logic_errorThis exception is theoretically detectable by reading code.
    std::domain_errorThis is an exception thrown after using a mathematically invalid domain.
    std::invalid_argumentThis exception is thrown for using invalid arguments.
    std::length_errorThis exception is thrown after creating a big std::string.
    std::out_of_rangeThrown by at method.
    std::runtime_errorThis is an exception that cannot be detected via reading the code.
    std::overflow_errorThis exception is thrown after the occurrence of a mathematical overflow.
    std::range_errorThis exception is thrown when you attempt to store an out-of-range value.
    std::underflow_errorThis exception is thrown after the occurrence of mathematical underflow.

    User-Defined Exceptions

    The C++ std::exception class allows us to define objects that can be thrown as exceptions. This new exception can be defined by overriding and inheriting the exception class functionality. This class has been defined in the <exception> header.

    Example: user-defined exception in c++

    #include <iostream>
    #include <exception>
    using namespace std;
    
    class ExceptionEg: public exception
    {
      virtual
      const char *what() const
      throw ()
      {
        return "Occurance of new exception";
      }
    };
    
    int main()
    {
      ExceptionEg newEx;
      try
      {
        throw newEx;
      }
    
      catch (exception & ex)
      {
        cout << ex.what() << '\n';
      }
    
      return 0;
    }

    Output:

    Occurance of new exception


  • C++ Strings

    A string is a sequence of characters that is an object of std::string class in C++. Memory to a string is allocated dynamically that is we can assign memory during runtime as required. Various operations are performed on a string such as concatenation, comparison, conversion, etc.

    C++ supports two types of string in a program.

    • C-style character string.
    • String class type (Standard C++ Library).

    C-style character string

    C-style was introduced in the C programming language and is continued to be supported by C++. These one-dimensional strings are stored in a series in an array of type char and are terminated by a null character ‘\0’.

    Memory presentation of the character array in C/C++:

    string

    Declaring C-style string:

    char name[5] = {'A', 'l', 'e', 'x', '\0'};

    The above character for a string ‘Alex‘. But notice that the number f character is 4 but we declare the size 5 as because the last space is reserved for the null character in order to terminate the string.

    Although, we can also initialize the above in the following way.

    char name[] = "John";

    Note that here, we do not have to add a null character at the end. The C++ compiler will automatically place the ‘\0‘ at the end of the string.

    Example: C++ program to read and display the string

    #include <iostream>
    using namespace std;
    
    int main()
    {
        char str[100];
        
        cout << "Enter a string: ";
        cin.get(str, 100);
    
        cout << "Entered String is: " << str << endl;
        return 0;
    }

    Enter a string: This is simple2code.com
    Entered String is: This is simple2code.com

    Notice that we use cin.get in order to get the string from the user that contains white spaces in a string. It takes two argument name of a string and the size of an array.


    String class type

    The standard C++ library provides a string class that supports the various operation on a string. It is written as std::string.

    Also, instead of char type, we create a string object to hold the string. It does not require fined length like in char type, we can extend the character according to our need.

    Now in order to use the class to perform various operations on a string, we need to include the following header file.

    #include<cstring>

    Example: C++ program to read and display the string using string object

    Before performing on class type with some operation, let us first see a simple example of string using its object.

    #include <iostream>
    using namespace std;
    
    int main()
    {
        string str;
        
        cout << "Enter a string: ";
        getline(cin, str);
    
        cout << "Entered String is: " << str << endl;
        return 0;
    }

    Enter a string: This is simple2code.com
    Entered String is: This is simple2code.com

    Notice that to get the string from the user, we use getline() function that takes two arguments – input stream (cin) and location of the line to be stored (str).


    C++ String Functions

    There are different functions provided by the string class to manipulate strings in a program. The cstring class defines these functions and we need to include cstring header file in a program. Let us see some of these functions with examples.

    FunctionDescription
    strcpy(str1, str2);It copies string2 content in string1.
    strcmp(str1, str2); It is a comparison function.
    returns 0, if str1 = str2
    returns less than 0, if str1<str2
    returns greater than 0, if str1>str2
    strcat(str1, str2); It joins str2 into the end of str1.
    strlen(str); It returns the length of the string passed.

    Example of the above string function in C++

    #include <iostream>
    #include <cstring>
    using namespace std;
    
    int main() 
    {
        char str1[10] = "Mark";
        char str2[10] = "John";
        char str3[10];
        int  len;
    	
        //copy string2 to string3
        strcpy(str3, str2);
        cout << "strcpy( str3, str2) : " << str3 << endl;
    
        //concatinate string1 and string2
        strcat(str1, str2);
        cout << "strcat( str1, str2): " << str1 << endl;
    
        //length of a string1
        len = strlen(str1);
        cout << "strlen(str1) : " << len << endl;
    	
        //compare: returns 0 since str2 = str3
        cout << "strcmp(str2, str3) : " << strcmp(str2, str3) << endl;
    
        return 0;
    }

    Output:

    strcpy( str3, str2) : John
    strcat( str1, str2): MarkJohn
    strlen(str1) : 8
    strcmp(str2, str3) : 0


    Passing String to a Function

    We pass the string in a similar way like we pass an array to a function. We will see an example where we will learn to pass two different strings in a function.

    It is a basic example, where we create two print functions and take the user input for two different strings.

    #include <iostream>
    using namespace std;
    
    //function prototype
    void print(string);
    void print(char *);
    
    int main()
    {
        string str1;
        char str2[100];
    
        cout << "Enter First string: ";
        getline(cin, str1);
    
        cout << "Enter Second string: ";
        cin.get(str2, 100);
    
        print(str1);
        print(str2);
        
        return 0;
    }
    
    void print(string str)
    {
        cout << "\nString is: " << str << endl;
    }
    void print(char str[])
    {
        cout << "Char array is: " << str << endl;
    }
    
    

    Enter First string: This is a website
    Enter Second string: It is simple2code.com

    String is: This is a website
    Char array is: It is simple2code.com


  • C++ Preprocessor

    As you have studied in C preprocessor before, C++ preprocessor also has the same exact concept of it with a change in coding.

    As the “pre” means beforehand, similarly it means processing something before passing it on further. The preprocessor is a program that processes the source program before it is passed to the compiler. So we can say that it is a separate process in the compilation.

    Preprocessor gives specific features called directives. All preprocessor directive begins with# symbol and do not need to be end with senicolon (;). We have seen the use of #include in the program till now.

    The following are preprocessor directives:

    • Macro expansion
    • File inclusion
    • Conditional Compilation
    • Miscellaneous directives

    Macro Definition

    macro is defined by #define in a program. It is used to define some constant in a program that can be used anywhere during the entire program. This constant becomes global value.

    #define PI 3.1415

    This statement is called ‘macro definition’ or more commonly, just a ‘macro’.
    Its purpose: during preprocessing, the preprocessor replaces every occurrence of PI in the program with a 3.1415 value.

    You may try this program:

    #include <iostream>
    using namespace std;
    
    #define PI 3.14159 //macro
    
    int main () 
    {
       float radius = 2.5;
       cout << "Area of a circle :" << PI * radius *radius << endl; 
    
       return 0;
    }

    Area of a circle :19.6349


    File inclusion

    #include is used to include some files into the program. These are usually header files, but sometimes maybe any text file. The command looks something like this:

    #include <iostream>

    iostream is the header file that contains the library function useful to the program.


    Conditional Compilation

    The C++ preprocessor provides a series of directives for conditional compilation: #if, #elif, #else, #ifdef, #ifndef, and #endif. These commands cause the preprocessor to include or exclude sections of the source code from compilation depending on certain conditions.

    Conditional compilation is used for three main purposes:

    • Optionally include debugging code
    • Enclose non-portable code
    • Guard against multiple inclusion of header files.

    Syntax:

    #ifdef, #endif, #if, #else, #ifndef

    #ifndef

    #ifndef TEXT
       #define TEXT "Hello World"
    #endif

    It tells the C Preprocessor to define TEXT only if TEXT isn’t already defined.

    #ifdef Directive

    #ifdef MACRO     
       // conditional codes
    #endif
    #if expression
       conditional codes if expression is non-zero
    #else
       conditional if expression is 0
    #endif

    You can also add nested conditional to your #if...#else using #elif

    #if expression
        // conditional codes if expression is non-zero
    #elif expression1
        // conditional codes if expression is non-zero
    #elif expression2
        // conditional codes if expression is non-zero
    #else
        // conditional if all expressions are 0
    #endif

    Other directives

    #undef is used to undefine a defined macro variable.

    #undef  FILE_SIZE
    #define FILE_SIZE 38

    It tells the C Preprocessor to undefine existing FILE_SIZE and define it as 38.

    #pragma startup and #pragma exit: These are used to call a function before and after the main function in a C++ program.

    #undef, #pragma startup, #pragma exit


    Predefined Macros

    MacroValue
    __DATE__A string containing the current date
    __FILE__A string containing the file name
    __LINE__An integer representing the current line number
    __TIME__A string containing the current date.

  • C++ Namespaces

    Suppose there is a function called abc() in your code and you are also using some library that has the function with the same name as abc(). Now while executing these functions, the compiler will not know which one to execute among two abs() functions. In such cases namespace comes into action.

    A namespace is used to overcome the above situation in a program. It is used as additional information for functions, classes, etc. It allows us to organize the elements of the program into a logical group so that the collision of multiple libraries can be prevented.

    Defining a Namespace

    The keyword “namespace” is used to define the namespace class and to call prepend (::) the namespace such as:

    namespace namespace_name
    {
    void func() {
    // body of function
    }
    }

    //to call, inside main
    namespace_name::func();

    It could be variable or function in a program.


    Example of namespace in C++

    #include <iostream>
    using namespace std;
    
    namespace space_one 
    {
       void funcHello() {
          cout << "Hello space_ONE" << endl;
       }
    }
    
    namespace space_Two 
    {
       void funcHello() {
          cout << "Hello space_Two" << endl;
       }
    }
    
    int main () 
    {
       //Calling function with their namespace
       space_one::funcHello();
       space_Two::funcHello(); 
    
       return 0;
    }

    Output:

    Hello space_ONE
    Hello space_Two


    C++ program for a namespace with the use of directive.

    Here we use using keyword and avoid prepending a namespace.

    #include <iostream>
    using namespace std;
    
    namespace space_one 
    {
       void funcHello() {
          cout << "Hello space_ONE" << endl;
       }
    }
    
    namespace space_Two 
    {
       void funcHello() {
          cout << "Hello space_Two" << endl;
       }
    }
    
    using namespace space_one;
    int main () 
    {
       //Calling function with their namespace
       funcHello();
    
       return 0;
    }

    Output:

    Hello space_ONE


  • C++ Files and Streams

    Till now, we have seen the use of iostream standard library that provides us with cin and cout methods to take input and print output respectively. Here we will learn about another library to handle files.

    Files are used to store the data permanently in the storage device and a standard C++ library called fstream allows us to work with files.

    fstream Library

    The fstream Library provides us with three classes that help us to read and write from the files in C++. And these classes are:

    • fstream: This class generally represents a file stream. It is used to create files, write or read data from or to the files.
    • ifstream: This class represents an input stream and used to read the data from the files.
    • ofstream: This class represents an output stream and used to write the data to the files.

    Open a file

    We can not perform any operation on file without opening it first. If you want to perform a write operation on the file then open the file using fstream or ofstream objects. If you want to perform a read operation on the file then open the file using ifstream object.

    There is a function called open() which is a member of all three classes (fstream, ifstream, and ofstream) and is used to open a file. The syntax to open a file is:

    open (file_name, mode);

    • file_name: This simply indicates the name of the file to be opened.
    • mode: It defines the mode in which the file should be opened. It is opetaional. There are several modes given below.
    ModeDescription
    ios:: appAppend mode. The output sent to the file is appended to it.
    ios::ateAt end mode. It opens the file for the output then moves the read and write control to the end of the file.
    ios::inInput mode. It opens the file for reading.
    ios::outOutput mode. It opens the file for writing.
    ios::truncTruncate mode. If a file exists then before opening the file its contents are discarded.

    Also while opening a file we can combine the above modes together using OR operator (|) such as:

    ofstream file;
    file.open("file_name", ios::out | ios::trunc);

    Default Modes:

    As stated above the mode in an open() function is optional and if we do not provide the mode then the following default mode will be assigned to the respective classes.

    ClassMode
    ifstreamios::in
    ofstreamios::out
    fstreamios::in | ios::out

    Close a file

    Once the program is terminated in C++, it automatically closes the opened files. However, it is recommended to practice closing a file every time you open a file.

    Just like a function open() is there to open a file, the fstream, ofstream, and ifstream objects also have a close() function. The syntax is pretty simple.

    void close();


    Example: C++ program to open and close a file

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main() 
    {
       fstream file;
       file.open("file.txt", ios::out);
    	
       //check if file creation is failed or not
       if (!file) 
       {
          cout << "File is not created!";
       }
       else 
       {
          cout << "File is created successfully.";
          file.close(); 
       }
    
       return 0;
    }

    //Output
    File is created successfully.

    After successful execution of the above code, you may check the directory where your c++ program file is present, there you will find a new text file with file.txt name.


    Writing to a file

    Below is the example of C++ to write to a file. We will write to a text file called file.txt using the stream insertion operator (<<). Here we use ofstream or fstream object instead of the cout object.

    Example: C++ to write in a file.

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
      ofstream file("file.txt");
    
      //check if file is opened or not
      if (file.is_open())
      {
        file << "This is Simple2Code.com.\n";
        file << "Learn Programming Language.\n";
        file.close();
      }
      else
      {
        cout << "File failed to open";
      }
    
      return 0;
    }

    After successful execution of the program, you can open your file.txt and you will see the following sentence inside that file.

    This is Simple2Code.com.
    Learn Programming Language.


    Reading from a file

    Below is the example of C++ to read from a file. We will from a text file called file.txt using the stream extraction operator (>>). Here we use ifstream or fstream object instead of the cin object.

    Example: C++ to read from a file.

    Now before running the program, you must create a file and write some text in it as for this example, we created a file called file.txt and wrote the following text in it.
    This is Simple2Code.com.
    Learn Programming Language.

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
      string str;
      ifstream file("file.txt");
    
      //check if file is opened or not
      if (file.is_open())
      {
        while (getline(file, str))
        {
          cout << str << endl;
        }
    
        file.close();
      }
      else
      {
        cout << "File failed to open";
      }
    
      return 0;
    }

    After successful execution of the program, you will see the following output (String from opened file.)

    This is Simple2Code.com.
    Learn Programming Language.


    Example: Read and Write in C++

    Here, we will see an example where we will write some data in a text file called file.txt and then read those from the file using C++ FileStream. To write the data, we will take user input.

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
      char data[100];
    
      //WRITE mode
      ofstream writeFile;
      writeFile.open("file.txt");
    
      cout << "Writing to a file:" << endl;
      cout << "Enter your name: ";
      cin.getline(data, 100);
    
      writeFile << data << endl;  //writing the entered data
    
      cout << "Enter your age: ";
      cin >> data;
      cin.ignore();
    
      writeFile << data << endl;  //writing the entered data
    
      writeFile.close();   //file closed
    
      //READ mode
      string str;
      ifstream readFile;
      readFile.open("file.txt");
    
      cout << "\nReading from a file:" << endl;
      while (getline(readFile, str))
      {
        cout << str << endl;
      }
    
      readFile.close();  //file closed
    
      return 0;
    }

    After Execution, a file name file.txt will be created and the following entered will be present in that file.

    Writing to a file:
    Enter your name: John Markson
    Enter your age: 29

    Reading from a file:
    John Markson
    29


  • C++ Enumeration

    An enumeration is a user-defined type that consists of a set of named integral constants. These constants are fixed constant. The keyword enum is used to define these data types.

    Syntax of enums

    enum enum_name{const1, const2, ....... };

    • enum_name: Name of the enum given by the user.
    • const1, const2 : These are the value of type enum_name.

    Let us see an example to define enum.

    enum season { spring, summer, autumn, winter };

    The above is the enum for the season, spring, summer, autumn and winter are the types of the season and by default, the value starts in increasing order from zero such as spring is 0, summer is 1, autumn is 2 and winter is 3.

    We can change the default values of enum and assign the required value in the following way.

    enum season { spring = 01, summer = 04, autumn = 06, winter=09 };


    How to declare an enum variable

    We can declare an enum variable in two different ways:

    1. We can declare it at the time of defining enum, just add the enum variable name at the end and before the semicolon.
    2. Another way is we can create it inside the main function. Both ways are shown below.
    //first way
    enum enum_name{const1, const2, ....... } variable_name;
    
    
    //Second way
    enum enum_name{const1, const2, ....... };
    int main()
    {
      enum_name variable_name;
    }

    Example of enumeration in c++

    1. Let us see an example of enum in c++ with the first way of declaring variables.

    #include <iostream>
    using namespace std;
    
    enum week{ 
           Sunday, 
           Monday, 
           Tuesday, 
           Wednesday, 
           Thursday, 
           Friday, 
           Saturday
       } today;
    
    int main()
    {
       today = Monday;
       cout << "Day: " << today+1;
        
       return 0;
    }

    Output:

    //Output
    Day: 2


    2. Another example of enum, where we declare the variable inside the main function. Also, we change the default values of enums.

    #include <iostream>
    using namespace std;
    
    enum colors{red = 12, green = 24, blue = 36};
    
    int main()
    {
       colors color;
       color = green;
       
       cout << "Green: " << color; 
       
       return 0;
    }

    Output:

    //Output
    Green: 24


    Why use enum in C++

    We use enum when we want to assign the variable with one of the possible sets of values. These values cannot be changed, if we try to assign different values to this variable the compiler generates an error. Thus, it improves safety and increases compile-time checking.

    There is another use of enum that is in a switch case statement. Also, enum can be traversed.


  • C++ Structure and Function

    The relation of structure and function in C++ is that just like any other argument passed in a function, a structure can also be passed.

    Passing structure to function in C++

    We can pass and access the structure to function as an argument in a program. It is similar to the way we pass a normal argument to a function. And it is also returned from a function just like any other argument.

    Let us understand through an example.

    #include<iostream>
    #include <cstring>
    using namespace std;
    
    struct Student
    {
        char name[50];
        int roll;
    };
    
    void display(struct Student s); // Function declaration
    
    int main()
    {
        struct Student s;
    
        strcpy(s.name, "John Mathers");
        s.roll = 32;
    
        display(s);
        return 0;
    }
    void display(struct Student s)
    {
        cout << "Person Name: " << s.name<<endl;
        cout << "Person Roll: " << s.roll;
    }

    Output:

    Person Name: John Mathers
    Person Roll: 32


    Returning structure from function in C++

    #include<iostream>
    #include <cstring>
    using namespace std;
    
    struct Student
    {
       char name[50];
       int roll;
    };
    
    // Function declaration
    Student returnInfo(Student);
    void display(struct Student s); 
    
    int main()
    {
       Student s;
    
       s = returnInfo(s);
       display(s);
       return 0;
    }
    
    Student returnInfo(Student s)
    {
       strcpy(s.name, "John Mathers");
       s.roll = 32;
    	
       return s;
    }
    
    void display(Student s)
    {
       cout << "Person Name: " << s.name<<endl;
       cout << "Person Roll: " << s.roll;
    }

    The output of this program is the same as the output of the above program.

    In this program, the structure variable s stores the returned value from returnInfo() function where value is provided to structure members (s = returnInfo(s);).

    After that, the s is passed to display() function where the information os student is displayed.


  • C++ Pointer to Structure

    A pointer in C++ can also be created for a user-defined type like structure. It is similar to those pointers that point to the native data types such as int, float, etc.

    Visit pointers and structures to learn more about them.

    Creating pointer for structures:

    We create a pointer for structure in the same way we create a pointer for any other variable.

    struct Student *struct_pointer;

    Now we can store the address of the structure variable in the following way.

    struct_pointer = &s1;

    To access the members of a structure using a pointer can be achieved by -> operator such as:

    struct_pointer->name;

    Let us go through an example in order to understand its use in a program.


    Example of Pointer to Structure in C++

    #include <iostream>
    using namespace std;
    
    struct Distance
    {
       int meters;
       float centimeters;
    };
    
    int main()
    {
       Distance *ptr, len;
       ptr = &len;
    
       cout << "Enter meters value: ";
       cin >> (*ptr).meters;
    
       cout << "Enter centimeters value: ";
       cin >> (*ptr).centimeters;
    	
       //display
       cout << "Distance = " << (*ptr).meters << "m " << (*ptr).centimeters << "cm";
    
       return 0;
    }

    Output:

    Enter meters value: 8
    Enter centimeters value: 25
    Distance = 8m 25cm

    Also, as you can see in the above program we use . (dot operator) to access members from the pointer. However, -> operator is preferred over . (dot operator) while using pointers. Because . (dot operator) has higher precedence than the * operator that is why we enclose the pointer within brackets (*ptr).meters. Therefore we can conclude the following:

    (*ptr).meters is same as ptr->meters
    (*ptr).centimeters is same as ptr->centimeters


  • C++ Structures

    In the C/C++ programming language, the structure is user-defined data types that allow us to store the combination of different data types together. All the different data type variables are represented by a single name.

    Unlike an array that holds the data of the same type, the structure holds the data of different types in a contiguous memory location. It begins with the keyword struct.

    Suppose, we want to keep the record of students with their name(string), roll_no(int), address(string), Score(float) and these are of different data types. So instead of creating a different variable, again and again, we can simply create members for each student with their respective data.

    Syntax of struct in C++:

    The keyword used to define the structure is struct.

    struct structure_name 
    {  
        data_type member1;  
        data_type member2;
        data_type member3; 
        ... 
        ...  
    };  

    Consider basic data of student: name, roll_no, score.
    student structure is declared in the following way:

    struct student
    {
      char name[30];
      int roll_no;
      float score;
     };

    Declaring Structure variable

    It means creating an instance of a structure in order to access the members of the structure. Once the structure student is declared, its variable is created by adding the following in the main function.

    struct student s1, s2;

    s1 and s2 are structure variables of the type Student. These are like the objects for the student just like an object in C++. When these variables are created, memory is allocated by the compiler.


    Accessing Struct Members

    The structure variable can be accessed by using a dot (.) operator.

    Suppose you want to access the score of an s1 student and assign it with a value of 80. This work can be performed in the following way.

    s1.score = 80;


    Example of C++ Structure

    #include <iostream>
    #include <cstring>
    using namespace std;
    
    struct Student
    {
        char name[50];
        int roll;
        float score;
    };
    
    int main()
    {
        Student s1, s2;
        
        //Accessing Student members
        strcpy(s1.name, "John Mac");
        s1.roll = 101; 
        s1.score = 92.15;
        
        strcpy(s2.name, "Mickey Macguel");
        s2.roll = 102; 
        s2.score = 80;
        
        //Display student 1 Info   
       cout << "Student 1 Information" <<endl;    
       cout << "Name: " << s1.name <<endl;    
       cout << "Roll No: " << s1.roll <<endl;
       cout << "Score: " << s1.score <<endl <<endl;
       
       //Display student 2 Info
       cout << "Student 2 Information" <<endl; 
       cout << "Name: " << s2.name <<endl;    
       cout << "Roll No: " << s2.roll <<endl;
       cout << "Score: " << s2.score <<endl;
        
    
        return 0;
    }

    Output:

    Student 1 Information
    Name: John Mac
    Roll No: 101
    Score: 92.15

    Student 2 Information
    Name: Mickey Macguel
    Roll No: 102
    Score: 80


    After learning structure, go through the following topics in structure:


  • C++ Static Keyword

    Static is a keyword in C++ that is when used with different types gives different meanings. static keyword can be used with variables in a function or class or with the static members of a class such as Class objects and Functions in a class.

    When is used with any of the mentioned above, it cannot be modified in the future. static elements are allocated storage only once in a program lifetime.

    Static Keyword can be used with the following in c++.

    1. Static variables in a functions
    2. Static Class Objects
    3. Static member Variable in class
    4. Static Methods in a class

    1. Static variables in a Function

    A variable declared static in a program is allocated to a static storage area. The static variables are only initialized only once in a program even if it is called multiple times in a program. It is useful when you do need to reset the counter even after multiple calls of the function.

    Example of a static variable inside a function in c++

    #include <iostream>
    using namespace std;
      
    void counter()
    { 
        // static variable
        static int count = 0;
        cout << count << " ";
        
        //updating counter but does not reset
        count++;
    }
      
    int main()
    {
        for (int i=0; i<=3; i++)    
            counter();
        return 0;
    }

    Output:

    //Output
    0 1 2 3

    2. Static class Objects

    The class objects are declared as static works the same in the same way as static variables. The objects declared static are allocated to a static storage area and have a scope till the lifetime of the program.

    Example of a static class object in c++

    #include <iostream>
    using namespace std;
      
    class Eg
    {
        int i;
        public:
            Eg()
            {
                i=0;
                cout << "CONSTRUCTOR" << endl;
            }
            ~Eg()
            {
                cout << "DESTRUCTOR" << endl;
            }
    };
    
    int main()
    {
        int x = 0;
        if(x == 0)
        {
            static Eg eg;
        }
        cout << "END" << endl;
    }

    Output:

    CONSTRUCTOR
    END
    DESTRUCTOR

    As you can see the destructor is called after the end of the main function because the scope of static object is throughout the lifetime of the program.


    3. Static Data Members inside a class:

    Static variables of a class are shared by all the objects and these members are initialized once and allocated a separate single static storage. Each object does not have a separate copy of those variables.

    Also, static data members are not initialized using the constructor as they are not dependent on variable initialization.

    Example of a Static Data Members inside a class in c++

    #include<iostream>
    using namespace std;
      
    class Abc
    {
       public:
         static int x; //static member
          
         Abc()
         {
            // Do nothing
         };
    };
      
    int Abc::x = 1;
    
    int main()
    {
      Abc obj;
    
      obj.x = 10;
        
      // display x
      cout << obj.x;   
    }

    Output:

    //Output
    10

    As you can see, it has to be explicitly initialized outside the class with a class name and scope resolution operator.


    4. Static function in a class

    Just like static data variables in a class, the static function also does not depend on the object of the class. We cannot call or invoke the static function of a class using object or ‘.‘ operator. But can be invoked using the class name and the scope resolution operator.

    However, these functions can only access the static data members and static member functions as it does not have ‘this‘ keyword.

    Example of a Static function in a class in c++

    #include<iostream>
    using namespace std;
      
    class Abc
    {
      public:
        // static member function
        static void display()
        {
            cout<<"This is simple2code.com";
        }
    };
      
    int main()
    {
        //static member function invoked
        Abc :: display();
    }

    Output:

    //Output
    This is simple2code.com