#FutureSTEMLeaders - Wiingy's $2400 scholarship for School and College Students

Apply Now

C++

Learn C++ Programming Basics : Introduction to C++

Written by Rahul Lath

Updated on: 24 Jan 2024

tutor Pic

What is C++ Programming?

C++ is a high-level programming language that is frequently used in the creation of software. It is a development of the C programming language and comes with new features that increase its flexibility and capability.

It gives developers a language that is efficient, flexible and reliable. It is frequently used to build intricate systems, including those that need high performance and reliable functioning, including operating systems, video games, and software applications.

Lets look at its history a little, early in the 1980s, Bjarne Stroustrup developed C++ as a development of the C programming language. The requirement for a more potent language that could handle object-oriented programming, which was then gaining popularity, had an impact on its creation. C++ has undergone several updates since it was first developed, and it is now extensively utilized in a number of sectors, including gaming, aerospace, and finance.

Now lets see how do we get started with programming with C++
The first step is to set up the programming/development  environment. The three essential stages for setting up a C++ development environment will be covered in this section.

Setting up the Development Environment

The first step is to choose an Integrated Development Environment (IDE). A software program known as an IDE offers a complete environment for creating, debugging, and compiling code. For C++ programming, there are a number of well-known IDEs available, such as Visual Studio, Code::Blocks, and Eclipse. It’s crucial to select the IDE that best meets your demands because each one has its own unique collection of features and capabilities.

The second step is to install a C++ compiler. A compiler is a program that translates the code you write into machine-readable instructions that can be executed by a computer. GCC, Clang, and Microsoft Visual C++ are some of the most widely used C++ compilers. Once you have installed a compiler, you can use it to compile your code and generate executable files.

The final step is to configure the IDE for C++ development. This involves setting up the IDE to recognize and work with C++ code files, as well as configuring the compiler settings and build options. The specific steps involved in configuring an IDE will depend on the IDE you have chosen and the operating system you are running.

Basic Structure of a C++ Program

There are a few essential components that you must keep in mind when creating C++ programmes. These consist of the main(), preprocessor directives, comments, and documentation and function. To better comprehend each of these components’ function in a C++ programme, let’s take a deeper look at each one.

The first is the main() function. This is your program’s entrance point, and that’s where it starts running. All C++ programmes must have the main() function, which must always return an integer value. Typically, the result returned by main() shows whether the programme was successful or unsuccessful.

The comments and documentation come next. These are crucial for improving the readability and comprehension of your code. Comments are lines of text intended to clarify what your code is doing but which are disregarded by the compiler. On the other side, documentation is a more official method of disseminating knowledge about your code. It generally includes a more thorough explanation of how your program operates and is written in a separate file.

Preprocessor instructions come last. Before your code is built, the preprocessor processes these instructions. The inclusion of header files, the definition of constants, and other chores that must be completed before your code can be generated are accomplished using preprocessor directives.

Variables and Data Types

Now let’s take a closer look at the data types and variables in C++:

A. Declaration and Initialisation of Variables:

In C++ we must declare the variables before using them. The declaration specified the name and data type of the variable. We can also simultaneously initialise them while declaring the variables.

int x; // declare an integer variable x = 5; // initialize the variable with the value 5 int y = 10; // declare and initialize an integer variable with the value 10

B. Fundamental Data Types:
C++ has several fundamental data types, including int, float, double, char, and bool. Here’s a brief description of each:

  • int: used to store integer values
  • float: used to store floating-point values with single precision
  • double: used to store floating-point values with double precision
  • char: used to store a single character
  • bool: used to store true/false values

Here is an example of declaring and initialising the various types of variables:

int age = 30; float height = 1.75; double weight = 75.5; char gender = 'M'; bool isStudent = true;

C. User-defined Data Types:

In addition to the fundamental data types, C++ also allows you to define your own data types using struct and enum. A struct is a collection of data elements, while an enum is a set of named integer constants. Here’s an example of defining a struct and an enum:

// define a struct to represent a person struct Person { string name; int age; }; // define an enum to represent the days of the week enum Day { Monday,Tuesday, Wednesday,Thursday, Friday, Saturday, Sunday};

D. Type Modifiers:

