C++ is a programming language. A standardized, general- purpose, object-oriented, compiled language. C++ is accompanied by a set of functions and containers called the C++ Standard-Library.
C and C++ are two different languages. C++ started as “C with classes,” but it is now a completely different language. So, C++ is not C; C++ is not C with classes; it is just C++. And there is no such thing as a C/C++ programming language.
C++ is widely used for the so-called systems programming as well as application programming.
C++ is a language that allows us to get down to the metal where we can perform low-level routines if needed, or soar high with abstraction mechanisms such as templates and classes.
Bjarne Stroustrup joined the 1127 Computing Science Research Center of AT&T Bell Laboratories in 1979. Strongly influenced by the object-oriented model of the Simula language (created by Dahl and Nygaard), he began work on developing class extensions to the C language so that developers could write software using a far higher level of abstraction and sophistication while retaining the efficiency of C.
Stroustrup said, “My initial aim for C++ was a language where I could write programs that were as elegant as Simula programs, yet as efficient as C programs.” The first C++ language reference manual was published internally in 1984, and the C++ language was released commercially in 1985. C++ spread rapidly and became the dominant object-oriented programming language in the 1990s. The language remains one of the most widely used programming languages today.
Bjarne Stroustrup created C++ as an extension to a C programming language. Still, C++ evolved to be a completely different programming language.
C++ has evolved through several versions over time, each introducing new features and improvements. Here's a brief overview:
C90/C++98: The early standards introduced basic concepts like functions, loops, and arrays. C++98 added more advanced features such as templates, exceptions, namespaces, and the Standard Template Library (STL).
C++03: This version made small changes to C++98 and introduced std::auto_ptr, the explicit keyword for constructors, and other improvements.
C++11: A major update that introduced new features like lambdas, range-based for loops, type inference with auto, rvalue references, move semantics, variadic templates, and more. It also improved existing features like smart pointers.
C++14: Added minor features such as generic lambdas, binary literals, user-defined literals, and improvements to the STL.
C++17: Another major update with new features like structured bindings, if-statements with initializer clauses, coroutines, fold expressions, guaranteed copy elision, and more. It improved the STL with concepts, filesystem support, and more.
C++20: introduced concepts, coroutines, modules, co_await in lambdas, calendar and timezone support, improvements to the STL, and more.
C++23: introduces numerous enhancements, including improved constexpr functions, multidimensional subscript operators, and new standard library components like std::flat_map. It also enhances error handling with std::expected and simplifies lambda expressions for better usability.
Each standard builds upon the previous one, adding new features while improving safety and efficiency.
C++ is a powerful and versatile programming language that offers several key features which make it suitable for a wide range of applications. Here are the primary features of C++:
Object-Oriented Programming (OOP):
C++ supports OOP concepts like classes, objects, inheritance, polymorphism, and encapsulation.
Classes allow you to define your own data types with their own methods.
Performance:
C++ is a low-level language that provides direct hardware access, which means it can be much faster than high-level languages.
It allows for efficient memory management and fine-grained control over resources.
Memory Management:
C++ gives you complete control over dynamic memory allocation using new and delete.
This feature is crucial for applications that need to manage large amounts of data or those requiring optimization in resource usage.
Standard Template Library (STL):
The STL is a collection of ready-to-use classes and functions that simplify common programming tasks.
It includes containers like vectors, lists, maps, and algorithms like sort, search, and transform.
Templates:
C++ templates allow you to write generic code that can work with different data types without sacrificing performance.
This feature enhances code reusability and reduces errors.
Pointers and References:
Pointers in C++ provide a way to directly manipulate memory addresses, which is essential for low-level programming tasks such as file I/O, system programming, and graphics programming.
References are an alias for existing variables, providing another name to access the same data.
Overloading Operators:
You can redefine operators for user-defined types, making them more intuitive and easier to use.
This feature is particularly useful in implementing complex classes like matrices or vectors.
Exception Handling:
C++ provides mechanisms for handling errors that may occur during runtime using try, catch, and throw blocks.
This helps in writing robust and error-free applications.
Namespaces:
Namespaces help to avoid name clashes by encapsulating identifiers within a scope.
This is particularly useful as the number of libraries and APIs grows.
Preprocessor Directives:
C++ includes powerful preprocessor directives such as #include, #define, #ifdef, etc., which allow for conditional compilation, code reuse, and more.
Cross-Platform Compatibility:
While C++ is platform-dependent in terms of the system calls and low-level details, it can be compiled on various platforms using different compilers.
This makes C++ a popular choice for developing cross-platform applications.
Multi-Threading:
C++ supports multi-threading through libraries like <thread>, allowing you to write concurrent programs.
This is essential for modern applications that need to handle multiple tasks simultaneously, such as games or web servers.
These features make C++ a robust language suitable for both system-level and application development. Its flexibility and performance characteristics allow developers to tackle complex problems efficiently while maintaining control over the underlying hardware and software environment.
C++ programs are usually a collection of C++ code spread across one or multiple source files.
The C++ compiler compiles these files and turns them into object files. Object files are linked together by a linker to create an executable file or a library.
Some of the more popular C++ compilers are:
The g++ frontend (as part of the GCC)
Visual C++ (as part of the Visual Studio IDE)
Clang (as part of the LLVM)
To install a C++ compiler on Ubuntu Linux, type the following inside the terminal:
sudo apt-get install build-essential
To compile the C++ source file, we type:
g++ <filename>.cpp
This command will produce an executable with the default name of a.out. To run the executable file, type:
./a.out
To compile for a C++ standard like c++11, we add the - std=c++11 flag:
g++ -std=c++11 <filename>.cpp
To enable warnings, we add the -Wall flag:
g++ -Wall <filename>.cpp
To produce a custom executable name, we add the -o flag followed by an executable name:
g++ -Wall <filename>.cpp -o myprog
The same rules apply to the Clang compiler. Substitute g++ with clang++.
Note: All of the applications in this course will be built on Linux.
iostream stands for input-output stream and is a fundamental part of the C++ standard library. It provides functionalities for input and output operations through streams, which are abstractions that represent devices or data sources. The primary purpose of including the iostream header file in a C++ program is to enable the use of standard input and output objects, such as cin (for input) and cout (for output).
When you include #include <iostream>, it allows you to perform various I/O operations using these global stream objects:
cin: An instance of the istream class used for reading input from standard input (keyboard).
cout: An instance of the ostream class used for writing output to standard output (console).
cerr: Used for error messages; it is unbuffered, meaning error messages are displayed immediately.
clog: Also used for error messages but buffered, which means it stores messages before displaying them.
The inclusion of iostream is essential for any program that requires user interaction through input or output.
A namespace in C++ is a declarative region that provides a scope to the identifiers (like variables, functions, classes) inside it. The primary purpose of namespaces is to prevent name collisions in larger programs or when multiple libraries are used. For example, if two libraries define a function named print, using namespaces helps distinguish between them.
The standard library in C++ uses a namespace called std. When you include the iostream header, all the standard input and output objects (like cout, cin, etc.) are part of this namespace. Therefore, to use these objects without prefixing them with std::, you can include the statement:
using namespace std;
This allows you to write cout instead of std::cout. However, while this can make code cleaner and easier to read, it can also lead to ambiguity if there are multiple definitions of an identifier across different libraries. For this reason, in production code, it's often recommended to use fully qualified names like std::cout.
cin and cout are fundamental components of the C++ Standard Library used for input and output operations respectively.
Cin (Standard Input):
cin stands for “character input.” It is a predefined object of the class istream, which is part of the std namespace.
cin is connected to the standard input device, typically the keyboard.
It reads data from the user and stores it in variables.
The >> operator is used with cin to extract data. It skips any leading whitespace characters and reads until it encounters whitespace.
Cout (Standard Output):
cout stands for “character output.” It is a predefined object of the class ostream, also part of the std namespace.
cout is connected to the standard output device, typically the screen or console.
It displays data on the standard output. For example:
The << operator is used with cout to insert data. It outputs characters one by one until it reaches a newline character or the end of the stream.
Example:
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number; // Reads an integer from the standard input (keyboard)
cout << "You entered " << number;
return 0;
}
Together, cin and cout are essential for creating interactive programs where the user inputs data and the program processes it accordingly. They form the basis for input/output operations in C++ programming.
You must use the std:: prefix to refer to cin and cout. Here’s how you can do it:
#include <iostream>
int main() {
int number;
// Prompt the user to enter a number
std::cout << "Enter a number: ";
// Read an integer from the user using cin
std::cin >> number;
// Output the entered number
std::cout << "You entered: " << number << std::endl;
return 0;
}
Include <iostream>: This header contains the declarations for cin and cout.
Use std::cin and std::cout: Prefixing these with std:: makes it clear that they are part of the std namespace.
Avoid Direct Referencing: Using the using directive to bring cin and cout into the global namespace can lead to confusion and potential conflicts. It’s generally better to be explicit.
By following this approach, you ensure your code remains clear and maintainable while avoiding common pitfalls associated with namespaces in C++.
Without using the std:: prefix
You can refer to cin and cout without using the std:: prefix if you specify that you are using the entire std namespace. This is done by adding a using directive at the beginning of your code:
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number; // No need for std:: prefix
cout << "You entered: " << number << endl;
//endl inserts a new line and flushes the stream(output buffer)
return 0;
}
Clarity: Using std:: explicitly can make your code more clear and easier to understand, especially in large programs.
Namespace Pollution: If you use the entire std namespace with a using directive, it may lead to namespace pollution. This means that names from other libraries or even from your own custom classes might conflict with names in the std namespace.
For these reasons, many developers prefer to either:
Use std:: explicitly for clarity.
Include only what you need and use using directives sparingly to avoid conflicts.