r/cpp_questions • • Sep 01 '25

META Important: Read Before Posting

189 Upvotes

Hello people,

Please read this sticky post before creating a post. It answers some frequently asked questions and provides helpful tips on learning C++ and asking questions in a way that gives you the best responses.

Frequently Asked Questions

What is the best way to learn C++?

The community recommends you to use this website: https://www.learncpp.com/ and we also have a list of recommended books here.

What is the easiest/fastest way to learn C++?

There are no shortcuts, it will take time and it's not going to be easy. Use https://www.learncpp.com/ and write code, don't just read tutorials.

What IDE should I use?

If you are on Windows, it is very strongly recommended that you install Visual Studio and use that (note: Visual Studio Code is a different program). For other OSes viable options are Clion, KDevelop, QtCreator, and XCode. Setting up Visual Studio Code involves more steps that are not well-suited for beginners, but if you want to use it, follow this post by /u/narase33 . Ultimately you should be using the one you feel the most comfortable with.

What projects should I do?

Whatever comes to your mind. If you have a specific problem at hand, tackle that. Otherwise here are some ideas for inspiration:

  • (Re)Implement some (small) programs you have already used. Linux commands like ls or wc are good examples.
  • (Re)Implement some things from the standard library, for example std::vector, to better learn how they work.
  • If you are interested in games, start with small console based games like Hangman, Wordle, etc., then progress to 2D games (reimplementing old arcade games like Asteroids, Pong, or Tetris is quite nice to do), and eventually 3D. SFML is a helpful library for (game) graphics.
  • Take a look at lists like https://github.com/codecrafters-io/build-your-own-x for inspiration on what to do.
  • Use a website like https://adventofcode.com/ to have a list of problems you can work on.

Formatting Code

Post the code in a formatted way, do not post screenshots. For small amounts of code it is preferred to put it directly in the post, if you have more than Reddit can handle or multiple files, use a website like GitHub or pastebin and then provide us with the link.

You can format code in the following ways:

For inline code like std::vector<int>, simply put backticks (`) around it.

For multiline code, it depends on whether you are using Reddit's Markdown editor or the "Fancypants Editor" from Reddit.

If you are using the markdown editor, you need to indent every code line with 4 spaces (or one tab) and have an empty line between code lines and any actual text you want before or after the code. You can trivially do this indentation by having your code in your favourite editor, selecting everything (CTRL+A), pressing tab once, then selecting everything again, and then copy paste it into Reddit.

Do not use triple backticks for marking codeblocks. While this seems to work on the new Reddit website, it does not work on the superior old.reddit.com platform, which many of the people answering questions here are using. If they can't see your code properly, it introduces unnecessary friction.

If you use the fancypants editor, simply select the codeblock formatting block (might be behind the triple dots menu) and paste your code into there, no indentation needed.

import std;

int main()
{
    std::println("This code will look correct on every platform.");
    return 0;
}

Asking Questions

If you want people to be able to help you, you need to provide them with the information necessary to do so. We do not have magic crystal balls nor can we read your mind.

Please make sure to do the following things:

  • Give your post a meaningful title, i.e. "Problem with nested for loops" instead of "I have a C++ problem".
  • Include a precise description the task you are trying to do/solve ("X doesn't work" does not help us because we don't know what you mean by "work").
  • Include the actual code in question, if possible as a minimal reproducible example if it comes from a larger project.
  • Include the full error message, do not try to shorten it. You most likely lack the experience to judge what context is relevant.

Also take a look at these guidelines on how to ask smart questions.

Other Things/Tips

  • Please use the flair function, you can mark your question as "solved" or "updated".
  • While we are happy to help you with questions that occur while you do your homework, we will not do your homework for you. Read the section above on how to properly ask questions. Homework is not there to punish you, it is there for you to learn something and giving you the solution defeats that entire point and only hurts you in the long run.
  • Don't rely on AI/LLM tools like ChatGPT for learning. They can and will make massive mistakes (especially for C++) and as a beginner you do not have the experience to accurately judge their output.

r/cpp_questions • • 42m ago

OPEN Title: Why use a functor instead of a static variable in C++?

5 Upvotes

If a function can maintain state between calls using a static variable, why would we use a functor to achieve the same thing?

What advantages do functors offer in practice, and when would you choose one over a function with a static variable?

I'm curious about the reasoning behind this design choice in C++.


r/cpp_questions • • 11h ago

OPEN Starting C++ with a little programming background.

10 Upvotes

I’ve been into programming and software since highschool which’s when i started self learning python. I’m not an expert in python but i know logic flow, functions, data types, loops, lists and dictionaries.
Now i’m in my sophomore year majoring in Math Science. Turns out python is used mostly for scientific research. However, I plan to work in industry rather than go the academic and research route.
I wanted to find a book that covers C++ topics intensively, absolute beginner level, and also having enough chapters where after i finish, i’d have a strong background and could easily dive into a specific part of C++.
So far i’m just learning the basics of software engineering and programming, haven’t yet decided what i wanna do.


r/cpp_questions • • 16h ago

OPEN where am I heading?

0 Upvotes

I've recently started learning c++ and will go through every part of it and its related stuff. the goal is to learn until i can myself work on projects where micro-seconds matter. passed only high school, followed my family business. now i want to make a career out of this. i've also studied about dsa, networking low level stuff, basics ... . can experienced , currently in-industry people tell me what can i expect and what compnies/niche i can work in given my background? Thanks for your time.


r/cpp_questions • • 22h ago

OPEN Can you recommend a good source for learning constexpr/consteval patterns?

1 Upvotes

The specific thing I'm thinking of right now is a function that looks like:

auto func(auto... args)
{
    for each arg {
        if arg is type T {
            do a thing with T
        }
        else if arg is type U {
            do a thing with U
        }
        else {
            compile error
        }
    }
}

but I'm not just looking to solve just this specific issue, I'd like to learn a substantial amount of this skillset.


r/cpp_questions • • 17h ago

OPEN What extent did "Black October" affect the transition from C++ to Rust?

0 Upvotes

I'm cs student and i was thinking about how this will affect or change the shift from the foundational language C++ to Rust. I want to see what those with more experience in this field think.


r/cpp_questions • • 1d ago

OPEN I'm going to build a kernel in c++ just for a better engineering understanding of a os.

17 Upvotes

Anyone who worked on something similar? I would really appreciate the advice. Going to use Bare Bones for it.


r/cpp_questions • • 1d ago

OPEN Switching from Thinkpad to M2 Air? What would I give up for C++ dev?

0 Upvotes

How different of an experience would it be doing things like C++ dev, learning Docker, as well as gaining experience developing on Linux if I switched from a Thinkpad having 32GB RAM to a M2 MacBook Air having 24GB of RAM and 256GB of storage? I‘d create a small partition to install Asahi Linux. On Windows, I like using VS Code and Notepad++. I also want to start a project using SFML and work on a project that using networking C++ libraries (for example, making a chatting program for fun, or a game that can be played between two players over the same WiFi network).


r/cpp_questions • • 1d ago

OPEN I have trouble with testing my Controller module

2 Upvotes

I'm coding the classic Snake game using Cpp + Qt. Right now, one of my modules is a GameController, that conects the other classes (snake, apple and board), for the game loop:

/* the class atributes: 
private: 
  std::unique_ptr<Board> game_board; 
  Snake game_snake; 
  Apple game_apple; 
  int score; 
  Snake::direction key_pressed; 
  QTimer *timer; */

GameController::GameController(std::unique_ptr<Board> next_board):game_board{std::move(next_board)}, game_snake(calculate_snake_initial_position(game_board->getInitialPosition())), game_apple(calculate_apple_position()),score{0} { timer = new QTimer(this); connect(timer,&QTimer::timeout,this,&GameController::GameTick); 
key_pressed = Snake::left; 
}

  QPoint GameController::calculate_apple_position()
    {
        QList<QPoint> free_cells = game_board->getValidPositions();
        QPoint new_coordinates;
        bool found;
    
        do{
            std::srand(std::time(0));
            int random_value = std::rand();
    
            new_coordinates.setX(free_cells[random_value % free_cells.size()].x());
            new_coordinates.setY(free_cells[random_value % free_cells.size()].y());
    
            found = game_snake.is_occupied(new_coordinates);
        }while(!found);
    
        game_board->occupyCell(new_coordinates); 
    }
    
    QList<QPoint> GameController::calculate_snake_initial_position(QPoint head)
    {
        QList<QPoint> snake_body;
        snake_body.push_back(head);
    
        game_board->occupyCell(head);
    
        for(int i = 0; i < 3; i++){
            head.setX(head.x()+1);
            snake_body.push_back(head);
            game_board->occupyCell(head);
        }
    
        return snake_body;
    }
    
    void GameController::end_game(bool ending_status)
    {
        stop_timer();
    
        emit game_finalized(ending_status);
    }
    
    
    bool GameController::key_validation(int key)
    {
        bool right_key = false;
    
        if(key == Qt::Key_W || Qt::Key_Up){
            key_pressed = Snake::up;
            right_key = true;
        }
        else if(key == Qt::Key_A || Qt::Key_Left){
            key_pressed = Snake::left;
            right_key = true;
        }
        else if(key == Qt::Key_S || Qt::Key_Down){
            key_pressed = Snake::down;
            right_key = true;
        }
        else if(key == Qt::Key_D || Qt::Key_Right){
            key_pressed = Snake::right;
            right_key = true;
        }
    
        return right_key;
    }
    
    void GameController::start_timer()
    {
        timer->start(300);
    }
    
    void GameController::stop_timer()
    {
        timer->stop();
    }
    
    void GameController::GameTick(){
    
    
        if(game_board->getValidPositions().empty()) 
        {
            end_game(true);
        }
        else if(game_board->colisionedWithBoard(game_snake.head()))
        {
            end_game(false);
        }
        else
        {
            bool crece = false;
            if(game_snake.is_occupied(game_apple.position())) 
            {
                game_apple.position(calculate_apple_position());
                game_board->occupyCell(game_apple.position());
                emit apple_render_requested(game_apple);
    
                score+=10;
                emit score_render_requested(score);
    
                crece = true;
            }
            game_snake.move(key_pressed,crece);
            game_board->occupyCell(game_snake.head());
            if(!crece) game_board->freeCell(game_snake.tail());
            emit snake_render_requested(game_snake);
        }
    }

However, now I'm writing the tests and I realized that I don't have a way to really test it. If I want to test if the new apple position is generated correctly, I can't access the board or the apple to do so. I can check if its inside the permited board space by hardcoding it, but I think it is a bad practice. The same goes for snake position, the key validation, constructor...

The one that seems fine is the GameTick, has I just need to check if It throws signals correctly.

My first guess is to refactor the code, or move it to their respective classes, but I don't want to do the latter unless is the only way, has I want them to be isolated from each other in order to keep coupling as low as possible.


r/cpp_questions • • 1d ago

OPEN Does compile-time evaluation only happen when there are constant expressions or can they happen when there are runtime expressions?

1 Upvotes

r/cpp_questions • • 2d ago

OPEN I still have no idea how to implement linked lists

3 Upvotes

I don't effectively know how to make them work because it feels abstract that I can just say something points to a node that isn't even there yet, and I especially don't know how to make it get data without me manually assigning it to each node.

For example, there's an assignment that asks me to make a linked list read and put in each node numbers that it will take from a .txt file. I don't even know where to start.

And I'm afraid if I don't understand this, I won't be able to understand abstract data types either.


r/cpp_questions • • 3d ago

OPEN Operator + overloads on std::string

7 Upvotes

Consider https://godbolt.org/z/oY9r59P5E

#include <string>

const char *temp = "Hello";

std::string returnstring(){
    return "abc";
}

int main(){
    std::string abc = temp + returnstring() + "_";
    std::string def = temp + "_";
}

The second line in main() does not compile with the error of "invalid operands". The first line compiles fine and that can only be due to the intervening "returnstring()" call which returns an std::string, somehow.

What is the cleanest way to get the intent behind the second line to compile? In my application, I cannot change const char * temp into an std::string.


r/cpp_questions • • 2d ago

OPEN project resume worth

0 Upvotes

how to think about projects? like where does the ideas come from? and then how to work upon the libraries needed for it and learning it? also as a beginner is the freecoddecamp's 31 hour video a good place to learn cpp, ik the basics of it like the bit needed for dsa but not any advanced .
thank u


r/cpp_questions • • 2d ago

OPEN Learning c++ for a exam

0 Upvotes

Guys I've my exam coming up next week of Object oriented programming it's the midterm so you can say that it's not advanced level exam but a basic level

I want to learn it and practice for my exam I tried learning it with the help of chatgpt but I feel like I'm not getting it it's not that efficient

What's the best way to learn its basics online in a few number of days ?

I'm not saying that I'll be at pro level in a week but just to pass the exam

Give your best recommendations for learning c++ online with free resources


r/cpp_questions • • 3d ago

OPEN Dangling Pointers and Function Execution

0 Upvotes
ManagerVariableR* Local = new ManagerVariableR();
Local->Handler["New"] = Var{};

MB.Execute(FuncName, { Local });
delete Local;/// Grand Promblem here, after deletion of pointer it will crash

Soo if you see, Its Working when i am passing the pointer and not deleting the pointer at end

, And crashing when i am deleting the pointer at the end.

MB.Execute is a just Function Handler, i had linked function pointer to a string using hash map to call them. and the fucntion is succesfully called,

if i tell you about more the at runtime a function is compiled to a dll file, and it is retrwing the function using windows.h LoadLibaryA

 aHMODULE handle = LoadLibraryA(libPath.c_str());HMODULE handle = LoadLibraryA(libPath.c_str());

to a format of function of void ptr

typedef void (*fn)(ManagerVariable* Local);typedef void (*fn)(ManagerVariable* Local);

and i am just executing it by my function handler that sotres the function you can check it out here

https://github.com/iampokebro/FLOW-/blob/main/Flow%2B%2B/Backend/Functionlity/ManagerBase/ManagerBase.h

but problem is not related to this.

overall problem is that when the pointer is delete after the call it crash. i used future and promise to do waiting but it also failed. i think that function from .dll is not close from background or maybe its stack is left behind operating.

if this solves then it would be sooo great for my project,

NOTE -> the program memory operates at same level, so there is no pointer mismatch problem

i dont want to try chancing the architecture cause it will ruin the efficiency maybe


r/cpp_questions • • 3d ago

OPEN Starting cpp with learn cpp.com

5 Upvotes

i have been wanted to learn cpp for quite long and finally i have the time

and asked a friend about courses and stuff and got recommended learn cpp, i have seen a lot of people fond of this website

I know like really basic python dict lists def and all, 11th grade CS basically, im still learning python though on a really slow pace because well school wont go faster

Thinking about 5 days a week a hour or two each day, i think ill finish this course in about a year

what im here to ask is, can i start with learn cpp?


r/cpp_questions • • 3d ago

OPEN Why does entering a string value into a variable declared as an `int` result in an output of 0?

0 Upvotes
#include "std_lib_facilities.h"
int
 main()
{
    cout << "Enter your name and age(and press Enter):\n";
    string first_name = "???";
    
int
 age = -1;
    cin >> first_name >> age;
   
    cout << "Hello, " << first_name << " (age " << age << ")\n";
}

I recently started learning C++ using the book "Programming: Principles and Practice Using C++." In one of the author's examples, there is code that, when given the input "22 Carlos," is supposed to output "Hello, 22 (age -1)." However, I get 0 instead of -1, and I don't understand why. Could this have something to do with the C++11 standard?


r/cpp_questions • • 3d ago

OPEN Is this a good use-case for an inline function?

0 Upvotes

I need a function for generating hashes for different files in my program. I'm using Stephan Brumme's hashing library fwiw. It struck me that this is the kind of thing that might be useful in other parts of my program, so rather than write into a single class, I've opted to write a standalones.h file for rarely used but generally useful functions. Claude assures me that making this an "inline" function is the correct way to go about this, but I guess it bothers me that the function isn't tied to any specific namespace, so if I ever have a naming conflict in some file, what prevents me from accidentally calling the wrong function? I don't necessarily have a problem with inlining if that is indeed the correct way to do this, I just want some assurance that an accidental call via a naming conflict won't happen.

My code:

#pragma once

#include <string>
#include <fstream>
#include <filesystem>
#include <optional>

#include "sha256.h"

namespace fs = std::filesystem;

inline std::optional<std::string> getFileHash(const fs::path& file)
{
    std::ifstream binaryOpen(file, std::ios::binary);
    if (!binaryOpen.is_open())
        return std::nullopt;
            
    SHA256 pHash;
    constexpr int bufferSize = 64 * 1024;
    char binBuffer[bufferSize];
    while (binaryOpen)
    {
        binaryOpen.read(binBuffer, sizeof binBuffer);
        pHash.add(binBuffer, binaryOpen.gcount());
    }

    if (binaryOpen.bad())
        return std::nullopt;
    std::string rHash = pHash.getHash();

    return rHash;
}

r/cpp_questions • • 4d ago

OPEN What is the best way to build a physics engine from scratch?

7 Upvotes

Hi guys, i have a poor english but i thing you can understand!

Actually i've been studying about quantum physics in university, and create a engine using a low level language seems a very cool challenge.

Well, i already have a very good knowledge in java and linux fundamentals, so what is the best way to learn c++ in this case?


r/cpp_questions • • 4d ago

OPEN i want to learn cpp but dont know where to

5 Upvotes

im a 11th student.. i want to be a gamedev and i want to learn c++ and some other stuff before i enter into btech .....so i need videos to learn .....plz dont recommed me learncpp....i want video tutorials


r/cpp_questions • • 5d ago

OPEN Where does the Curiously Recurring Template Pattern actually earn its keep in production code

6 Upvotes

I understand CRTP 👀 class Derived : public Base<Derived>, static polymorphism, no vtable overhead. Every tutorial shows the same toy example with `Shape` and `area()`, and then it stops. What I can't find is real-world usage. I'd love to hear where you've actually shipped it, and why prefer beat the Mixin or policy‑based design. Use cases I've seen so far:

Mixins, like std::enable_shared_from_this, to inject behavior into the derived class

Static interfaces for hot paths where virtual dispatch costs too much

Expression templates in Eigen

I'm still unsure about whether-

  1. Is it worth the readability cost since C++20 has concepts and deducing this?
  2. Any production pitfalls like error messages, code bloat, or slicing issues?

If you've used it in a codebase you maintain, I'd love to hear what problem it solved and if you derived any reusable patterns that you continue to use as snippet when shipping production code under limited time constraints. 🙏


r/cpp_questions • • 6d ago

OPEN Great C++ Software Engineering techniques

38 Upvotes

Currently starting up a new project and I really want to emphasize very sophisticated uses and practices that make it beyond just a toy project and a real software engineering project. I'm using Alpaca for live market feed so I'm learning about socket programming but I wanna ask, what are some very very useful techniques to know that actually prep for C++ software jobs? Stuff like CI/CD, Yaml, and other toolchains that make hiring managers look and take notice


r/cpp_questions • • 5d ago

OPEN C

0 Upvotes

So I wanna learn c and c++ , all ik is python learning c is very very hard for me . I tried all possible ways like yt tutorials, books, using ai etc it's really tough the syntax (often confusing with python) and logic everything is sorted tuff. Please suggest some sources and tips


r/cpp_questions • • 6d ago

OPEN Why are exceptions so "backstabby"?

37 Upvotes

Simply put, I often find myself being told that exceptions "are not that costly" and that "the compiler puts it on cold sections anyways".

As a forenote, I'm the kind of person who always does `-fno-rtti -fno-exceptions` as I value code size usage (I develop small embedded shit and such, which does lead me to decorate functions with alignas and other thingies). Sometimes I also drop using the libc/libc++ and do syscalls raw because I can't stand the overhead (malloc/operator new is a great general purpouse allocator, but it doesn't suit my specific performance needs for example), so I take the hit from doing a syscall for a big mmap and then manually allocate memory by using fixed upper bounds.

(Ok also because glibc malloc sucks, but that is another topic)

Now with that noted, I have one pique in life: Why should I even use exceptions?

I often find myself removing exceptions of whatever codebase I happen to contribute to. Which does lead to people telling me that "you shouldn't do that".

The reason they often cite is either:

- It's not that important in the grand scheme of things (Valid, but so is every 'death by a thousand cuts')

- It makes code less clear (I'd argue otherwise)

- It's standard/idiomatic (Yeah and so is std::auto_ptr)

I really want to know WHY should I even use exceptions. I feel like they're a waste of language grammar I'm forbidden for touching, for it would bring me great despair.

As a cited case; recently I was working on optimizing a JSON parsing loop (oh scary). Obviously the final solution was not using JSON and just doing raw text with the |0x202020 casecmp trick.

But after collecting the values on a vector (I'd rather prefer a VLA to avoid indirection btw) I saw that the specialization of the vector for the non trivial class did in fact make a bunch of garbage for a case that I would have not hit otherwise.

https://godbolt.org/z/MPb9xnYqx

Like this is dumb, I'm not developing code for an airplane, if the thing runs out of memory it's just gonna crash anyways.

And no, noexcept also sucks because it just wraps shit around {} with std::terminate(), which is dumb (atleast on MSVC, but whatever).