Type modifiers in C++ also let you change how a data type behaves. A variable’s initial value cannot be altered once it has been initialised, according to the const modifier. With integer types, the signed and unsigned modifiers are used to determine whether or not the values can be negative. Here’s an illustration of how to use type modifiers:

const int MAX_VALUE = 100; // declare a constant variable unsigned int count = 0; // declare an unsigned integer variable signed int temperature = -10; // declare a signed integer variable

Input and Output Operations

Now let us take a look at how the input and output operations look in C++:
A. Standard Input and Output Streams:

C++ provides standard input and output streams, which are represented by the built in “cin” and “cout”.
–The cin object is used for reading input from the user.

–The cout object is used for writing output to the console.
Here’s an example of using cin and cout to read input and write output:

int age; cout << "Enter your age: "; cin >> age; cout << "Your age is: " << age << endl;

B. Formatting Output:

C++ provides several ways to format output using the cout object.
–setw() function to specify the width of the output.
–setprecision() function to specify the number of decimal places to display for floating-point numbers.
–setfill() function to specify the fill character for the output.
Here’s an example of using formatting functions:

double pi = 3.14159265358979323846; cout << "Pi is approximately: " << setprecision(4) << pi << endl;

C. String Manipulation:

C++ provides several functions for manipulating strings, which are represented by the string class.
– “+” operator to concatenate strings

– size() function to get the length of a string
– substr() function to get a substring of a string
Here’s an example of using string manipulation functions:

string firstName = "John"; string lastName = "Doe"; string fullName = firstName + " " + lastName; cout << "Full name: " << fullName << endl; cout << "Length of full name: " << fullName.size() << endl; cout << "First name: " << fullName.substr(0, 4) << endl; // Output Full name: John Doe Length of full name: 8 First name: John

Control Flow Structures

Let’s take a closer look at control flow structures and functions in C++.

A. Conditional Statements:

In C++, you can use conditional statements like if, if-else, and switch to execute different blocks of code based on different conditions.
–”if” statement executes a block of code if a specified condition is true
– “if-else” statement executes one block of code if the condition is true and another block of code if the condition is false
– “switch” statement is used to execute different blocks of code based on the value of a variable. Here’s an example of using conditional statements:

int num = 10; if (num > 0) { cout << "The number is positive" << endl; } else if (num < 0) { cout << "The number is negative" << endl; } else { cout << "The number is zero" << endl; } int day = 1; switch (day) { case 1:cout << "Monday" << endl; break; case 2:cout << "Tuesday" << endl; break; // ... default:cout << "Invalid day" << endl; }

B. Looping Statements:

C++ provides several looping statements like for, while, and do-while to execute a block of code repeatedly.
– “for” loop executes a block of code a fixed number of times
– “while” the while loop executes a block of code as long as a specified condition is true
– “do-while” loop is similar to the while loop, but it always executes the block of code at least once
Here’s an example of using looping statements:

for (int i = 0; i < 10; i++) { cout << i << endl; } int j = 0; while (j < 10) { cout << j << endl; j++; } int k = 0; do { cout << k << endl; k++; } while (k < 10);

C. Nested Loops and Conditional Statements:

You can also nest conditional statements and loops to create more complex control flow structures. Here’s an example of using nested loops and conditional statements:

for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { for (int j = 1; j <= i; j++) { cout << "*"; } cout << endl; } }

Functions

A. Defining and calling functions:
Functions are used to perform a specific task. A function is a block of code that can be called from other parts of your program. To define a function, you need to specify the 

-return type

-name

-parameter list

To call a function, you simply need to use its name and pass any required arguments. Here’s an example of defining and calling a function:

int add(int x, int y) { return x + y; } int sum = add(5, 7); cout << "The sum is: " << sum << endl;

B. Parameters and Return Values:

Functions can take zero or more parameters,they are values that are passed to it . Functions can also return a value, which is the result of the function’s computation. To specify a return value, you need to use the return statement. Here’s an example of using parameters and return values:

double divide(double x, double y) { return x / y; } double result = divide(10.0, 2.0);

C. Function Overloading:

In C++, you can define multiple functions with the same name but different parameter lists. This is called function overloading, and it allows you to use the same function name for different tasks,where the return type is different. Here’s an example of function overloading:

