DEV Community

Cover image for Learning C++: A Beginner's Guide
Amit Pandey
Amit Pandey

Posted on

Learning C++: A Beginner's Guide

C++ is a robust and adaptable programming language for system software, game development, and more. A Danish researcher, Bjarne Stroustrup created C++ as an extension to C while working on his PhD. This guide simplifies learning, helping beginners take their first steps with C++.

Why Learn C++?

Foundation of Programming: Learning C++ provides a solid foundation for understanding other programming languages, such as Java and Python.

  • Performance: C++ is known for its speed and efficiency, making it suitable for high-performance applications.
  • Widespread Use: C++ is commonly used in various industries, including gaming, embedded systems, and software development.

Step-by-Step Guide to Learning C++:

1. Configuring Your Development Environment

  • Install a Compiler: Opt for GCC (MinGW for Windows) or Clang.
  • Select an IDE: Good choices are Visual Studio, Code::Blocks, or VS Code with C++ extensions.
  • Create and Execute Code: Begin with basic programs, such as "Hello, StackUp!"

2. Understanding the Basics

Let's look at the fundamental structure of C++ programming.

#include <iostream>
using namespace std;

int main() {
    // statements within the body are executed to result as output.
    cout << "Hello, StackUp!" << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Here, #include <iostream> is a header file that includes the Input/Output Stream library. It allows the program to use standard input (cin) and output (cout) functions.

Below the header file(s), Using namespace std; is used. It simplifies the code by allowing direct usage of the standard namespace (std). Without this line, you would need to prefix standard library components with std:: (e.g., std::cout).

For example, the above code will look like

#include <iostream>

int main() {
    std::cout << "Hello, StackUp!" << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Then, a main function with a return type of int is written, so we need to return some value at the end before closing the main function. Since we do not want anything to be returned from the main function, the return 0; statement has been given.

Inside the main function, we generally write our program logic. As we can see in our example, cout << "Hello, StackUp!" << endl; has been written. Here, cout<< is responsible for displaying/ generating output to the system. Hence, the output section will display Hello, StackUp!.

<<endl basically refers to the endline. It is used to go to the next line in the output.

3. What are variables and data types?

Variables are used to store data. The data can be changed inside the variables once initialized. A variable must be declared or initialized with a data type as a prefix. For example, int x = 5; is a variable initialization as the variable x gets the value 5 as data. The data type used here is int which refers to an integer.

Similarly, there are numerous data types available in the C++ programming language:

Primitive Data Types:

  • int: Represents integer values (e.g., int x = 10;)
  • float: Used for floating-point numbers (e.g., float pi = 3.14;)
  • double: Refers to double-precision floating-point values (e.g., double d = 3.14159;)
  • char: Represents individual characters (e.g., char c = 'A';)
  • bool: Represents boolean values, which can be either true or false
  • void: Indicates the absence of a value, typically utilized in functions that do not return a value.

Derived Data Types:

  • Arrays: A collection of elements that are of the same type (e.g., int arr[5];)
  • Pointers: Variables that store memory addresses (e.g., int* ptr;)
  • References: An alternative name for another variable (e.g., int& ref = x;)

User-Defined Data Types:

  • struct: A construct for grouping related variables (e.g., struct Point { int x, y; };)
  • class: Defines objects that contain attributes and methods, part of the OOP paradigm.
  • enum: A way to define named constants through enumerations (e.g., enum Color { RED, GREEN, BLUE };)

Do not stress over the above information, you will learn it eventually by the time you follow the tutorial and practice on your own!

4. Operators in C++:

  • Arithmetic Operators: These operators perform basic arithmetic operations.
int a = 100, b = 50;
cout << a + b; // Addition (150)
cout << a - b; // Subtraction (50)
cout << a * b; // Multiplication (5000)
cout << a / b; // Division (2)
cout << a % b; // Modulus (0) it finds the remainder
Enter fullscreen mode Exit fullscreen mode
  • Relational Operators: These operators compare two values and return a boolean result.
cout << (a > b);  // Greater than
cout << (a < b);  // Less than
cout << (a == b); // Equal to
cout << (a != b); // Not equal to
cout << (a >= b); // Greater than or equal to
cout << (a <= b); // Less than or equal to
Enter fullscreen mode Exit fullscreen mode
  • Logical Operators: These are used for performing logical operations.
cout << (a > 50 && b < 100); // Logical AND
cout << (a > 50 || b < 100); // Logical OR
cout << !(a > b);          // Logical NOT
Enter fullscreen mode Exit fullscreen mode
  • Bitwise Operators: These operators perform bit-level operations.
cout << (a & b);  // Bitwise AND
cout << (a | b);  // Bitwise OR
cout << (a ^ b);  // Bitwise XOR
cout << (~a);     // Bitwise NOT
cout << (a << 1); // Left shift (multiples by 2)
cout << (a >> 1); // Right shift (divided by 2)
Enter fullscreen mode Exit fullscreen mode
  • Assignment Operators: These operators are used to assign values to variables.
a += b; // Equivalent to a = a + b
a -= b; // Equivalent to a = a - b
a *= b; // Equivalent to a = a * b
a /= b; // Equivalent to a = a / b
a %= b; // Equivalent to a = a % b
Enter fullscreen mode Exit fullscreen mode
  • Increment/Decrement Operators: These operators increase or decrease a value by 1.
int a=10;
cout << a++;   // Post-increment (10)
cout << ++a;   // Pre-increment (12)
cout << a--;   // Post-decrement (12)
cout << --a;   // Pre-decrement (10)
Enter fullscreen mode Exit fullscreen mode
  • Other Operators:

    • Ternary Operator: A shorthand for if-else statements.
    int max = (a > b) ? a : b;  
    // if (a>b) is true, max = a or else max = b
    
    • Type Cast Operator: Converts data types.
    float f = (float)a / b;
    
    • sizeof Operator: Returns the size of a data type.
    cout << sizeof(a);
    

5. Let's explore conditional statements:

Conditional statements enable a program to make choices based on specific conditions. The most frequently used conditional statements include if, else if, and else.

- If Statement:

int x = 100;
if (x > 50) {
    cout << "x is greater than 50";
}
Enter fullscreen mode Exit fullscreen mode

This executes the block of code if the condition specified is true.

- If-Else Statement:

int x = 10;
if (x > 15) {
    cout << "x is greater than 15";
} else {
    cout << "x is not greater than 15";
}
Enter fullscreen mode Exit fullscreen mode

This runs the if block if the condition holds true; otherwise, it runs the else block.

- Else If Ladder:

int x = 100;
if (x > 150) {
    cout << "x is greater than 150";
} else if (x == 100) {
    cout << "x is equal to 100";
} else {
    cout << "x is less than 100";
}
Enter fullscreen mode Exit fullscreen mode

This allows for multiple conditions to be checked in order.

- Switch Statement:
This statement is used to choose one among many blocks of code to execute.

int color = 3;
switch (color) {
    case 1:
        cout << "Red";
        break;
    case 2:
        cout << "Blue";
        break;
    case 3:
        cout << "Yellow";
        break;
    case 4:
        cout << "Green";
        break;
    default:
        cout << "Invalid color";
}
Enter fullscreen mode Exit fullscreen mode
  • case: indicates a potential value of the variable being assessed.
  • break: concludes the switch block to avoid falling through to the subsequent cases.
  • default: is optional; it runs if none of the cases match.

6. Exploring Loops:

Loops are used to repeatedly execute a block of code as long as a specified condition is satisfied. C++ supports several types of loops:

  • For Loop: This loop is used when the number of iterations is known in advance.
for (int i = 0; i < 10; i++) {
    cout << i << endl;
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • int i = 0: Initializes the loop variable.
  • i < 10: The condition that is checked before each iteration.
  • i++: Updates the loop variable after each iteration.

  • While Loop: This loop is used when the number of iterations is not predetermined. It continues executing as long as the condition remains true.

int j = 0;
while (j < 10) {
    cout << j << endl;
    j++;
}
Enter fullscreen mode Exit fullscreen mode

In this case, the condition is checked before each iteration.

  • Do-While Loop: Similar to the while loop, the do-while loop ensures that the loop body is executed at least once because the condition is checked after the iteration.
int x = 0;
do {
    cout << x << endl;
    x++;
} while (x < 10);
Enter fullscreen mode Exit fullscreen mode

In this scenario, the loop body is executed first, and then the condition is checked.

7. Functions in C++

Functions are distinct blocks of code that are designed to execute specific tasks. They enhance modularity, promote code reusability, and facilitate a clearer understanding and maintenance of programs.

Rationale for Utilizing Functions

  • Code Reusability: A function can be written once and utilized multiple times, thus saving effort and reducing redundancy.
  • Modularity: Functions allow for the decomposition of complex problems into smaller, more manageable components.
  • Readability: The use of functions enhances the clarity of the main logic of the code.
  • Debugging: Errors can be more easily identified and addressed within isolated functions.

A function is comprised of three primary components:

  • Declaration (Prototype): This describes the function's name, return type, and parameters.
  • Definition: This contains the implementation details of the function.
  • Call: This is the mechanism by which the function is executed.

Syntax

return_type function_name(parameter_list) {
    // Function body
    return value; // Optional
}
Enter fullscreen mode Exit fullscreen mode

Example: Simple Function

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

int main() {
    cout << add(3, 4); // Output: 7
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Parameters and Return Values

  • Parameters: These serve as inputs to a function.
  • Return Value: This represents the output generated by a function.

Example

int multiply(int a1, int a2) {
    return a1 * a2;
}

int main() {
    cout << multiply(4, 5); // Output: 20
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Default Parameters
Functions may be defined with default parameter values, allowing such parameters to be omitted when invoking the function.

Example

void call(string name = "StackUp") {
    cout << "Hello, " << name << "Good morning!";
}

int main() {
    call();        // Output: Hello, StackUp Good morning!
    call("Amit"); // Output: Hello, Amit Good morning!
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Inline Functions
Inline functions are created using the inline keyword, thereby reducing the overhead associated with function calls.

Example

inline int square(int x) {
    return x * x;
}

int main() {
    cout << square(4); // Output: 16
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Recursive Functions
A recursive function is defined as one that invokes itself to address smaller instances of a problem.

Example

int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

int main() {
    cout << factorial(5); // Output: 120
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Function Overloading
Function overloading allows multiple functions to share the same name, provided that they possess different parameters.

Example

void print(int i) {
    cout << "Integer: " << i;
}

void print(double d) {
    cout << "Double: " << d;
}

int main() {
    print(10);    // Output: Integer: 10
    print(3.14);  // Output: Double: 3.14
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

8. What is a Pointer?

A pointer is defined as a variable that holds the memory address of another variable. This feature enables indirect access to variables and supports dynamic memory management.

  • Declaring Pointers
int *ptr;   // Declaration of a pointer to an integer
float *fptr; // Declaration of a pointer to a float
Enter fullscreen mode Exit fullscreen mode
  • Initializing Pointers A pointer may be initialized by assigning it the address of a variable.
int a = 10;
int *ptr = &a;  // ptr now contains the address of a
Enter fullscreen mode Exit fullscreen mode
  • Dereferencing Pointers Dereferencing a pointer refers to the process of accessing the value located at the memory address that the pointer references.
int a = 10;
int *ptr = &a;
cout << *ptr;  // Output: 10 (the value at the address stored in ptr)
Enter fullscreen mode Exit fullscreen mode
  • Pointer Arithmetic It is possible to perform arithmetic operations on pointers to navigate through arrays or memory blocks.
int arr[] = {1, 2, 3};
int *ptr = arr;
cout << *(ptr + 1);  // Output: 2 (accesses the second element of arr)
Enter fullscreen mode Exit fullscreen mode
  • Pointers and Arrays There exists a close relationship between arrays and pointers. The name of an array functions as a pointer to its first element.
int arr[] = {10, 20, 30};
int *ptr = arr;  // ptr points to arr[0]
cout << *ptr;  // Output: 10 (the value of arr[0])
Enter fullscreen mode Exit fullscreen mode
  • Null Pointer A null pointer indicates that it points to nothing. It is commonly utilized to initialize pointers to prevent them from referencing arbitrary memory locations.
int *ptr = nullptr;  // C++11 and later
Enter fullscreen mode Exit fullscreen mode
  • Pointer to Pointer A pointer may also reference another pointer.
int a = 10;
int *ptr1 = &a;
int **ptr2 = &ptr1;  // ptr2 points to ptr1
cout << **ptr2;  // Output: 10
Enter fullscreen mode Exit fullscreen mode
  • Dynamic Memory Allocation Pointers facilitate the allocation of memory dynamically using the new operator (for a single variable) and new[] (for an array).
int *ptr = new int;  // Allocates memory for a single integer
*ptr = 10;
cout << *ptr;  // Output: 10

int *arr = new int[5];  // Allocates memory for an array of 5 integers
delete ptr;  // Deallocates the memory allocated for the single integer
delete[] arr;  // Deallocates the memory allocated for the array
Enter fullscreen mode Exit fullscreen mode
  • Function Pointers Pointers can also point to functions, thereby enabling dynamic function calls.
void display() {
    cout << "Hello, World!";
}

int main() {
    void (*func_ptr)() = display;
    func_ptr();  // Invokes the display function
}
Enter fullscreen mode Exit fullscreen mode

9. Object-Oriented Programming (OOP) in C++:

Object-Oriented Programming (OOP) represents a programming paradigm that systematically organizes code into objects, which integrate data and methods. C++ stands out as one of the most widely utilized programming languages that support OOP principles. The features of OOP in C++ enable developers to create code that is clean, modular, and reusable. The foundational concepts—encapsulation, abstraction, inheritance, and polymorphism—facilitate the development of robust and maintainable software systems. Below is a concise overview of OOP concepts within C++.

Fundamental Concepts of OOP

  • Class: A blueprint for constructing objects, defining attributes (data members), and behaviors (functions or methods).
  • Object: An instance derived from a class, representing a tangible entity.
  • Encapsulation: The practice of bundling data and functions into a single unit (class). Data is typically concealed via access specifiers (private, protected, public).
  • Abstraction: The process of concealing complex implementation details while presenting only the essential features of an object.
  • Inheritance: A mechanism that permits one class to inherit attributes and behaviors from another class.
  • Polymorphism: The capability of diverse classes to be treated as instances of the same class through a common interface, enabling method overriding and function overloading.

Class and Object Declaration

Class Declaration:

   class Car {
   public:
       // Data members
       string model;
       int year;

       // Member function
       void displayInfo() {
           cout << "Model: " << model << ", Year: " << year << endl;
       }
   };
Enter fullscreen mode Exit fullscreen mode

Creating Objects:

   Car car1;          // Object instantiation
   car1.model = "Tesla";
   car1.year = 2023;
   car1.displayInfo();  // Invocation of member function
Enter fullscreen mode Exit fullscreen mode

Encapsulation in C++:

Access Specifiers: Private and Public:

  • Private: Members are accessible exclusively within the class itself.
  • Public: Members can be accessed externally from outside the class.
   class Account {
   private:
       double balance;  // Private data member

   public:
       void setBalance(double b) { balance = b; }  // Public setter method
       double getBalance() { return balance; }      // Public getter method
   };
Enter fullscreen mode Exit fullscreen mode

Inheritance

  • Base Class and Derived Class: A derived class acquires the attributes and methods of a base class.
   class Animal {
   public:
       void eat() {
           cout << "Eating..." << endl;
       }
   };

   class Dog : public Animal {  // Dog class inherits from Animal class
   public:
       void bark() {
           cout << "Barking..." << endl;
       }
   };
Enter fullscreen mode Exit fullscreen mode
  • Accessing Inherited Methods:
   Dog dog;
   dog.eat();  // Inherited method from Animal class
   dog.bark(); // Method defined in Dog class
Enter fullscreen mode Exit fullscreen mode

Polymorphism

Method Overloading: The use of the same function name with different parameters.

   class Calculator {
   public:
       int add(int a, int b) {
           return a + b;
       }

       double add(double a, double b) {
           return a + b;
       }
   };
Enter fullscreen mode Exit fullscreen mode

Method Overriding: The redefinition of a method in the derived class.

   class Base {
   public:
       virtual void show() {
           cout << "Base class show function" << endl;
       }
   };


   class Derived : public Base {
   public:
       void show() override {
           cout << "Derived class show function" << endl;
       }
   };
Enter fullscreen mode Exit fullscreen mode

Constructors and Destructors

Constructor: A special member function called when an object is created. It is used to initialize the object's attributes.

class Book {
public:
    string title;
    Book(string t) { title = t; }  // Constructor
};

Book b("C++ Programming");
Enter fullscreen mode Exit fullscreen mode

Destructor: A special member function that is called when an object is destroyed. It is used to free resources associated with the object.

class Book {
public:
    ~Book() { cout << "Destructor called!" << endl; }  // Destructor
};
Enter fullscreen mode Exit fullscreen mode

Abstract Classes and Interfaces

Abstract Class: A class that cannot be instantiated and contains at least one pure virtual function.

class Shape {
public:
    virtual void draw() = 0;  // Pure virtual function
};

class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing Circle" << endl;
    }
};
Enter fullscreen mode Exit fullscreen mode

Encapsulation Example:

#include <iostream>
using namespace std;

class Student {
private:
    string name;
    int age;

public:
    void setName(string n) {
        name = n;
    }

    string getName() {
        return name;
    }

    void setAge(int a) {
        age = a;
    }

    int getAge() {
        return age;
    }
};

int main() {
    Student student;
    student.setName("John");
    student.setAge(20);

    cout << "Name: " << student.getName() << ", Age: " << student.getAge() << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.