C++ Data Types ”; Previous Next While writing program in any language, you need to use various variables to store various information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. You may like to store information of various data types like character, wide character, integer, floating point, double floating point, boolean etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Primitive Built-in Types C++ offers the programmer a rich assortment of built-in as well as user defined data types. Following table lists down seven basic C++ data types − Type Keyword Boolean bool Character char Integer int Floating point float Double floating point double Valueless void Wide character wchar_t Several of the basic types can be modified using one or more of these type modifiers − signed unsigned short long The following table shows the variable type, how much memory it takes to store the value in memory, and what is maximum and minimum value which can be stored in such type of variables. Type Typical Bit Width Typical Range char 1byte -127 to 127 or 0 to 255 unsigned char 1byte 0 to 255 signed char 1byte -127 to 127 int 4bytes -2147483648 to 2147483647 unsigned int 4bytes 0 to 4294967295 signed int 4bytes -2147483648 to 2147483647 short int 2bytes -32768 to 32767 unsigned short int 2bytes 0 to 65,535 signed short int 2bytes -32768 to 32767 long int 8bytes -9223372036854775808 to 9223372036854775807 signed long int 8bytes same as long int unsigned long int 8bytes 0 to 18446744073709551615 long long int 8bytes -(2^63) to (2^63)-1 unsigned long long int 8bytes 0 to 18,446,744,073,709,551,615 float 4bytes double 8bytes long double 12bytes wchar_t 2 or 4 bytes 1 wide character The size of variables might be different from those shown in the above table, depending on the compiler and the computer you are using. Following is the example, which will produce correct size of various data types on your computer. Live Demo #include <iostream> using namespace std; int main() { cout << “Size of char : ” << sizeof(char) << endl; cout << “Size of int : ” << sizeof(int) << endl; cout << “Size of short int : ” << sizeof(short int) << endl; cout << “Size of long int : ” << sizeof(long int) << endl; cout << “Size of float : ” << sizeof(float) << endl; cout << “Size of double : ” << sizeof(double) << endl; cout << “Size of wchar_t : ” << sizeof(wchar_t) << endl; return 0; } This example uses endl, which inserts a new-line character after every line and << operator is being used to pass multiple values out to the screen. We are also using sizeof() operator to get size of various data types. When the above code is compiled and executed, it produces the following result which can vary from machine to machine − Size of char : 1 Size of int : 4 Size of short int : 2 Size of long int : 4 Size of float : 4 Size of double : 8 Size of wchar_t : 4 Following is another example: #include <iostream> #include <limits> using namespace std; int main() { std::cout << “Int Min ” << std::numeric_limits<int>::min() << endl; std::cout << “Int Max ” << std::numeric_limits<int>::max() << endl; std::cout << “Unsigned Int Min ” << std::numeric_limits<unsigned int>::min() << endl; std::cout << “Unsigned Int Max ” << std::numeric_limits<unsigned int>::max() << endl; std::cout << “Long Int Min ” << std::numeric_limits<long int>::min() << endl; std::cout << “Long Int Max ” << std::numeric_limits<long int>::max() << endl; std::cout << “Unsigned Long Int Min ” << std::numeric_limits<unsigned long int>::min() <<endl; std::cout << “Unsigned Long Int Max ” << std::numeric_limits<unsigned long int>::max() << endl; } typedef Declarations You can create a new name for an existing type using typedef. Following is the simple syntax to define a new type using typedef − typedef type newname; For example, the following tells the compiler that feet is another name for int − typedef int feet; Now, the following declaration is perfectly legal and creates an integer variable called distance − feet distance; Enumerated Types An enumerated type declares an optional type name and a set of zero or more identifiers that can be used as values of the type. Each enumerator is a constant whose type is the enumeration. Creating an enumeration requires the use of the keyword enum. The general form of an enumeration type is − enum enum-name { list of names } var-list; Here, the enum-name is the enumeration”s type name. The list of names is comma separated. For example, the following code defines an enumeration of colors called colors and the variable c of type color. Finally, c is assigned the value “blue”. enum color { red, green, blue } c; c = blue; By default, the value of the first name is 0, the second name has the value 1, and the third has the value 2, and so on. But you can give a name, a specific value by adding an initializer. For example, in the following enumeration, green will have the value 5. enum color { red, green = 5, blue }; Here, blue will have a value of 6 because each name will be one greater than the one that precedes it. Print Page Previous Next Advertisements ”;
Category: cplusplus
C++ Boolean Data Type
C++ Boolean (bool) Data Type ”; Previous Next The bool data type in C++ stands for Boolean values, which are True and False. In C++, 1 stands for True whereas 0 stands for False. The keyword “bool” is used to declare a Boolean data type. The addition of bool data type is a one of the newer features of C++ language. Use of Boolean Data Type The Boolean (bool) data type is used in the following ways − In conditions where we need to have binary values, i.e., values which represent two states of a variable. When we need to run loops based on certain conditions, we use bool data types. In case of having null values, we generally relate them to bool data types. For comparing two values for equality or inequality, we generally use bool data types. Values of Boolean (bool) Data Type The bool data types in C++ can have one of two values, and these values are as follows − True or 1 False or 0 As stated earlier, Boolean 1 means true whereas Boolean 0 means false in C++ compilation. Creating a Boolean Variable We can declare a Boolean variable using the “bool” keyword followed by the variable name. Syntax Use the following syntax to create a Boolean type variable − bool variable_name = [value]; Here, [value] is an optional and can be used to assign value during the declaration. Example In the following examples, we are declaring a Boolean variable, assigning a value to it. // C++ program to demonstrate // bool data type #include <iostream> using namespace std; // Driver code int main() { bool flag; flag=1;//this is true cout<<flag; return 0; } Example of bool Data Type The following example demonstrate the use of Boolean (bool) data type − // C++ program to demonstrate // bool data type #include <iostream> using namespace std; int main(){ bool flag; flag=1;//this is true bool flag1=true; cout<<flag<<” “<<flag1<<endl; int count=0; while(flag){ //condition where flag is true count++; if(count>=3) flag=false; } cout<<count<<” “<<flag<<endl; if(flag1) cout<<“True flag1″<<endl; else cout<<“False flag1″<<endl; return 0; } Output 1 1 3 0 True flag1 Implicit Conversion of Bool Variables Boolean data types can be implicitly converted to numeric data types, and vice-versa. This is possible as any value greater than 0 has a Boolean true value, whereas any value less than or equal to 0 has a Boolean false value. Also, the Boolean values can be added in form of integers to integral variables, using implicit conversion techniques. Hence, when we add a Boolean value to an integer, it gets incremented by 1 if the value is true, otherwise it remains same as false value corresponds to 0. Example This is clearly explained in the examples given below − // C++ program to demonstrate // bool data type #include <iostream> using namespace std; int main() { bool flag; flag=1;//this is true bool flag1=true; cout<<flag<<” “<<flag1<<endl; int count=0; int x=12; float y=35.45; bool k=count, k1=x, k2=y; int sum=x+flag+flag1; cout<<k<<” “<<count<<” “<<k1<<” “<<x<<” “<<k2<<” “<<y<<” “<<endl; cout<<”After adding Boolean and integer values : ”<< sum<<endl; return 0; } Print Page Previous Next Advertisements ”;
C++ Programming Tutorial
C++ Tutorial Job Search PDF Version Quick Guide Resources Discussion This C++ tutorial has been written by experienced C++ programmers which helps beginners to advanced programmers while learning C++ in simple and easy step. This tutorial uses a simple and practical approach to describe the concepts of C++ to software engineers. What is C++? C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. C++ is an extension of C programming language with object-oriented programming concepts. Or, we can say “C++ is a super set of C programming with additional implementation of object-oriented concepts”. Why to Learn C++ C++ is an important programming language for the students and working professionals to become a great Software Developer. I will list down some of the key advantages of learning C++: C++ is very close to hardware, so you get a chance to work at a low level which gives you lot of control in terms of memory management, better performance and finally a robust software development. C++ programming gives you a clear understanding about Object Oriented Programming. You will understand low level implementation of polymorphism when you will implement virtual tables and virtual table pointers, or dynamic type identification. C++ is one of the every green programming languages and loved by millions of software developers. If you are a great C++ programmer then you will never sit without work and more importantly you will get highly paid for your work. C++ is the most widely used programming languages in application and system programming. So you can choose your area of interest of software development. C++ really teaches you the difference between compiler, linker and loader, different data types, storage classes, variable types their scopes etc. There are 1000s of good reasons to learn C++ Programming. But one thing for sure, to learn any programming language, not only C++, you just need to code, and code and finally code until you become expert. Hello, World! Program Using C++ Just to give you a little excitement about C++ programming, I”m going to give you a small conventional C++ Hello World program, You can try it by clicking on “Edit & Run”. Below is the code to print “Hello World” on the screen − #include <iostream> using namespace std; // main() is where program execution begins. int main() { cout << “Hello, World!”; // prints Hello, World! return 0; } C++ Online Compiler We provided an easy, user-friendly, and fast C++ online compiler, where you can write, save, run, and share your C++ programs. Click on this link to open it: C++ Online Compiler. Try to click the icon to run the following C++ code to print conventional “Hello, World!” using C++ Programming. #include <iostream> using namespace std; int main() { cout << “Hello, World!”; // prints Hello, World! return 0; } There are many C++ compilers available which you can use to compile and run above mentioned program: Apple C++. Xcode Bloodshed Dev-C++ Clang C++ Cygwin (GNU C++) Mentor Graphics MINGW – “Minimalist GNU for Windows” GNU CC source IBM C++ Intel C++ Microsoft Visual C++ Oracle C++ HP C++ Features of C++ The following are the features of C++ programming language − C language compatibility: C++ provides backward compatibility with C, it supports all features of C language. Object-oriented programming: C++ supports the concepts of OOPs such as objects & classes, encapsulation, data binding, inheritance, and polymorphism. Compiled language: C++ is a compiler language where the complete code is converted into machine language, which makes it a faster programming language. Standard template library: C++ provides many data structures and algorithms-related library collections, such as template libraries for contains, iterators, algorithms, etc. Dynamic memory management: C++ provides two operators new and delete that help to allocate and deallocate memory blocks dynamically. Exceptional handling: C++ provides try, catch, and throw blocks for exceptional handling, which were not available in C programming. Applications of C++ Programming As mentioned before, C++ is one of the most widely used programming languages. It has it”s presence in almost every area of software development. I”m going to list few of them here: Application Software Development – C++ programming has been used in developing almost all the major Operating Systems like Windows, Mac OSX and Linux. Apart from the operating systems, the core part of many browsers like Mozilla Firefox and Chrome have been written using C++. C++ also has been used in developing the most popular database system called MySQL. Programming Languages Development – C++ has been used extensively in developing new programming languages like C#, Java, JavaScript, Perl, UNIX”s C Shell, PHP, Python, and Verilog etc. Computation Programming – C++ is the best friends of scientists because of fast speed and computational efficiencies. Games Development – C++ is extremely fast which allows programmers to do procedural programming for CPU intensive functions and provides greater control over hardware, because of which it has been widely used in development of gaming engines. Embedded System – C++ is being heavily used in developing Medical and Engineering Applications like softwares for MRI machines, high-end CAD/CAM systems etc. This list goes on, there are various areas where software developers are happily using C++ to provide great softwares. I highly recommend you to learn C++ and contribute great softwares to the community. Learn C++ By Examples Practicing C++ examples is the best way to learn C++ programming. All chapters of our C++ tutorial have the related examples with explanation. You can simply go through those examples to understand the concept better. Jobs or Careers in C++ C++ is a versatile and widely used programming language. Here is the list of some job roles that you can get after learning C++ programming: Software Engineer Game Developer Systems Programmer Embedded System Developer Robotics Engineer Database Developer Graphics Programmer Here is the list of the companies hiring C++ developers: Microsoft
C++ Multithreading
C++ Multithreading ”; Previous Next Multithreading is a specialized form of multitasking and a multitasking is the feature that allows your computer to run two or more programs concurrently. In general, there are two types of multitasking: process-based and thread-based. Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Before C++ 11, there is no built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature. This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C++ program using POSIX. POSIX Threads, or Pthreads provides API which are available on many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris. Creating Threads The following routine is used to create a POSIX thread − #include <pthread.h> pthread_create (thread, attr, start_routine, arg) Here, pthread_create creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code. Here is the description of the parameters − Sr.No Parameter & Description 1 thread An opaque, unique identifier for the new thread returned by the subroutine. 2 attr An opaque attribute object that may be used to set thread attributes. You can specify a thread attributes object, or NULL for the default values. 3 start_routine The C++ routine that the thread will execute once it is created. 4 arg A single argument that may be passed to start_routine. It must be passed by reference as a pointer cast of type void. NULL may be used if no argument is to be passed. The maximum number of threads that may be created by a process is implementation dependent. Once created, threads are peers, and may create other threads. There is no implied hierarchy or dependency between threads. Terminating Threads There is following routine which we use to terminate a POSIX thread − #include <pthread.h> pthread_exit (status) Here pthread_exit is used to explicitly exit a thread. Typically, the pthread_exit() routine is called after a thread has completed its work and is no longer required to exist. If main() finishes before the threads it has created, and exits with pthread_exit(), the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes. Example This simple example code creates 5 threads with the pthread_create() routine. Each thread prints a “Hello World!” message, and then terminates with a call to pthread_exit(). #include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; #define NUM_THREADS 5 void *PrintHello(void *threadid) { long tid; tid = (long)threadid; cout << “Hello World! Thread ID, ” << tid << endl; pthread_exit(NULL); } int main () { pthread_t threads[NUM_THREADS]; int rc; int i; for( i = 0; i < NUM_THREADS; i++ ) { cout << “main() : creating thread, ” << i << endl; rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i); if (rc) { cout << “Error:unable to create thread,” << rc << endl; exit(-1); } } pthread_exit(NULL); } Compile the following program using -lpthread library as follows − $gcc test.cpp -lpthread Now, execute your program which gives the following output − main() : creating thread, 0 main() : creating thread, 1 main() : creating thread, 2 main() : creating thread, 3 main() : creating thread, 4 Hello World! Thread ID, 0 Hello World! Thread ID, 1 Hello World! Thread ID, 2 Hello World! Thread ID, 3 Hello World! Thread ID, 4 Passing Arguments to Threads This example shows how to pass multiple arguments via a structure. You can pass any data type in a thread callback because it points to void as explained in the following example − #include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; #define NUM_THREADS 5 struct thread_data { int thread_id; char *message; }; void *PrintHello(void *threadarg) { struct thread_data *my_data; my_data = (struct thread_data *) threadarg; cout << “Thread ID : ” << my_data->thread_id ; cout << ” Message : ” << my_data->message << endl; pthread_exit(NULL); } int main () { pthread_t threads[NUM_THREADS]; struct thread_data td[NUM_THREADS]; int rc; int i; for( i = 0; i < NUM_THREADS; i++ ) { cout <<“main() : creating thread, ” << i << endl; td[i].thread_id = i; td[i].message = “This is message”; rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&td[i]); if (rc) { cout << “Error:unable to create thread,” << rc << endl; exit(-1); } } pthread_exit(NULL); } When the above code is compiled and executed, it produces the following result − main() : creating thread, 0 main() : creating thread, 1 main() : creating thread, 2 main() : creating thread, 3 main() : creating thread, 4 Thread ID : 3 Message : This is message Thread ID : 2 Message : This is message Thread ID : 0 Message : This is message Thread ID : 1 Message : This is message Thread ID : 4 Message : This is message Joining and Detaching Threads There are following two routines which we can use to join or detach threads − pthread_join (threadid, status) pthread_detach (threadid) The pthread_join() subroutine blocks the calling thread until the specified ”threadid” thread terminates. When a thread is created, one of its attributes defines whether it is joinable or detached. Only threads that are created as joinable can be joined. If a thread is created as detached, it can never be joined. This example demonstrates how to wait for thread completions by using the Pthread join routine. #include <iostream> #include <cstdlib> #include <pthread.h> #include <unistd.h> using namespace std; #define NUM_THREADS 5 void *wait(void *t) { int i; long tid; tid = (long)t; sleep(1); cout << “Sleeping in thread ” << endl; cout << “Thread with id : ” << tid << ” …exiting ” << endl; pthread_exit(NULL); } int main () { int rc; int
C++ Signal Handling
C++ Signal Handling ”; Previous Next Signals are the interrupts delivered to a process by the operating system which can terminate a program prematurely. You can generate interrupts by pressing Ctrl+C on a UNIX, LINUX, Mac OS X or Windows system. There are signals which can not be caught by the program but there is a following list of signals which you can catch in your program and can take appropriate actions based on the signal. These signals are defined in C++ header file <csignal>. Sr.No Signal & Description 1 SIGABRT Abnormal termination of the program, such as a call to abort. 2 SIGFPE An erroneous arithmetic operation, such as a divide by zero or an operation resulting in overflow. 3 SIGILL Detection of an illegal instruction. 4 SIGINT Receipt of an interactive attention signal. 5 SIGSEGV An invalid access to storage. 6 SIGTERM A termination request sent to the program. The signal() Function C++ signal-handling library provides function signal to trap unexpected events. Following is the syntax of the signal() function − void (*signal (int sig, void (*func)(int)))(int); Keeping it simple, this function receives two arguments: first argument as an integer which represents signal number and second argument as a pointer to the signal-handling function. Let us write a simple C++ program where we will catch SIGINT signal using signal() function. Whatever signal you want to catch in your program, you must register that signal using signal function and associate it with a signal handler. Examine the following example − #include <iostream> #include <csignal> using namespace std; void signalHandler( int signum ) { cout << “Interrupt signal (” << signum << “) received.n”; // cleanup and close up stuff here // terminate program exit(signum); } int main () { // register signal SIGINT and signal handler signal(SIGINT, signalHandler); while(1) { cout << “Going to sleep….” << endl; sleep(1); } return 0; } When the above code is compiled and executed, it produces the following result − Going to sleep…. Going to sleep…. Going to sleep…. Now, press Ctrl+c to interrupt the program and you will see that your program will catch the signal and would come out by printing something as follows − Going to sleep…. Going to sleep…. Going to sleep…. Interrupt signal (2) received. The raise() Function You can generate signals by function raise(), which takes an integer signal number as an argument and has the following syntax. int raise (signal sig); Here, sig is the signal number to send any of the signals: SIGINT, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGTERM, SIGHUP. Following is the example where we raise a signal internally using raise() function as follows − #include <iostream> #include <csignal> using namespace std; void signalHandler( int signum ) { cout << “Interrupt signal (” << signum << “) received.n”; // cleanup and close up stuff here // terminate program exit(signum); } int main () { int i = 0; // register signal SIGINT and signal handler signal(SIGINT, signalHandler); while(++i) { cout << “Going to sleep….” << endl; if( i == 3 ) { raise( SIGINT); } sleep(1); } return 0; } When the above code is compiled and executed, it produces the following result and would come out automatically − Going to sleep…. Going to sleep…. Going to sleep…. Interrupt signal (2) received. Print Page Previous Next Advertisements ”;
C++ Structures
C++ Structures (struct) ”; Previous Next C/C++ arrays allow you to define variables that combine several data items of the same kind, but structure is another user defined data type which allows you to combine data items of different kinds. Structures are used to represent a record, suppose you want to keep track of your books in a library. You might want to track the following attributes about each book − Title Author Subject Book ID Defining a Structure To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member, for your program. The format of the struct statement is this − struct [structure tag] { member definition; member definition; … member definition; } [one or more structure variables]; The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure”s definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure − struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } book; Accessing Structure Members To access any member of a structure, we use the 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 would use struct keyword to define variables of structure type. Following is the example to explain usage of structure − Live Demo #include <iostream> #include <cstring> using namespace std; struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; int main() { struct Books Book1; // Declare Book1 of type Book struct Books Book2; // Declare Book2 of type Book // book 1 specification strcpy( Book1.title, “Learn C++ Programming”); strcpy( Book1.author, “Chand Miyan”); strcpy( Book1.subject, “C++ Programming”); Book1.book_id = 6495407; // book 2 specification strcpy( Book2.title, “Telecom Billing”); strcpy( Book2.author, “Yakit Singha”); strcpy( Book2.subject, “Telecom”); Book2.book_id = 6495700; // Print Book1 info cout << “Book 1 title : ” << Book1.title <<endl; cout << “Book 1 author : ” << Book1.author <<endl; cout << “Book 1 subject : ” << Book1.subject <<endl; cout << “Book 1 id : ” << Book1.book_id <<endl; // Print Book2 info cout << “Book 2 title : ” << Book2.title <<endl; cout << “Book 2 author : ” << Book2.author <<endl; cout << “Book 2 subject : ” << Book2.subject <<endl; cout << “Book 2 id : ” << Book2.book_id <<endl; return 0; } When the above code is compiled and executed, it produces the following result − Book 1 title : Learn C++ Programming Book 1 author : Chand Miyan Book 1 subject : C++ Programming Book 1 id : 6495407 Book 2 title : Telecom Billing Book 2 author : Yakit Singha Book 2 subject : Telecom Book 2 id : 6495700 Structures as Function Arguments You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example − Live Demo #include <iostream> #include <cstring> using namespace std; void printBook( struct Books book ); struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; int main() { struct Books Book1; // Declare Book1 of type Book struct Books Book2; // Declare Book2 of type Book // book 1 specification strcpy( Book1.title, “Learn C++ Programming”); strcpy( Book1.author, “Chand Miyan”); strcpy( Book1.subject, “C++ Programming”); Book1.book_id = 6495407; // book 2 specification strcpy( Book2.title, “Telecom Billing”); strcpy( Book2.author, “Yakit Singha”); strcpy( Book2.subject, “Telecom”); Book2.book_id = 6495700; // Print Book1 info printBook( Book1 ); // Print Book2 info printBook( Book2 ); return 0; } void printBook( struct Books book ) { cout << “Book title : ” << book.title <<endl; cout << “Book author : ” << book.author <<endl; cout << “Book subject : ” << book.subject <<endl; cout << “Book id : ” << book.book_id <<endl; } When the above code is compiled and executed, it produces the following result − Book title : Learn C++ Programming Book author : Chand Miyan Book subject : C++ Programming Book id : 6495407 Book title : Telecom Billing Book author : Yakit Singha Book subject : Telecom Book id : 6495700 Pointers to Structures You can define pointers to structures in very similar way as you define pointer to any other variable as follows − struct Books *struct_pointer; Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the & operator before the structure”s name as follows − struct_pointer = &Book1; To access the members of a structure using a pointer to that structure, you must use the -> operator as follows − struct_pointer->title; Let us re-write above example using structure pointer, hope this will be easy for you to understand the concept − Live Demo #include <iostream> #include <cstring> using namespace std; void printBook( struct Books *book ); struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; int main() { struct Books Book1; // Declare Book1 of type Book struct Books Book2; // Declare Book2 of type Book // Book 1 specification strcpy( Book1.title, “Learn C++ Programming”); strcpy( Book1.author, “Chand Miyan”); strcpy( Book1.subject, “C++ Programming”); Book1.book_id = 6495407; // Book 2 specification strcpy( Book2.title, “Telecom Billing”); strcpy( Book2.author, “Yakit Singha”); strcpy( Book2.subject, “Telecom”); Book2.book_id = 6495700; // Print Book1 info, passing address of structure printBook( &Book1 ); // Print Book1 info, passing address of structure printBook( &Book2 ); return 0; } // This function accept pointer to structure as parameter. void printBook( struct Books *book ) { cout << “Book title : ” << book->title <<endl; cout << “Book author : ” << book->author <<endl; cout << “Book subject
C++ Namespaces
Namespaces in C++ ”; Previous Next Consider a situation, when we have two persons with the same name, Zara, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother’s or father’s name, etc. Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code. A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope. Defining a Namespace A namespace definition begins with the keyword namespace followed by the namespace name as follows − namespace namespace_name { // code declarations } To call the namespace-enabled version of either function or variable, prepend (::) the namespace name as follows − name::code; // code could be variable or function. Let us see how namespace scope the entities including variable and functions − Live Demo #include <iostream> using namespace std; // first name space namespace first_space { void func() { cout << “Inside first_space” << endl; } } // second name space namespace second_space { void func() { cout << “Inside second_space” << endl; } } int main () { // Calls function from first name space. first_space::func(); // Calls function from second name space. second_space::func(); return 0; } If we compile and run above code, this would produce the following result − Inside first_space Inside second_space The using directive You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. The namespace is thus implied for the following code − Live Demo #include <iostream> using namespace std; // first name space namespace first_space { void func() { cout << “Inside first_space” << endl; } } // second name space namespace second_space { void func() { cout << “Inside second_space” << endl; } } using namespace first_space; int main () { // This calls function from first name space. func(); return 0; } If we compile and run above code, this would produce the following result − Inside first_space The ‘using’ directive can also be used to refer to a particular item within a namespace. For example, if the only part of the std namespace that you intend to use is cout, you can refer to it as follows − using std::cout; Subsequent code can refer to cout without prepending the namespace, but other items in the std namespace will still need to be explicit as follows − Live Demo #include <iostream> using std::cout; int main () { cout << “std::endl is used with std!” << std::endl; return 0; } If we compile and run above code, this would produce the following result − std::endl is used with std! Names introduced in a using directive obey normal scope rules. The name is visible from the point of the using directive to the end of the scope in which the directive is found. Entities with the same name defined in an outer scope are hidden. Discontiguous Namespaces A namespace can be defined in several parts and so a namespace is made up of the sum of its separately defined parts. The separate parts of a namespace can be spread over multiple files. So, if one part of the namespace requires a name defined in another file, that name must still be declared. Writing a following namespace definition either defines a new namespace or adds new elements to an existing one − namespace namespace_name { // code declarations } Nested Namespaces Namespaces can be nested where you can define one namespace inside another name space as follows − namespace namespace_name1 { // code declarations namespace namespace_name2 { // code declarations } } You can access members of nested namespace by using resolution operators as follows − // to access members of namespace_name2 using namespace namespace_name1::namespace_name2; // to access members of namespace:name1 using namespace namespace_name1; In the above statements if you are using namespace_name1, then it will make elements of namespace_name2 available in the scope as follows − Live Demo #include <iostream> using namespace std; // first name space namespace first_space { void func() { cout << “Inside first_space” << endl; } // second name space namespace second_space { void func() { cout << “Inside second_space” << endl; } } } using namespace first_space::second_space; int main () { // This calls function from second name space. func(); return 0; } If we compile and run above code, this would produce the following result − Inside second_space Print Page Previous Next Advertisements ”;
C++ – Advanced Concepts
Advanced C++ Concepts ”; Previous Next C++ is a one of the foundation languages of modern programming. It has evolved out of the basic C into a very powerful tool in modern programming. The versions of C++ started with C++ 98, and are now upto C++ 20. After the update of C++ 11, all modern updates are known collectively as modern C++. These new models have vast and new features, making the language more user- friendly and better feature-equipped. Some of these new concepts were already part of other new languages like Ethereum, Ruby, Python, and Javascript, and with the introduction of these concepts in C++, programming has become more efficient today. Here is a list of different Advanced C++ topics we are going to understand in detail − RAII Wild Pointers Null Pointer Memory Leakage Smart Pointers Lambda Expression With the version of C++ 20, other features are also available, which are a slightly more advanced and would be covered in the later parts of this post. The features mentioned above are far advanced concepts as well, but the explanation provided in this post shall be adequate for readers to deep dive into the MODERN C++ LANGUAGE. RAII (Resource Aquisition is Initialization) Resource Acquisition is Initialization, often referred to by its acronym RAII, is a C++ technique which is used for memory management. Although it’s association with C++ is typically why it is studied, the scope of RAII extends beyond the barriers of language restrictions. To simply put up a definition, RAII means assigning memory to an object in form of a constructor, and then releasing the assigned memory using a destructor. Hence, it forms a part of OOP concepts, which was covered in the past topics. Now, you must be curious to know what problems does RAII actually solve? RAII works in many ways, some of which are − Mutex Locks (covered in Operating Systems) Process Synchronization Multithreading Dynamic Memory Allocation Some of these topics have already been discussed in the previous parts of this section, and some new concepts are discussed in the later parts of this post. Now, what is actually a resource in programming, particularly in terms of OOPS? A resource is an entity that can be required during the compilation or execution of a program or a sequence of programs. Examples of resources are Stack, Heap, Memory, Files, Sockets (in socket programming), Locks and Semaphores, etc. These resources are crucial for the smooth working of a program. These are acquired by the program through requests, like mutex() method calls for a mutex lock to be acquired. In classical programming using C, we use concepts of new() and delete() to create entities and then deallocate memory. This traditional concept, while still acceptable in OOP languages like C++, is however, discouraged. In C++, the concept of RAII makes it easy for allocation and deallocation of resources within a scope. The tenure of a new quantity is the tenure of the object, and while a constructor can create and assign memory to an object, a destructor can be used to simply release the memory after completion automatically. This makes C++ a very efficient and user-friendly language. Let’s understand this with a simple example. Example #include <bits/stdc++.h> using namespace std; mutex m; void bad() { m.lock(); // acquire the mutex f(); // if f() throws an exception, the mutex is never released if (!everything_ok()) return; // early return, the mutex is never released m.unlock(); // if bad() reaches this statement, the mutex is released } void good(){ lock_guard<mutex> lk(m); // RAII class: mutex acquisition is initialization f(); // if f() throws an exception, the mutex is released if (!everything_ok()) return; // early return, the mutex is released } int main(){ good(); bad(); return 0; } Wild Pointers in C++ A pointer is called a wild pointer if it points randomly to any address in the memory. This happens when the pointer is declared in the program, but it is not initialized to point to an address value. Wild pointers are different from normal pointers i.e. they also store the memory addresses but point the unallocated memory or data value which has been deallocated. These pointers can cause memory leak, a topic that will be discussed in the later parts of this article. Example #include <bits/stdc++.h> using namespace std; int main() { int *ptr; //this pointer has been declared but not initialized //hence, it is a wild pointer cout<<*ptr<<endl; int a=11; ptr=&a; cout<<*ptr<<endl<<ptr<<endl; //once a value is declared, it becomes a normal pointer *ptr=10; cout<<*ptr<<endl<<ptr; return 0; } Output -660944088 11 0x7ffcfb77825c 10 0x7ffcfb77825c Null Pointers in C++ In earlier versions of C++, the NULL would be defined as a void element which points to no memory. The conversion of NULL to int or similar data types was allowed, but in case of overloading of functions, the NULL pointer throws error. Since the emergence of C++ 11, the NULL was redefined to nullptr, which is a special data type that can only be used as a pointer to point to an address that is not available in the memory. Hence, it can act as a pointer to any location on redefining the pointer variable. Unlike NULL, it is not implicitly convertible or comparable to integral types, like int or char. Hence, it solves the problem of NULL invariably. On a side note, comparison between null pointers is possible in the newer version of C++, and hence it can be comprehended that pointers are comparable to bool data type. Example #include <bits/stdc++.h> using namespace std; int main() { //int ptr=nullptr; //this throws compiler error
C++ Polymorphism
Polymorphism in C++ ”; Previous Next The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance. C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function. Consider the following example where a base class has been derived by other two classes − #include <iostream> using namespace std; class Shape { protected: int width, height; public: Shape( int a = 0, int b = 0){ width = a; height = b; } int area() { cout << “Parent class area :” << width * height << endl; return width * height; } }; class Rectangle: public Shape { public: Rectangle( int a = 0, int b = 0):Shape(a, b) { } int area () { cout << “Rectangle class area :” << width * height << endl; return (width * height); } }; class Triangle: public Shape { public: Triangle( int a = 0, int b = 0):Shape(a, b) { } int area () { cout << “Triangle class area :” << (width * height)/2 << endl; return (width * height / 2); } }; // Main function for the program int main() { Shape *shape; Rectangle rec(10,7); Triangle tri(10,5); // store the address of Rectangle shape = &rec; // call rectangle area. shape->area(); // store the address of Triangle shape = &tri; // call triangle area. shape->area(); return 0; } When the above code is compiled and executed, it produces the following result − Parent class area :70 Parent class area :50 The reason for the incorrect output is that the call of the function area() is being set once by the compiler as the version defined in the base class. This is called static resolution of the function call, or static linkage – the function call is fixed before the program is executed. This is also sometimes called early binding because the area() function is set during the compilation of the program. But now, let”s make a slight modification in our program and precede the declaration of area() in the Shape class with the keyword virtual so that it looks like this − #include <iostream> using namespace std; class Shape { protected: int width, height; public: Shape( int a = 0, int b = 0){ width = a; height = b; } virtual int area() { cout << “Parent class area :” << width * height << endl; return width * height; } }; class Rectangle: public Shape { public: Rectangle( int a = 0, int b = 0):Shape(a, b) { } int area () { cout << “Rectangle class area :” << width * height << endl; return (width * height); } }; class Triangle: public Shape { public: Triangle( int a = 0, int b = 0):Shape(a, b) { } int area () { cout << “Triangle class area :” << (width * height)/2 << endl; return (width * height / 2); } }; // Main function for the program int main() { Shape *shape; Rectangle rec(10,7); Triangle tri(10,5); // store the address of Rectangle shape = &rec; // call rectangle area. shape->area(); // store the address of Triangle shape = &tri; // call triangle area. shape->area(); return 0; } After this slight modification, when the previous example code is compiled and executed, it produces the following result − Rectangle class area :70 Triangle class area :25 This time, the compiler looks at the contents of the pointer instead of it”s type. Hence, since addresses of objects of tri and rec classes are stored in *shape the respective area() function is called. As you can see, each of the child classes has a separate implementation for the function area(). This is how polymorphism is generally used. You have different classes with a function of the same name, and even the same parameters, but with different implementations. Virtual Function A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don”t want static linkage for this function. What we do want is the selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding. Pure Virtual Functions It is possible that you want to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class, but that there is no meaningful definition you could give for the function in the base class. We can change the virtual function area() in the base class to the following − class Shape { protected: int width, height; public: Shape(int a = 0, int b = 0) { width = a; height = b; } // pure virtual function virtual int area() = 0; }; The = 0 tells the compiler that the function has no body and above virtual function will be called pure virtual function. Print Page Previous Next Advertisements ”;
C++ Preprocessor
C++ Preprocessor ”; Previous Next The preprocessors are the directives, which give instructions to the compiler to preprocess the information before actual compilation starts. All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not C++ statements, so they do not end in a semicolon (;). You already have seen a #include directive in all the examples. This macro is used to include a header file into the source file. There are number of preprocessor directives supported by C++ like #include, #define, #if, #else, #line, etc. Let us see important directives − The #define Preprocessor The #define preprocessor directive creates symbolic constants. The symbolic constant is called a macro and the general form of the directive is − #define macro-name replacement-text When this line appears in a file, all subsequent occurrences of macro in that file will be replaced by replacement-text before the program is compiled. For example − #include <iostream> using namespace std; #define PI 3.14159 int main () { cout << “Value of PI :” << PI << endl; return 0; } Now, let us do the preprocessing of this code to see the result assuming we have the source code file. So let us compile it with -E option and redirect the result to test.p. Now, if you check test.p, it will have lots of information and at the bottom, you will find the value replaced as follows − $gcc -E test.cpp > test.p … int main () { cout << “Value of PI :” << 3.14159 << endl; return 0; } Function-Like Macros You can use #define to define a macro which will take argument as follows − Live Demo #include <iostream> using namespace std; #define MIN(a,b) (((a)<(b)) ? a : b) int main () { int i, j; i = 100; j = 30; cout <<“The minimum is ” << MIN(i, j) << endl; return 0; } If we compile and run above code, this would produce the following result − The minimum is 30 Conditional Compilation There are several directives, which can be used to compile selective portions of your program”s source code. This process is called conditional compilation. The conditional preprocessor construct is much like the ‘if’ selection structure. Consider the following preprocessor code − #ifndef NULL #define NULL 0 #endif You can compile a program for debugging purpose. You can also turn on or off the debugging using a single macro as follows − #ifdef DEBUG cerr <<“Variable x = ” << x << endl; #endif This causes the cerr statement to be compiled in the program if the symbolic constant DEBUG has been defined before directive #ifdef DEBUG. You can use #if 0 statment to comment out a portion of the program as follows − #if 0 code prevented from compiling #endif Let us try the following example − Live Demo #include <iostream> using namespace std; #define DEBUG #define MIN(a,b) (((a)<(b)) ? a : b) int main () { int i, j; i = 100; j = 30; #ifdef DEBUG cerr <<“Trace: Inside main function” << endl; #endif #if 0 /* This is commented part */ cout << MKSTR(HELLO C++) << endl; #endif cout <<“The minimum is ” << MIN(i, j) << endl; #ifdef DEBUG cerr <<“Trace: Coming out of main function” << endl; #endif return 0; } If we compile and run above code, this would produce the following result − The minimum is 30 Trace: Inside main function Trace: Coming out of main function The # and ## Operators The # and ## preprocessor operators are available in C++ and ANSI/ISO C. The # operator causes a replacement-text token to be converted to a string surrounded by quotes. Consider the following macro definition − Live Demo #include <iostream> using namespace std; #define MKSTR( x ) #x int main () { cout << MKSTR(HELLO C++) << endl; return 0; } If we compile and run above code, this would produce the following result − HELLO C++ Let us see how it worked. It is simple to understand that the C++ preprocessor turns the line − cout << MKSTR(HELLO C++) << endl; Above line will be turned into the following line − cout << “HELLO C++” << endl; The ## operator is used to concatenate two tokens. Here is an example − #define CONCAT( x, y ) x ## y When CONCAT appears in the program, its arguments are concatenated and used to replace the macro. For example, CONCAT(HELLO, C++) is replaced by “HELLO C++” in the program as follows. Live Demo #include <iostream> using namespace std; #define concat(a, b) a ## b int main() { int xy = 100; cout << concat(x, y); return 0; } If we compile and run above code, this would produce the following result − 100 Let us see how it worked. It is simple to understand that the C++ preprocessor transforms − cout << concat(x, y); Above line will be transformed into the following line − cout << xy; Predefined C++ Macros C++ provides a number of predefined macros mentioned below − Sr.No Macro & Description 1 __LINE__ This contains the current line number of the program when it is being compiled. 2 __FILE__ This contains the current file name of the program when it is being compiled. 3 __DATE__ This contains a string of the form month/day/year that is the date of the translation of the source file into object code. 4 __TIME__ This contains a string of the form hour:minute:second that is the time at which the program was compiled. Let us see an example for all the above macros − Live Demo #include <iostream> using namespace std; int main () { cout << “Value of __LINE__ : ” << __LINE__ << endl; cout << “Value of __FILE__ : ” << __FILE__ << endl; cout << “Value of __DATE__ : ” << __DATE__ << endl; cout << “Value of __TIME__ : ” << __TIME__ << endl;