int add(int x, int y) { return x + y; } double add(double x, double y) { return x + y; } int sum = add(5, 7); double total = add(3.14, 2.71); cout << "The sum is: " << sum << endl; cout << "The total is: " << total << endl;

Arrays and Pointers

A. Declaring and Accessing Arrays:

Arrays in programming are a collection of variables of the same data type, which are grouped together under a common name. The variables in an array can be accessed using their index number, which starts at 0 for the first element in the array.

We can declare an array in C++, we need to specify the data type of data elements followed by array name and size in the of th array in square brackets.

int myArray[5]; int myArray[5] = {1, 2, 3, 4, 5}; //array of size 5

To access  elements we need to use the index

int x = myArray[0]; // access the first element in the array

B. Multidimensional Arrays:

Multidimensional arrays are arrays that have more than one dimension. The most common type is the two-dimensional array, which is also called a table or matrix. To declare a two-dimensional array in C++, you can use the following syntax:

int myArray[3][4]; int myArray[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

To access the elements we use:

int x = myArray[0][1]; // access the element in the first row and second column

C. Introduction to Pointers:

A pointer is a variable that holds the memory address of another variable. Pointers are often used in C++ for dynamic memory allocation and for passing parameters by reference.

int* myPointer; int x = 10; myPointer = &amp;x; //This declares a pointer variable that can hold the memory address of an integer variable.

D. Pointers and Arrays:

In C++, arrays and pointers are closely related. In fact, the name of an array is a pointer to the first element in the array.

To declare a pointer to an array, you can use the following syntax:

int myArray[5]; int* myPointer = myArray;

This creates a pointer variable myPointer that points to the first element in the array myArray. You can access individual elements in the array using pointer arithmetic:

int x = *(myPointer + 2); // access the third element in the array

Object-Oriented Programming (OOP) Concepts

Object-oriented programming (OOP) is a programming paradigm that uses objects to represent and manipulate data. OOP uses concepts of classes and objects that help in encapsulating data and behavior into reusable components.

A. Classes and Objects

A class is a template for creating objects. It defines the properties and behavior of the objects. An object is an instance of a class and it has  its own set of properties and can perform certain actions. To create a class in C++, you can use the class keyword, followed by the class name and the class definition:

class MyClass { private: int myPrivateVariable; public: int myPublicVariable; void myPublicMethod(); };

This makes a class named MyClass with private data members.

To make the object of the class and then access the properties and methods of the class we use dot notation, like we can see below

MyClass myObject; myObject.myPublicVariable = 10; // access the variable myObject.myPublicMethod(); // access the method

B. Encapsulation and Data Hiding:

Encapsulation is a key concept in OOPS which hides the implementation details of a class from the outside world, and provides a well-defined interface for interacting with the class. It can be achieved by using access modifiers that help in controlling the visibility of the class members.

The access modifiers in C++ include private, public and protected. Lets see an example and declare 

class MyClass { private: int myPrivateVariable; public: int myPublicVariable; void myPublicMethod(); };

C. Inheritance and Polymorphism

Inheritance is another concept of creating a new class from an existing class, where the new class inherits the properties and behavior of the existing class. The existing class is called the base class or parent class, while the new class is called the derived class or child class.

Polymorphism is the concept of using a single interface to represent multiple types.Like using the same function with various different declarations but same name. In C++, polymorphism is achieved through virtual functions and function overriding.

class Shape { public: virtual void draw() = 0; }; class Rectangle : public Shape { public: void draw() { // draw a rectangle } }; class Circle : public Shape { public: void draw() { // draw a circle } };

Over here we can see that circle and rectangle are child classes of the parents Shape and have overriding draw() methods of their parent.

D. Constructors and Destructors

Constructors and destructors are special member functions in a class that are called automatically when an object is created or destroyed, respectively.

Lets see its implementation to better understand the same

class MyClass { public: MyClass(); // constructor ~MyClass(); // destructor }; MyClass::MyClass() { // constructor code } MyClass::~MyClass() { // destructor code }\

Constructors and Destructors have the same name as the class and no return types. Destructors start with the symbol “~” as we can see. 

Exception Handling

Exception handling in  C++ helps us  handle errors or exceptional situations that may occur during program execution.

A. Handling Exceptions with “try-catch” Blocks:

The try block contains the code that may throw an exception, while the catch block contains the code that handles the exception.

Lets see an example to better understand this.

try { // code that may throw an exception } catch (exceptionType exceptionObject) { // code that handles the exception }

B. Throwing Custom Exceptions

You can define your own exception classes in C++ to handle specific types of exceptions. We can customize the error message and for which exception should the message be printed. 

Lets understand this through an example:

class MyException : public exception { public: const char* what() const throw() { return "My custom exception"; } }; try { throw MyException(); } catch (MyException&amp; e) { cout << e.what() << endl; }

File Handling

C++  allows multiple I/O operations on files.

Lets look at how it allows reading and writing to and from files:

To Read from the file in C++, we first need to create an input file stream object and open the desired file using its filename. We can then use various input stream functions like getline(), get(), and read() to read data from the file.

#include <iostream> #include <fstream> int main() { std::ifstream inputFile("input.txt"); if (inputFile.is_open()) { std::string line; while (std::getline(inputFile, line)) { std::cout << line << std::endl; } inputFile.close(); } else { std::cerr << "Failed to open file!" << std::endl; } return 0; }

We use the header #include<fstream> for writing and reading to and from files. The above code reads contents from a “input.txt” file 

To write from the file in C++ we create an output file stream object and use its various output stream functions like put(), write(), and operator<< to write data to the file. 

#include <fstream> int main() { std::ofstream outputFile("output.txt"); outputFile << "Hello, world!" << std::endl; outputFile.close(); return 0; }

The above code writes to an “output.txt” file.

C++ also provides several file I/O operations like copying files, deleting files, and renaming files. These operations can be performed using functions like std::remove(), std::rename(), and std::copy().

Additional Features and Libraries in C++

The Standard Template Library (STL) is a library that gives a collection of powerful data structures and algorithms like vectors, maps, and sorting functions. 

#include <algorithm>
#include <iostream>
#include <vector>


int main() {
    std::vector<int> numbers = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3 };


    std::sort(numbers.begin(), numbers.end());


    for (int number : numbers) {
        std::cout << number << " ";
    }
    std::cout << std::endl;


    return 0;
}
#include <iostream> template<typename T> T add(T a, T b) { return a + b; } int main() { int result1 = add<int>(1, 2); double result2 = add<double>(3.14, 2.71); std::cout << "Result 1: " << result1 << std::endl; std::cout << "Result 2: " << result2 << std::endl; return 0; }

Namespaces provide a way to group related code together and avoid naming conflicts. C++ also supports advanced topics like lambda expressions and multithreading, which allow developers to write better code improving efficiency.

Let us see this through a code snippet:

#include <iostream> namespace myNamespace { int myValue = 42; } int main() { std::cout << "Value from namespace: " << myNamespace::myValue << std::endl; return 0; }

Best practices and Tips for C++ Programming

Now let us discuss some best practices and tips for C++ Programming:

  1. Coding Standards and Style Guidelines
    In C++, it’s important to follow some coding standards and style guidelines to ensure that the code is readable, maintainable, and consistent. 
  2. Debugging Techniques
    For debugging C++ code, there are several techniques that can be used, including using a debugger like GDB or Visual Studio Debugger, adding print statements to your code, using static analysis tools like Clang (discussed earlier)
  3. Memory Management Considerations
    Memory management is a aspect of C++ programming, as it’s a language that allows direct access to memory. It’s important to properly manage memory to avoid issues like memory leaks and dangling pointers, therefore deallocating pointers and dynamic variables is very important.

Conclusion and Next Steps

In this article, we covered the basics of C++ programming, including variables, data types, control structures, functions, and object-oriented programming. We also discussed advanced topics like file handling, STL, templates, and namespaces, as well as best practices and tips for C++ programming.

If you’re interested in learning more about C++, there are several resources available online, including books, tutorials, and online courses. 

Finally, it’s important to practice and build projects to improve your C++ skills. Building small projects like console applications or games can be a great way to apply what you’ve learned and gain practical experience.

Written by

Rahul Lath

Reviewed by

Arpit Rankwar

Share article on

tutor Pic
tutor Pic