C++ is a general-purpose programming language created by Bjarne Stroustrup as an extension of the C programming language, or “C with Classes”.
What is C++?
C++ is a cross-platform language that can be used to create high-performance applications.
C++ was developed by Bjarne Stroustrup, as an extension to the C language.
C++ gives programmers a high level of control over system resources and memory.
The language was updated 3 major times in 2011, 2014, and 2017 to C++11, C++14, and C++17.
Why Use C++
C++ is one of the world’s most popular programming languages.
C++ can be found in today’s operating systems, Graphical User Interfaces, and embedded systems.
C++ is an object-oriented programming language which gives a clear structure to programs and allows code to be reused, lowering development costs.
C++ is portable and can be used to develop applications that can be adapted to multiple platforms.
C++ is fun and easy to learn!
As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or vice versa
C++ Syntax
Let’s break up the following code to understand it better:
Example
#include <iostream>
using namespace std;
int main() {
cout << “Hello World!”;
return 0;
Example explained
Line 1: #include <iostream>
is a header file library that lets us work with input and output objects, such as cout
(used in line 5). Header files add functionality to C++ programs.
Line 2: using namespace std
means that we can use names for objects and variables from the standard library.
Don’t worry if you don’t understand how #include <iostream>
and using namespace std
works. Just think of it as something that (almost) always appears in your program.
Line 3: A blank line. C++ ignores white space.
Line 4: Another thing that always appear in a C++ program, is int main()
. This is called a function. Any code inside its curly brackets {}
will be executed.
Line 5: cout
(pronounced “see-out”) is an object used together with the insertion operator (<<
) to output/print text. In our example it will output “Hello World”.
Note: Every C++ statement ends with a semicolon ;
.
Note: The body of int main()
could also been written as:int main () { cout << "Hello World! "; return 0; }
Remember: The compiler ignores white spaces. However, multiple lines makes the code more readable.
Line 6: return 0
ends the main function.
Line 7: Do not forget to add the closing curly bracket }
to actually end the main function
C++ Compiler Explained: What is the Compiler and How Do You Use it?
Intro to C++ Compilers
In order to get started with C++, you will need to learn a little about compilers and how C++ runs on your computer.
When all is said and done, computers only understand one language, machine language. Machine language is entirely made up of binary bits, or 0s and 1s.
While it would be possible to program in binary, it would be incredibly tedious and time consuming. So, we humans developed programming languages to make it easier to develop software.
Assembly language is a direct 1 to 1 with machine language. Languages like C, C++, and COBOL are a little higher and need to be compiled down. It goes even higher. Languages like JavaScript and Python have components that get translated into C++ or other low level languages before they get compiled, effectively making them “higher” languages than C or C++.
Because computer architecture is made up of electronic switches and cables that can only work with binary 1s and 0s, you need a compiler to translate your code from high level C++ to machine language that the CPU can understand.
How compilers work
Compilers are utility programs that take your code and transform it into executable machine code files.
When you run a compiler on your code, first, the preprocessor reads the source code (the C++ file you just wrote). The preprocessor searches for any preprocessor directives (lines of code starting with a #). Preprocessor directives cause the preprocessor to change your code in some way (by usually adding some library or another C++ file).
Next, the compiler works through the preprocessed code line by line translating each line into the appropriate machine language instruction. This will also uncover any syntax errors that are present in your source code and will throw an error to the command line.
Finally, if no errors are present, the compiler creates an object file with the machine language binary necessary to run on your machine. While the object file that the compiler just created is likely enough to do something on your computer, it still isn’t a working executable of your C++ program. There is a final important step to reach an executable program.
C++ contains a vast library to aid in performing difficult tasks like I/O and hardware manipulation. You can include these libraries with preprocessor directives, but the preprocessor doesn’t automatically add them to your code.
In order for you to have a final executable program, another utility known as the linker must combine your object files with the library functions necessary to run the code.
Think of it as having all the necessary blocks to build a house. The compiler made all the blocks but the linker is the one that sticks them all together to finally create a house. Once this is done, you now have a functioning executable file!
How to Compile a file
Let’s say you have a C++ file called helloWorld.cpp
…
If you are on Windows
Using and IDE like CodeBlocks
It is as simple as clicking the build and run buttons, they will create a file in the project folder.
Using Command Prompt
- Open a Developer Command Prompt – For this step, you will need to have Microsoft Visual Studio or some other IDE that enables you to compile your program from the command line. You can also search online for C++ compilers.
- Navigate to the source code directly
- Run the Compiler on your source code (assuming you are using the Microsoft Visual Studio compiler)
cl /EHsc helloWorld.cpp
This will now create an object file and automatically link it for you. If you look in that same folder, you will see a hellWorld.exe executable file (note the exe extension) is now present.
- Type
helloWorld
into the prompt to run the executable
Alternatively, many IDEs allow for quick building and viewing of your program. This may be easier since your version of windows may not come pre packaged with a compiler utility.
If you are on Linux or OSX
- Open up a terminal window and navigate to the source code directory
- Run the Compiler on your source code
g++ helloWorld.cpp -o helloWorld
This will create an object file and automatically link it for you. Look in the folder and you will see a helloWorld.exe executable file (note the exe extension).
- Type
./helloWorld
in the terminal window to run the executable file
g++ is the standard Linux compiler and is a great utility. It comes packaged with the operating system.
NOTE: to compile and execute your code directly, run g++ -o helloWorld helloWorld.cpp; ./helloWorld
so when you need to compile and run your code multiple times, up arrow-enter.
There are a number of different types of compilers. The two listed are the two that are usually packaged with Windows or Linux/OSX.
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords), for example:
int
– stores integers (whole numbers), without decimals, such as 123 or -123double
– stores floating point numbers, with decimals, such as 19.99 or -19.99char
– stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotesstring
– stores text, such as “Hello World”. String values are surrounded by double quotesbool
– stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:
Syntax
typevariable = value;
Where type is one of C++ types (such as int
), and variable is the name of the variable (such as x or myName). The equal sign is used to assign values to the variable.
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int
and assign it the value 15:int myNum = 15;
cout << myNum;
You can also declare a variable without assigning the value, and assign the value later:
Example
int myNum;
myNum = 15;
cout << myNum;
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10
Other Types
A demonstration of other data types:
Example
int myNum = 5; // Integer (whole number without decimals)
double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = ‘D’; // Character
string myText = “Hello”; // String (text)
bool myBoolean = true; // Boolean (true or false)
C++ Strings
Strings are used for storing text.
A string
variable contains a collection of characters surrounded by double quotes:
Example
Create a variable of type string
and assign it a value:string greeting = “Hello”;
To use strings, you must include an additional header file in the source code, the <string>
library:
Example
// Include the string library
#include <string>
// Create a string variable
string greeting = “Hello”;
C++ Operators
Operators are used to perform operations on variables and values.
In the example below, we use the +
operator to add together two values:
Example
int x = 100 + 50;
Although the +
operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:
Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
C++ divides the operators into the following groups:
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator | Name | Description | Example | |
---|---|---|---|---|
+ | Addition | Adds together two values | x + y | |
– | Subtraction | Subtracts one value from another | x – y | |
* | Multiplication | Multiplies two values | x * y | |
/ | Division | Divides one value by another | x / y | |
% | Modulus | Returns the division remainder | x % y | |
++ | Increment | Increases the value of a variable by 1 | ++x | |
— | Decrement | Decreases the value of a variable by 1 | –x |
ADVANTAGES OF C++
Advantages and Disadvantages of C++
C++ is undoubtedly one of the oldest and most efficient programming languages that still continues to dominate the realm of programming. Every beginner is curious to know the Advantages and Disadvantages of C++ on the basis of which they can start their programming journey. Benefits and limitations are important to know to predict their next step.
So, what are you waiting for? Let’s dive together!
Advantages and Disadvantages of C++
Every coin has two faces, now its time to uncover the faces of C++, through its advantages and disadvantages-
Advantages of C++
1. Portability
C++ offers the feature of portability or platform independence which allows the user to run the same program on different operating systems or interfaces at ease.
Suppose you write a program in LINUX OS and for some apparent reason you switch to Windows OS, you would be able to run the same program in windows as well without any error. This feature proves to be of great convenience to the programmer.
2. Object-oriented
One of the biggest advantages of C++ is the feature of object-oriented programming which includes concepts like classes, inheritance, polymorphism, data abstraction, and encapsulation that allow code reusability and makes a program even more reliable.
Not only this, it helps us deal with real-world problems by treating data as an object. C lacked this feature and hence it was created, proving to be of great significance.
This feature gave birth to numerous job prospects and technologies. It is fascinating to note that C++ was created by combining features not only from C but Simula 67, the first object-oriented programming language.
3. Multi-paradigm
C++ is a multi-paradigm programming language. The term “Paradigm” refers to the style of programming. It includes logic, structure, and procedure of the program. Generic, imperative, and object-oriented are three paradigms of C++.
Let us now try to understand what generic programming means. Generic programming refers to the use of a single idea to serve several purposes. Imperative programming, on the other hand, refers to the use of statements that change a program’s state.
4. Low-level Manipulation
Since C++ is closely associated with C, which is a procedural language closely related to the machine language, C++ allows low-level manipulation of data at a certain level. Embedded systems and compiler are created with the help of C++.
5. Memory Management
C++ gives the programmer the provision of total control over memory management. This can be considered both as an asset and a liability as this increases the responsibility of the user to manage memory rather than it being managed by the Garbage collector. This concept is implemented with the help of DMA (Dynamic memory allocation) using pointers.
6. Large Community Support
C++ has a large community that supports it by providing online courses and lectures, both paid and unpaid. Statistically speaking, C++ is the 6th most used and followed tag on StackOverflow and GitHub.Machine Learning Project Cartoonifier
7. Compatibility with C
C++ is pretty much compatible with C. Virtually, every error-free C program is a valid C++ program. Depending on the compiler used, every program of C++ can run on a file with .cpp extension.
8. Scalability
Scalability refers to the ability of a program to scale. It means that the C++ program is capable of running on a small scale as well as a large scale of data. We can also build applications that are resource intensive.
Disadvantages of C++
1. Use of Pointers
Pointers in C/C++ are a relatively difficult concept to grasp and it consumes a lot of memory. Misuse of pointers like wild pointers may cause the system to crash or behave anomalously.
2. Security Issue
Although object-oriented programming offers a lot of security to the data being handled as compared to other programming languages that are not object-oriented, like C, certain security issues still exist due to the availability of friend functions, global variables and, pointers.
3. Absence of Garbage Collector
As discussed earlier, C++ gives the user complete control of managing the computer memory using DMA. C++ lacks the feature of a garbage collector to automatically filter out unnecessary data.
4. Absence of Built-in Thread
C++ does not support any built-in threads. Threads is a relatively new concept in C++ which wasn’t initially there. Now, C++ is capable of supporting lambda functions.
Summary
In this article, we discussed the various pros and cons of C++. It is safe to say that after developing an understanding of the advantages and disadvantages of C++, you are now ready to make the right choice to learn C++.
Drop your comment