In previous blog posts, we’ve programmed mainly in C. But with a blog post about classes coming up, I figured a short post about how C++ works would be helpful for everybody.
We’re going to start out with the classic first program; “hello world”.
Here’s “hello world” in C code:
Comparatively, here’s “hello world” in C++:
The very first line, we can see a difference — that stdio.h has been replaced by iostream.
We can break into input/output stream. Input and output are pretty self-explanatory. Stream is new, but not extremely complicated. A stream is just a series of characters. For this blog post, all we’re using are the istream and ostreams, but there are other types of streams.
The implication of stream means we aren’t going to use printf anymore. We use cout to print items to the terminal, with “>>” between data. Also in the cout line you see that cout and endl both have “std::” in front of them. If we put the line “using namespace std” below our header definition, we don’t have to put “std::” in front of cout and endl (and similar items). This is considered bad practice, because if we include multiple namespace, calling functions can become ambiguous, and cause problems.
C++ is an object-oriented programming (OOP) and generic programming language. The implication of object-oriented programming means that C++ has classes, objects, encapsulation, operator overloading, inheritance, and polymorphism. Generic programming focuses on function and class templates. In this blog post, we are going to learn about function and operator overloading, and the difference between C and C++, so classes and other features of C++ will be in a later post.
C++ allows functions to be defined by the same name, as long as they all have different parameters. This is called function overloading.
If you run this code, you will see that the “print” calls have different inputs, which then changes what function will be called. We called “using namespace std”, so we must be careful to not create any functions that are already in the std library. Another small difference between C and C++ is the “cin” function.
Below is an addition to our previous code (the link has all the code):
If you check out cin, you see it uses “>>”, while cout uses “<<“. I recommend typing in some invalid inputs when prompted for an integer (like ‘123apple’) just to see what happens!
This is just one of the features that C++ has. There are many other differences from C, but if you know how to program in C, C++ is only a small jump away.
4 Comments on “A Brief Intro to C++”
Great information. Since last week, I am gathering details about the c++ experience. There are some amazing details on your blog which I didn’t know. Thanks.
thanks for this great intro to c++ article
An interesting website!
I think that I can learn a lot of good knowledge and improve my ability in the future.
Thank you so much
Thank you so much