FirstHack Learn
Log in Sign up free

Introduction to C++

9 min read · 41 views

Introduction to C++

C++ began in 1979 as a project by Bjarne Stroustrup called "C with Classes". The goal was practical rather than grand: keep everything that makes C fast and close to the machine, and add the tools needed to organise large programs without giving up that speed.

That history explains almost everything about the language you are about to learn. C++ is not a replacement for C and it is not a simplification of it. It is C plus several decades of additions, some of which you will use every day and most of which you can safely ignore for now.

What C++ actually adds

If you already know C, the honest summary is that C++ gives you four things C does not have.

  1. Classes and objects. You can bundle data together with the functions that operate on that data, and control who is allowed to touch what. A Student in C is a struct plus a scattered collection of functions that hopefully all agree on the rules. A Student in C++ can enforce its own rules.
  2. A standard library of ready-made containers. std::vector is a resizable array. std::string is a text type that manages its own memory. In C you write these yourself, with malloc, free, and a great deal of care.
  3. References. A second name for an existing variable, giving you the effect of pointers for the common case without the syntax or the risk of a null pointer.
  4. Function overloading and templates. Several functions can share one name and differ by parameter type, and a single piece of code can work for many types at once.

There are more features, including operator overloading, exceptions and lambdas, but you do not need them yet.

What stays the same is worth stating too: variables, if, for, while, functions, arrays, pointers, arithmetic and the compilation model are all inherited directly from C. A valid C program is very nearly a valid C++ program.

Input and output: iostream instead of stdio

The first visible difference is how you print. C uses printf from <stdio.h>, with a format string and placeholders. C++ uses std::cout from <iostream>, with the << operator.

The reason for the change is type safety. printf("%d\n", 3.7) compiles happily and prints nonsense, because printf trusts your format string. With std::cout << 3.7, the compiler already knows the type and picks the right behaviour. There is no format string to get wrong.

Your first program

C++
#include <iostream>

int main() {
    std::cout << "Hello from C++" << std::endl;
    return 0;
}

Line by line:

  • #include <iostream> pulls in the input/output stream declarations. Note there is no .h. C++ standard headers dropped the extension. The C headers are still available as <cstdio>, <cmath> and so on.
  • int main() is the entry point, exactly as in C. Execution starts here. In C++ the empty brackets already mean "no parameters", so you do not need to write void inside them.
  • std::cout is the standard output stream object. The std:: prefix says it lives in the namespace called std, which is where the entire standard library lives.
  • << is the stream insertion operator. Read it as an arrow pointing at where the data is going. You can chain it: each << returns the stream, so the next one has something to attach to.
  • std::endl writes a newline and flushes the output buffer.
  • return 0; reports success to the operating system.

What the std:: prefix is for

A namespace is a named container for identifiers. It exists so that two libraries can both define something called count without colliding. Everything in the standard library sits inside std, so you write std::cout, std::string, std::vector.

You will see using namespace std; in many textbooks, which lets you drop the prefix. It is convenient and it is also the reason many students later hit confusing errors, because it drags roughly two thousand names into your program at once. For small programs it is harmless. Write std:: while you are learning, so you can see where each name comes from.

💡Read the error, not the whole error

C++ compiler errors are famously long, especially once templates are involved. The useful information is almost always in the first error message, and usually in the first two lines of it. Everything after that is often the compiler cascading from the first mistake. Fix the top error and recompile.

A second program

C++
#include <iostream>
#include <string>

int main() {
    std::string name = "Ananya";
    int marks = 78;
    int total = 100;

    std::cout << "Student: " << name << "\n";
    std::cout << "Marks: " << marks << " out of " << total << "\n";
    std::cout << "Percentage: " << (marks * 100.0) / total << "%\n";

    return 0;
}

Notice there was no format specifier and so no risk of mismatching one. Notice also 100.0 rather than 100: dividing two integers throws away the fractional part, exactly as in C. Making one operand a double fixes it.

Compiling and running

Save the file with a .cpp extension and use g++, which is the C++ front end of the GNU compiler.

TEXT
g++ -std=c++17 -Wall hello.cpp -o hello
./hello

-std=c++17 selects the 2017 version of the language standard. Without it, older compilers default to an older standard and reject perfectly normal modern code. -Wall turns on warnings, and you should never turn it off. -o hello names the output; without it you get a.out.

On Windows, use MinGW or run the same commands inside WSL. The compiled file will be hello.exe.

Common mistakes

  • Writing cout without std:: and without a using-directive. The error reads 'cout' was not declared in this scope. Either write std::cout or add using namespace std; near the top.
  • Including <iostream.h>. That header has not existed since the language was standardised in 1998. Use <iostream> with no extension.
  • Compiling a .cpp file with gcc instead of g++. It often compiles and then fails at the linking stage with undefined references to standard library symbols, because gcc does not link the C++ standard library by default. Use g++.
  • Forgetting the semicolon after a statement. The compiler usually reports the error on the next line, because that is where it finally notices something is wrong. When an error makes no sense, check the line above it.
  • Expecting int / int to give a decimal. 7 / 2 is 3. Write 7 / 2.0 if you want 3.5.

You now have a working compiler, a program that runs, and a rough map of what C++ adds. Next comes variables and output in more detail. When you want to test yourself rather than read, head to the Practice page.

Create a free account to track what you have finished.