C++ Syntax


creation date: 2025-01-16 09:25
modification date: 2025-01-16 09:25


C++ Syntax

Scope Resolution

In C++, something::something denotes the scope resolution operator.

Here's a breakdown:

Examples:

Namespace Scope:

namespace MyNamespace {
    int x = 10; 
}

int main() {
    int x = 5; 
    std::cout << MyNamespace::x << std::endl; // Accesses x from MyNamespace
}

Class Scope:

class MyClass {
public:
    int x;
    void printX() {
        std::cout << x << std::endl; 
    }
};

int main() {
    MyClass obj;
    obj.x = 10; 
    obj.printX(); 

    std::cout << MyClass::x; // This will likely result in an error 
                           // because 'x' is a member variable, not a static member
}

Key Points:

std

In C++, std stands for the standard namespace.

Scope Resolution Operator:

std::cout << "Hello, world!" << std::endl; 
std::vector<int> myVector = {1, 2, 3};

Using Directive:

using namespace std; 

cout << "Hello, world!" << endl; 
vector<int> myVector = {1, 2, 3};

This brings all the entities from the std namespace into the current scope, making their names directly accessible. However, this can lead to potential naming conflicts if you have other entities with the same names.

In summary:

The std namespace is fundamental to C++ programming. It provides a vast collection of tools that you'll use extensively in your projects. Using the scope resolution operator is generally considered better practice than the using directive to avoid potential naming conflicts.

cout

In C++, cout is an object that represents the standard output stream.

What it does:

Example:

#include <iostream> 

int main() {
    std::cout << "Hello, world!" << std::endl; 
    return 0;
}

This code will print the message "Hello, world!" to the console.

Key points:

Dynamic Memory Allocation

What it is:

new and delete:

new:

Example:

int* ptr = new int; // Allocate memory for an integer
*ptr = 10;

delete:

Example:

delete ptr; // Deallocate the memory pointed to by ptr

malloc and free:

malloc:

Example:

int* ptr = (int*)malloc(sizeof(int)); 
*ptr = 10;

free:

Example:

free(ptr);

Memory Leaks:

Dangling Pointers:

Smart Pointers

What they are:

unique_ptr:

shared_ptr:

Example:

#include <memory>

int main() {
    std::unique_ptr<int> uniquePtr(new int(5)); 
    std::shared_ptr<int> sharedPtr(new int(10)); 

    // ... use the pointers ...

    return 0; // uniquePtr and sharedPtr go out of scope, 
            // the objects they point to are automatically deleted
}

Key Advantages of Smart Pointers:

In summary: