C++ Code Tutorial – Complete Guide

Are you eager to dive into the world of coding? Or maybe you’re a seasoned programmer looking to expand your skill set? Either way, you’re in the right place! We’re about to embark on an engaging, value-packed journey into the realm of C++ code. It’s a rather basic yet powerful programming language, and mastering it can open an array of opportunities in game creation, software development, and beyond. Let’s get decoding!

What is C++?

C++ is a highly efficient, general-purpose programming language that extends the C language. One of the most popular languages in the coding industry, C++ has a wide array of usages – from creating video games to complex computing systems.

What Can I Do with C++?

C++’s versatility is truly exceptional. While it’s extensively used in game development for its capability to process complex object-oriented programs efficiently, it also finds utility in creating operating systems, web browsers, and even banking applications. This broad spectrum of usage renders learning C++ a valuable asset for any coder.

Why Should I Learn C++?

As a coding enthusiast, the reasons to learn C++ are manifold. Here are just a few to consider:

  • Efficiency: Known for its high performance and efficiency, C++ allows developers to gain a better understanding of the machine and the software-hardware interplay.
  • Applicability: With its wide range of applications, from game creation to system software and beyond, C++ can significantly enhance your employability and project versatility.
  • Foundation: Understanding C++ provides a solid foundation for learning other programming languages.

With a clear idea of the “what”, “why”, and “how” regarding C++, let’s now jump right into some code. Ready for the fun part?

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Writing Your First C++ Program

Getting started with C++ is simple. Let’s create our first basic C++ program that outputs “Hello, Zenva!” to the console.

# include <iostream>
using namespace std;

int main() {
   cout << "Hello, Zenva!\n";
   return 0;
}

Let’s understand this program. We start by including the header iostream, which allows us to perform standard input and output operations.
The cout object, along with the extraction operator <<, is used to print our message. Function main() is where our program execution begins, and it returns an integer value at the end.

Variables and Data Types in C++

C++ includes several types of variables, such as integers, char, float etc. Here’s how you can declare and initialize variables in C++.

# include <iostream>
using namespace std;

int main() {
   int myInt = 10;
   float myFloat = 20.5; 
   char myChar = 'a';  

   cout << myInt << "\n";
   cout << myFloat << "\n";
   cout << myChar << "\n";

   return 0;
}

In the above example, myInt, myFloat, and myChar are initialized as an integer, float, and character respectively. They’re then printed out using the cout statement.

Using loops in C++

Looping is an essential concept in C++. Let’s explore a basic for loop that counts from 1 to 10.

#include <iostream>
using namespace std;

int main() {
   for (int i = 1; i <= 10; i++) {
      cout << i << "\n";
   }

   return 0;
}

In this loop, an initialization condition is set (int i = 1), an end condition is provided (i<=10), and an update statement increments the counter (i++).

Basic Input/Output Operations in C++

Besides output, C++ makes it easy to read user-provided input using the cin statement. Let’s create a program that accepts a number from a user and prints it.

# include <iostream>
using namespace std;

int main() {
   int num;
   cout <> num;

   cout << "You entered: " << num << "\n";

   return 0;
}

In the above code, “cin” alongside the extraction operator (>>) is used to receive the input from the user, which is subsequently printed out.

Functions in C++

Functions are essentially blocks of code that perform specific tasks. They’re useful for code reuse and modularity. Let’s define a function to add two numbers.

# include <iostream>
using namespace std;

int sum(int num1, int num2) {
   return num1 + num2;
}

int main() {
   int result = sum(2, 3);

   cout << "The sum is: " << result << "\n";

   return 0;
}

This program defines a function sum that takes two integers as input and returns their sum. The function is then called inside the main function.

Containers: Arrays and Vectors in C++

Arrays and vectors are two different types of containers in C++. An array is a fixed-size sequence created at compile-time, whereas a vector can be adjusted dynamically during runtime.

Let’s start with an example of an array that stores then prints 5 integers.

# include <iostream>
using namespace std;

int main() {
   int arr[5] = {1, 2, 3, 4, 5};
   
   for(int i = 0; i < 5; i++) {
      cout << "Element " << i << " is: " << arr[i] << "\n";
   }

   return 0;
}

Here, arr is declared as an array of size 5. Then we print each element of the array with a for loop.

Now let’s check vectors and their dynamic behavior. Note that for using vectors, you should include the vector library.

# include <iostream>
# include <vector>
using namespace std;

int main() {
   vector<int> vec = {1, 2, 3, 4, 5};
   
   cout << "Vector size: " << vec.size() << "\n";
   
   vec.push_back(6);
   
   cout << "New vector size: " << vec.size() << "\n";

   return 0;
}

Here, vec is a vector that initially holds 5 integers. We then add a 6th item using the push_back operation and print the new size of the vector.

Handling Exceptions in C++

