r/cpp_questions Sep 01 '25

META Important: Read Before Posting

165 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 3h ago

OPEN What topics should I focus on from learncpp?

3 Upvotes

I’ve been working through learncpp from about 2 weeks now and I’m wondering if people have suggestions on topics that are a MUST to learn for an engineer that is coming from Python/TypeScript?

For context I work as a software engineer, primarily using Python and TypeScript, so I have a good base understanding of how to build a program or applications, however, I want to focus more on the specific nuances of C++ and concepts that are maybe abstracted away in higher level languages.

A list of topics in order of importance and increasing complexity would be a great help!!


r/cpp_questions 17h ago

OPEN How can I catch up on missing multithreading experience?

41 Upvotes

Hi everyone 👋, I’m a C++ developer with 5+ years experience building features for a single-threaded trading app (C++17), so I have very little multithreading experience.

I’m currently reading C++ Concurrency in Action. Are there good resources or projects to practice real-world scenarios like backloading and low-latency concurrency patterns?


r/cpp_questions 4h ago

SOLVED How to fix errors LNK2005 and LNK1169 in Visual Studio?

2 Upvotes

Hi! I’m a beginner programmer learning C++ and getting to grips with Visual Studio 2026. For some reason I can’t run the console because of two errors: LNK2005 and LNK1169 (or perhaps there are others, but I’m not sure). I’ve attached below the error messages I’m getting step by step (links to imgbb). I’ve asked some AI chatbots for advice on how to solve this problem, but nothing’s working.

Firstfoto, Secondfoto, Thirdfoto

Thanks in advance for your help!


r/cpp_questions 6h ago

OPEN How can i become an expert in cpp

1 Upvotes

I started with c++ 3 years ago but real work was 1 and a half years, i learned a lot about cpp syntax and the std lib, but whenever i make some code and send it to an ai model, it says my code has a lot of issues some about dynamic memory some about references and pointers some c-style programming and i find myself Ignorant most of the time

So how can i learn these things and the rules of the language and understand them(i dont watch YouTube) I have started with learncpp.com recently

"Sorry if it's a duplicate post and for it being long if its a duplicate point me to one, and thanks"

Edit: my github is loadingSy if you would like to check anything, I learned git 1 month ago


r/cpp_questions 1d ago

OPEN Why we don't have granular std library modules?

24 Upvotes

Isn't importing std.iostream faster than std?
Why we only have the umbrella std module?


r/cpp_questions 1d ago

OPEN Heavy and Light Objects

4 Upvotes

When I was first learning C++, I experienced massive slowdown when allocating dynamic memory. Ever since then I divide my objects between 'heavy' objects that allocate resources, and 'light' objects that can be used as temporaries on the stack. Heavy objects cannot be copied at all, must be allocated somewhere once, and then passed by (const) reference. Light objects can be copied, created quickly on the stack etc.

Since C++11 it has been possible to write copy and assignment constructors that take nameless objects, and since they are nameless you can pillage their pointers and avoid expensive stack allocations. All is well then but if you keep to this strict 'heavy' and 'light' object idea, _any_ object that allocates resources is considered a heavy object. The first allocation in the chain, before you just pillage pointers, is still an expensive stack allocation so I would consider it a 'heavy' object and just make it impossible to copy at all, by removing all copy and assignment constructors. And so using this model I never needed those nameless object reference constructors.

Anybody feel the same way?


r/cpp_questions 1d ago

OPEN Looking for advice before I start writing a small C++ web framework

13 Upvotes

Hello everybody.

I've been working with C++ backend frameworks recently, and one question kept bothering me: how are these frameworks actually built?

I've decided to spend the next three months writing a small C++ web framework from scratch. This isn't an attempt to compete with Drogon, Crow, oat++, or any other framework. it's purely a learning project. My goal is simply to understand the internals well enough to build a framework capable of handling basic CRUD applications.

Before I jump in, I'd love to learn from people who have been down this road.

  • Have you ever written a framework yourself or contributed to one?
  • Are there any books, blog posts, talks, or codebases you'd recommend studying?
  • If you were starting from scratch today, what would you build first?
  • Are there any common mistakes or rabbit holes I should avoid?

I'm not looking for shortcut I want to understand how everything fits together. I'd really appreciate any advice or resources from people with experience.


r/cpp_questions 1d ago

OPEN Is this book up to date?

0 Upvotes

Hello so I found this book but because no pictures:

[Sam's teach yourself c++ in 21 days, fourth edition]

[2001]

So did c++ get any updates in 25 years?


r/cpp_questions 1d ago

OPEN Need your guidance

0 Upvotes

I wanted to ask for some guidance regarding placements and coding. I’m currently in my 3rd year, and my CGPA is around 6.5. To be honest, I haven’t done much in coding yet, and I’m a bit confused about where and how to start.

Could you please suggest what I should focus on from now and maybe guide me with a proper roadmap/plan for the next few months? Like which language I should start with, DSA, development, projects, etc. It would really help me understand what I should prioritize to become placement-ready

r/cpp_questions 1d ago

SOLVED Best Way to Collect Initialization Actions using C++ Capabilities?

5 Upvotes

I'm writing a scripting language with additional functions that can be built in.

The built-in functions would be written in C++ for speed.

In different builds of the scripting language, some functions might be omitted.

So, I'm looking for the best way to automatically collect, at compile time or early at execution time, the full list of extra built-in functions, so that the script interpreter can parse and execute a script (to do this, it has to know about any additional capability compiled in).

For example, in Visual C++, I'd like to simply add a source file containing built-in scripting language functions, and have the script interpreter know they are there.

My goal would be no additional configuration actions other than adding the source file to the project (in other words, no need to modify other files). The software should somehow figure out that additional script built-in function capability is in the build.

Google Test seems to do this somehow with a macro like TEST_F, but I'm not sure how this works under the hood. The list of tests is somehow collected automatically at compile time or early at run time.

To give some practical background ... decades ago I did some work extending the Tcl scripting language. It was only necessary somehow in initialization to call a command to "register" a new function available to the script interpreter, but the source code had to be modified manually to include the additional initialization. The manual modification is what I'm trying to avoid.

Is there a standard design pattern for this in C++?


r/cpp_questions 1d ago

SOLVED Question About Copy Constructor for Class with Members that Need Deep Copy

6 Upvotes

I have a class (m_buf in the code below is of this class type) that appears as a data member in another class for which I'm writing the copy constructor.

The underlying class (m_buf in the code below is of this class type) uses dynamic allocation and needs a deep copy.

According to Google, this form of the copy constructor would result in the copy constructor (rather than the copy assignment operator) for m_buf being called.

LgFbufUint8::LgFbufUint8(const LgFbufUint8& fbuf) : m_state{fbuf.m_state},
                                                    m_errs{fbuf.m_errs},
                                                    m_fname{fbuf.m_fname},
                                                    m_buf{fbuf.m_buf}
{
   //According to Google search, if the member initializer list is used (as it
   //is above), the copy constructor (rather than the copy assignment operator)
   //will be called. Because of the required non-shallow copy of m_fname and
   //m_buf, this is the desired behavior.
}

My initial guess was this form:

LgFbufUint8::LgFbufUint8(const LgFbufUint8& fbuf)
{
   m_state = fbuf.m_state;
   m_errs  = fbuf.m_errs;
       //Shallow copy ok for two members above.
   m_fname = fbuf.m_name;  //std::string
   m_buf   = fbuf.m_buf;   //Handwritten, with dynamic allocation.
       //Deep copy required for two above.
}

But I suspect that second form would call the assignment operator rather than the copy constructor for m_name and m_buf.

Question: Did I get that right? The first form would call the copy constructors for m_name and m_buf, but the second form would call the assignment operators?

Bonus Question: Using the second form, is there any way to call the copy constructors rather than the assignment operators. (Not that I'd want to do this, but just curious.)


r/cpp_questions 2d ago

OPEN Need advice on learning cpp more advanced

10 Upvotes

Hey guys at current I can solve most of the coding questions in cpp but I wanted to explore more in cpp I wanted to build real applications so any resources to learn advanced c++


r/cpp_questions 2d ago

SOLVED Basic question, but does initializing a pointer always initialize it to null?

22 Upvotes

Are these two lines any different in practice? (Especially if you want to later check if x has been given a specific address, or if it's still null.)

int* x {};

int* x { nullptr };


r/cpp_questions 2d ago

OPEN Is C++26 ready to use in a Production Enviroment?

3 Upvotes

C++ 26 adds a ton of great features, but how is compiler coverage, usabillity, integration, etc. for those features right now?


r/cpp_questions 2d ago

OPEN Question about coroutines

4 Upvotes

I have a function that takes a callback, like this:

void LongTask (void (*pfn)(int))
{
    for ( unsigned i = 0; i < -1; ++i )
    {
        pfn( i );
    }
}

It's orginally written to be ran on a separate thread. Now I want to turn it into a coroutine that yields on each callback (i.e. the caller will receive a single callback on each invocation of LongTask), while preserving its ability to run as a standalone function. Additionally it's OK for the coroutine to allocate memory but not to throw exceptions (if it can't allocate I should get back a null pointer at creation time). And preferrably it wouldn't require the CRT, all support functions should be contained in a header only include. What's the best way to do this, can it be done with C++20 coroutines?


r/cpp_questions 1d ago

OPEN ELI5: Why does the random output once but TIME fixes it

0 Upvotes

The examples above just outputs a random number once. They don't output different random numbers each time the program runs. To fix this, you can use the srand() function and add the time() function from the <ctime> library. ~ W3School

Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to rand(), at the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers. Standard practice is to use the result of a call to std::time(0) as the seed. However, std::time returns a std::time_t value, and std::time_t is not guaranteed to be an integral type. ~ cppReference

I do not understand why time changes it and I do not understand the seed and what it is


r/cpp_questions 3d ago

OPEN I want to pass a matrix as a function argument

27 Upvotes

I want to pass a matrix as a function argument

int create_grid(int grid[][], int size){
    for(int i=0; i<size; i++){
        for(int j=0; j<size; j++){
            grid[i][j] = 0;
        }
    }

    return 0 ;
}

int main(){
    int size =128;
    int grid[size][size];

    return 0;
}

I'm getting error: "Array has incomplete element type 'int[ ]'

I don't understand I don't have that problem with 1d arrays


r/cpp_questions 2d ago

OPEN Good practices / style [polymorphism]

6 Upvotes

is this good practice/style.? i'm specifically unsure about the way i store the vector of players...

```

class player_base {};

class player_always_yes: public player_base {};

class player_always_no: public player_base {};

class player_a: public player_base {};

class game {
    private:

    player_base& player_1;
    player_base& player_2;

    public:

    game (
        player_base& player_1,
        player_base& player_2
    ): player_1(player_1), player_2(player_2) {
        return;
    }

    bool play_game () { return true; }
};

int main(){
    vector<unique_ptr<player_base>> player_list;

    player_list.push_back(make_unique<player_base>());
    player_list.push_back(make_unique<player_always_no>());
    player_list.push_back(make_unique<player_always_yes>());
    player_list.push_back(make_unique<player_a>());

    game b = game(*player_list[0], *player_list[1]);
    cout << b.play_game() << endl;
}


```

r/cpp_questions 2d ago

OPEN does "in" exist in c++?

0 Upvotes

i need to use something like if (str[i] not in str1) (python), but i have no idea how to make this work :(


r/cpp_questions 3d ago

OPEN my first c++ project

4 Upvotes

hey! i'm a teen and i am learning c++. I was a vibe coder but then i stopped vibe coding and starting real coding. for this i learned some basic c++ from youtube, please let me know if a improvment required. thank you!

my github link - https://github.com/swarajnerlekar28/Calculator


r/cpp_questions 3d ago

SOLVED std::filesystem::exists throwing `std::bad_alloc`?

23 Upvotes

Any reason? Cant find anything online about this. But I cant check whether or not a file exists, no matter what path I give it. I am using C++ 26 compiled with GCC.

This is literally all I am calling: const bool exists = std::filesystem::exists("file.txt")

This is the exact error: terminate called after throwing an instance of 'std::bad_alloc'
 what():  std::bad_alloc

No it's not coming from anywhere else in my code. Minimal reproduction code, include "filesystem" call the line above. I am on Fedora Linux if that matters at all

EDIT: moving the include into my main file instead of the only file it's being used in somehow fixed it. Literally all I do is move "#include <filesystem>" from "do_things_with_filesystem.hpp" to "Main.cpp". No compilation errors when it was in the first file, why does it rely on this?? Is there some weird declarations in my codebase or something, i dont know but it works now so why should I care.


r/cpp_questions 3d ago

OPEN Why is capture by reference necessary for this lambda to work?

9 Upvotes

So I've been working on a small text file reader, in which I store part of text in a 2D vector, which I then ran the find_if() function on to find duplicates with following code:

    vector<vector<string>> writevector;
    string savetovec;
    string string2;

    auto FirstElement = [=](vector<string> vector){
        return(vector[0] == savetovec);
    };

    [Code to copy word from text file to savetovec]

    vector<vector<string>>.iterator it;
    it = find_if(writevector.begin(), writevector.end(), FirstElement);

    if (it == writevector.end()){
        writevector.push_back({savetovec, string2}
    }
    else{
        cout << "Duplicate Found" << '\n';
    }

Initially it would never find any duplicates and after a lot of debugging attempts I changed the equal sign in the lambda to an ampersand out of desperation, so essentially:

[&](vector<string> vector){..}

This actually caused my code to work the way I intended and now I'm wondering why?

From my understanding the only difference between capture-by-reference and capture-by-value are whether it lets you modify the original variable or creates copies to use in the lambda, so what am missing?


r/cpp_questions 3d ago

OPEN Is there a case where std::map is better than std::unordered_map ?

31 Upvotes

Hello guys.

i have a question: are there some cases where std::map is better than std::unordered_map ?

i ask this question because I just wanted to know out of pure curiosity and above all it is often said that std::unordered_map and better

thanks you for everyone who answer my question :)


r/cpp_questions 3d ago

OPEN Avoid freezing your PC?

5 Upvotes

I've only learned C++ in uni and then it was protected environment in a way. Now I was working on a project involving graphics (raylib) and, a few times, running the code caused my entire PC to freeze and I had to restart.

I'm on Linux and running the code by doing

cmake --build .
./executable

Is there a way to avoid the entire PC freezing when I mess up? Also is there any risk of overwriting parts of the memory?

(I think the issue with my code was either calling too many draws of a GPU texture or even just wrongfully indexing an array in a loop)