Exception handling with try, catch, and throw is extremely critical to prevent the abrupt termination of programs. Let’s see an example where we catch a string exception.

# include <iostream>
using namespace std;

int main() {
   try {
      throw "An Exception occurred!";
   }
   catch (const char* exception) {
      cout << "Caught Exception: " << exception << "\n";
   }

   return 0;
}

In the above code, we throw a string exception which is intercepted by the catch block and the corresponding message is printed.

Working with Files in C++

C++ allows file operations through the fstream library. Here’s an example illustrating file writing in C++.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ofstream myfile;
    myfile.open("example.txt");
    myfile << "Writing to the file!";
    myfile.close();

    return 0;
}

In this case, we open “example.txt” in write mode using ofstream, write a string “Writing to the file!” into it, and finally close the file.

More Advanced Concepts in C++

Having gotten the basics under our belt, let’s tackle some of the more advanced concepts – from Object-Oriented Programming (OOP) to working with the preprocessor directives.

Object-Oriented Programming in C++

C++ is widely preferred for its Object-Oriented Programming traits. These help manage complex and extensive code bases. Let’s define a basic class, create an object, and interact with it.

# include <iostream>
using namespace std;

class Zenva {
   public:
      void ShowMessage() {
         cout << "Welcome to Zenva!\n";
      }
};

int main() {
   Zenva z;
   z.ShowMessage();

   return 0;
}

In this block, we define a class Zenva with a public method. In the main function, we create an object of this class and call the method.

Constructors and Destructors in C++

A constructor is a special method invoked when an object is created and a destructor is invoked when the object goes out of scope. Here is a simple demonstration:

# include <iostream>
using namespace std;

class Zenva {
   public:
      Zenva() {
         cout << "Zenva Constructor!\n";
      }

      ~Zenva() {
         cout << "Zenva Destructor!\n";
      }
};

int main() {
   Zenva z;

   return 0;
}

The ‘Zenva Constructor’ message is printed when the z object is created via the constructor, and ‘Zenva Destructor’ message is printed when it is removed from scope via the destructor.

Pointer and Reference Variables in C++

C++ gives low-level access through pointers and references, permitting direct memory manipulation. Here’s how you declare and use pointer variables:

# include <iostream>
using namespace std;

int main() {
   int num = 10;
   int* p = &num;
   
   cout << "Value of num: " << num << "\n";
   cout << "Address of num: " << &num << "\n";
   cout << "Value of p: " << p << "\n";
   cout << "Value p is pointing to: " << *p << "\n";

   return 0;
}

Here, p is a pointer variable storing the address of integer num. Using an asterisk (*) with p lets us retrieve the value stored at the address that p is pointing to.

Preprocessor Directives in C++

Preprocessor directives like #include, #define and #ifdef provide instructions to the compiler before the actual compilation of the code begins. Here’s an example:

# include <iostream>
# define PI 3.14
using namespace std;

int main() {
   cout << "The value of PI is: " << PI << "\n";

   return 0;
}

Here, we’re using the #define preprocessor directive to define a constant PI. We can then use this constant elsewhere in the program.

Working with Strings in C++

String manipulation is fundamental to many projects. Here’s a simple string concatenation example:

# include <iostream>
# include <string>
using namespace std;

int main() {
   string str1 = "Hello";
   string str2 = " Zenva!";
   string str3 = str1 + str2;

   cout << "Resultant string: " << str3 << "\n";

   return 0;
}

After defining two strings, we concatenate them using the plus (+) operator, then print out the resultant string.

Where to go next?

With the basic concepts of C++ laid out, you’re now ready to step into the real world of C++, sharpen your skills, and unlock a world of opportunities. Remember, as crucial as the basics are, the fun part, the real learning, starts now. The more you code, the better you’ll get. So keep those neurons firing, and your fingers coding!

Stay ahead of the game by elevating your learning with Zenva’s C++ Programming Academy. The Academy provides a series of comprehensive, easy-to-understand courses that cover a gamut of C++ programming aspects from basics to advanced concepts, including program flow, object-oriented programming, and even game mechanics. And that’s not all! You’ll also get hands-on project experience for your portfolio – essential for cementing your learning and impressing potential employers.

In addition to the C++ Programming Academy, you can also explore our broader collection of C++ courses. Remember, learning is a journey. Let’s take that first step together with Zenva!

Conclusion

Stepping into the world of programming with a language as versatile as C++ will bring you exciting challenges and unrivaled satisfaction. Your journey with C++ has just begun, and the road ahead is, no doubt, filled with opportunities to learn, grow, and succeed in the digital world.

At Zenva, we’re committed to making that journey smoother and more rewarding for you. Our C++ courses, coupled with a practical hands-on approach, provide a comprehensive roadmap to becoming proficient in C++. With Zenva by your side, you’re sure to stay ahead of the game in your programming journey and beyond.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.