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 • • 2h ago

SOLVED Memory leak in a virtual destructor of an abstract base class

3 Upvotes

I have an abstract base class from which other classes are derived. It has a pure virtual method and a virtual destructor with an empty body:

class LibraryItem
{
protected:
    int id;
    std::string title;
    std::string author;
    int year;
    int cost;

    friend class BookEditor;
public:
    
// other methods...

    virtual void Print() const = 0;

    virtual ~LibraryItem() {}
};

My teacher said that I have a memory leak here, but I don't understand why.
The destructor is virtual, so when an object of a derived class is deleted through a LibraryItem*, the derived destructor should be called first, and then the base destructor.
I have always written destructors this way and have never received any complaints.

Some other students told me that because I declared the destructor with an empty body:

virtual ~LibraryItem() {}

because "it does NOTHING**"**. But I thought it does nothing EXCEPT destroy the fields automatically. None of the fields in LibraryItem are raw pointers that would need to be deleted manually, so I don't understand where exactly my mistake / memory leak is.

I have seen people suggest writing:

virtual ~LibraryItem() = default;

I would be very grateful if someone could explain:

  1. whether an empty virtual destructor like virtual ~LibraryItem() {} can itself cause a memory leak;
  2. what the difference is between virtual ~LibraryItem() {} and virtual ~LibraryItem() = default; in this context.

I was looking for similar questions, but I couldn't figure it out on my own.


r/cpp_questions • • 15h ago

OPEN Help With Using Standard Libraries In My Hyper-Specific Project

2 Upvotes

Hello, everyone. I've recently taken up a project where I work to streamline and rewrite an originally vibecoded project which allowed for the creation of custom DLLs which could be loaded by the game Serious Sam 2. From what I've gathered, the AI that wrote the original project created an environment isolated from the rest of the system and does not allow access to any standard library features. I've looked through this project's makefile to try and find what exactly is causing this and how to rectify it. Unfortunately, I do not believe that I am skilled or knowledgeable regarding makefiles to diagnose the problem and solve it. I have moving the code elsewhere and using auto-generated cmake files from IDEs such as CLion, and the library would compile, but Serious Sam 2 then refuses to recognize it. I know this is more of a niche problem compared to most of what gets posted here, but I'd really really really appreciate if some more experienced members could help out here! I would love to learn what the issue is and maybe how makefiles in general work. My experience with them is kinda subpar admittedly.

Here's the repo to the current version of my project:

https://github.com/GrouganDev/Another-SS2-Redo-DLL


r/cpp_questions • • 1d ago

OPEN What is the difference between ABI and API and what does it mean to say that C++ does not have a stable ABI while apparently C has a simple and stable ABI?

51 Upvotes

Can some simple examples be given to clarify this seemingly complicated topic?

What exactly is at stake in making an ABI stable and simple? Who benefits?


r/cpp_questions • • 23h ago

SOLVED Need help regarding a problem, it shows 'output mismatch' all the time.

4 Upvotes

I was solving this problem and I'm getting an 'output mismatch' in it.

This is a program in C++
I've tried asking chatGPT and Claude for it's solution but nothing is working.

The code is running, there is no compilation error. Only the output is not matching.

How can I correct it?

The problem:

Write a C++ program to create a Distance class with

  • feet and inches as data members
  • member function to input distance
  • member function to output distance
  • member function to add two distance objects

Write a main() function to create objects of Distance class, input two distances and output the sum.

Note:

  • Do use the cout with a newline character to display the output.
  • Write your code in file 2 (AddTwoDistances1.cpp).

The code:

#include <iostream>

using namespace std;

class Distance {

int feet, inches;

public:

void readDistance() {

	`cout << "Enter the distance in feet and inches : ";`

`cin >> feet >> inches;`

`}`

void displayDistance() const {

	`cout << feet << " feet " << inches << " inches" << "\n";`

`}`

void addDistances(Distance d1, Distance d2) {

	`feet = d1.feet + d2.feet;`

	`inches = d1.inches + d2.inches;`

	`feet += inches / 12;`

	`inches %= 12;`

`}`

};

The error:

Output mismatch
Expected outputActual output
Enter·the·distance·in·feet·and·inches·:·5 11Enter·the·distance·in·feet·and·inches·:·5 11
Enter·the·distance·in·feet·and·inches·:·6 12Enter·the·distance·in·feet·and·inches·:·6 12
The·first·distance·:·5·feet·11·inches·⏎The·first·distance·:·5·feet·11·inches_⏎
The·second·distance·:·6·feet·12·inches·⏎The·second·distance·:·6·feet·12·inches_⏎
Total·distance·:·12·feet·11·inches·⏎Total·distance·:·12·feet·11·inches_⏎

What do I need to change to correct this code? The code is running properly, it has no compilation errors.

This is a question from my college assignment and that website requires same phrasing as the sample test cases, that's why it shows output mismatch, but I'm confused about how to rectify it.


r/cpp_questions • • 16h ago

OPEN Unable to fix C++ output

1 Upvotes
Undefined symbols for architecture arm64:
  "_main", referenced from:
      <initial-undefines>
ld: symbol(s) not found for architecture arm64
clang++: error: linker command failed with exit code 1 (use -v to see invocation)

Hi. I've started learning C++ for Arduino and while practicing, I ran my code and the output is saying its a Clang++ error. I downloaded clang as it was recommended by a tutor on youtube,and it works for mark. Even basic print code wont work. Anyway to solve this?


r/cpp_questions • • 11h ago

OPEN A newbie in programming

0 Upvotes

Indeed am I and how i come to the craft of the programming, and with the next year I do begin a course at the university. In need, would I know how I might speak as a programmer doth, think as a programmer doth, take mine ease as a programmer doth, and so forth.

My intent is to conceive a program in my mind and bring it forth, and thus to press ever onward, outrunning the tutorials, and to feel within me that I do truly understand what I program and what I utter when I set down each command.

Moreover, I ought to say that I intend not only to grow for pleasure's sake, but for that I would earn my daily bread by that which pleaseth me or draweth of mine; and with this I likewise ask what manner of programmers or kinds of programming are out there, and how do i might become such one. Nighty night.


r/cpp_questions • • 18h ago

OPEN Help getting external libraries working

1 Upvotes

I'm decently inexperienced with C++ (Only did one class using the language during school, and we used std for everything). I'm not actually sure everything I need to do to get an external library working for my project.

I'm using CLion IDE, most of my settings are still untouched, and I'm trying to get CImg (with libpng) I researched the topic online, but I didn't quite figure out how to get it working... in part, because I'm not sure which part of libpng I'm supposed to use.

I usually prefer to recreate all my functions from scratch, but I couldn't really do that for images, especially if I wanted access to .png files. I'm not picky about using Cimg, I really just need something that can display, rotate, resize, and edit images together (like putting a character on a background).

I backed up my code to github, and made a public branch. If you wanna tear apart an amatuer's code, there's probably a lot to laugh at in here, but I might learn something from people pointing out all the mistakes.
https://github.com/Viteris/Jivelthresh


r/cpp_questions • • 22h ago

OPEN C++ IntelliSense and autocomplete are not working in VS Code Jupyter Notebooks with xeus-cling

0 Upvotes

Hi everyone,

I'm trying to set up an interactive C++ programming environment in VS Code using Jupyter Notebooks and the xeus-cling kernel. The main reason for choosing xeus-cling was its ability to execute C++ code interactively, with variables, structures, and functions persisting across cells without requiring a main() function.

For the setup, I installed xeus-cling in a separate Conda environment managed by Miniforge3, running inside Ubuntu on WSL2. I have connected VS Code to WSL and installed the necessary C/C++ and Jupyter extensions. I have also configured the GCC/G++ compiler correctly inside WSL.

IntelliSense works perfectly in standalone .c and .cpp files. However, the same functionality does not seem to work in Jupyter Notebook (.ipynb) cells. I'm particularly having trouble with tab completion, rich function signature and snippet suggestions, predefined namespace and standard library function suggestions, and suggestions for variables declared in previous cells.

For example, typing std::vec does not suggest std::vector, and pressing Tab does not provide the expected C++ completions. I have enabled Jupyter kernel completions and tried changing the relevant VS Code settings, but the problem persists. Interestingly, basic suggestions such as #include Snippets and some previously typed identifiers appear in JupyterLab, but I haven't been able to get proper C++ kernel-based completion to work. The C++17 kernel itself works correctly, and I can execute code that uses variables and functions that persist across cells.

Has anyone encountered a similar issue when using xeus-cling with VS Code Jupyter Notebooks? Is there a way to enable proper C++ IntelliSense, kernel-based autocomplete, function signatures, and namespace suggestions inside notebook cells?

I'd appreciate any suggestions, workarounds, extensions, or configuration changes that could improve the C++ notebook editing experience.

Thanks in advance!


r/cpp_questions • • 2d ago

OPEN Learn cpp coming from 9 years of C# and OOP

16 Upvotes

Hello everybody,

I worked 9 years with Unity, C#, OOP and game development, and I'd like to learn cpp for some reasons:

  • Fun and curiosity about the language.
  • To be able to work with Unreal and custom Game Engines.
  • I'd like to learn something about graphics programming.

I feel pretty confident in my OOP and programming knowledge, although I don't know much about "low level" programming.

I'm trying to learn from learncpp.com, but I'm finding it a bit boring, because it is a wonderful manual, going into every little detail of not only cpp but also about programming, but I feel that I already know 90% of what is written in the first chapters I'm reading (currently at 7), because little content is about actual cpp concept, and the rest is programming tips, some of them very obvious to me.

Also, I'd like to write something while learning, because it helps me fix things in mind and also have some fun while learning.

To do something in-between, I'm trying to both read learncpp.com and develop Ray Tracing in One Weekend, adapting the code in ways I learned from learncpp.com, and searching the parts I don't understand.

It is fun, but I also fear that not studying the language in-depth and knowing it in every detail will make me miss something and program in a bad way.

So I have some questions:

  • Is learncpp.com considered a good resource for more "senior" developers, or are there other sources that go more straight to the point?
  • If the learncpp.com approach is good, would you suggest studying it all and only then start programming? Or would you suggest a mixed approach of studying and programming?
  • Do you have other approaches to suggest?

Thank you in advance and have a nice day!


r/cpp_questions • • 2d ago

OPEN any web cpp ide for a beginner

0 Upvotes

so i started learning cpp from learn cpp ive completed the 0 chapter and did the setup of visual studio......and im going to not have my laptop for 15days for some reason ,,,,,so im thinking of connecting my keyboard to mobile and learn.....so recommend me some good web ide ....


r/cpp_questions • • 2d ago

OPEN How can I learn cpp properly (I more likely want books)

1 Upvotes

hey guys, i'm pretty new to c++ and honestly i cant find good resources. how can i learn c++ and more importantly i dont have much access to a pc right now. so is it worth buying a book for c++? if i buy one is there a good book that will take me from the start all the way through? id appreciate any info. like a book that explains the basics and everything, ideally simple english, if not simple english thats fine too. also if there happens to be a turkish translation that would be really nice, if not its whatever. thanks


r/cpp_questions • • 2d ago

OPEN C++ Messy Coursework, Need Guidance

3 Upvotes

Hey everyone!

I'm a first-semester BS Data Science student, currently studying Programming Fundamentals in C++.

Our professor initially focused on programming logic and fundamentals, covering topics up to loops, functions, user-defined data types (UDTs), 2D arrays, etc. Things were making sense until we moved towards deeper concepts like memory representation and manipulation.

Along the way, we also covered the Turtle library for logic building, C-style strings, and an introduction to OOP, even though pointers haven't been introduced yet.

I'm now struggling to prioritize what actually matters and would appreciate guidance on three things:

  1. Prerequisites before OOP: Which topics should I properly master before starting OOP? What is essential, and what can wait until later?
  2. Topic prioritization: Is it normal to find deeper concepts like memory representation and manipulation overwhelming at this stage? How deeply should I study these topics as a beginner, and which ones can I temporarily skip without compromising my fundamentals?
  3. Paper coding: I performed poorly in my midterms, particularly because I struggle to write code on paper. What are some effective ways to improve my dry-running, tracing, and problem-solving skills without relying too much on an IDE?

I'd really appreciate practical advice, especially from people who have been through their first semester of CS or a similar computing degree.

Thanks!


r/cpp_questions • • 3d ago

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

26 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 • • 2d ago

OPEN looking for quick upskill projects that are not game focused

3 Upvotes

Hey guys,

I am a long time unreal c++ programmer (7years) but other than college, I haven't done a lot of c++ outside of unreal other than stumbling and giving up on creating a game engine in OGL a few times. i want to broaden my horizons out side of the typical "make a game" format. I have been researching for about a month, and i cant seem to find something that tickles my fancy.

are there any project that you guys could suggest that have a tut attached to them?

I'm looking to get my feet wet with:

  • ai/ml
  • hardware utilization/ advanced memory management
  • more specific features in 14/17/20
  • graphics

I have a lot of respect for this sub and I have been going back and forth about posting here due to what i call "stack overflow syndrome". so hopefully i don't get killed in the comments lol

i just want to be able to do more than unreal

thanks in advanced


r/cpp_questions • • 3d ago

OPEN Is sub-100ns latency realistic for a complete L3 matching engine?

7 Upvotes

I'm currently working in MFT on the C++ backend side and have been exploring ways to bring order book processing latency down to the nanosecond range.

I'm curious whether it's realistically possible to achieve sub-100ns (0.1µs) latency for a complete L3 order book with DPDK, kernel bypassing, cache-aware data structures and high-performance hardware.

By complete, I mean packet reception, parsing, order validation, price-time priority matching, partial/full fills, order book updates and execution report transmission. Not just benchmarking an isolated insertion, cancellation or lookup.

I understand that DPDK removes much of the kernel overhead, but PCIe, DMA, cache misses and memory access latency are still unavoidable.

A few things I'm curious about:

  • What's the practical lower bound for a CPU-based L3 matching engine?
  • Is sub-100ns achievable for the matching core alone under realistic workloads?
  • How close can we get to 100ns wire-to-wire with high-end hardware?
  • At what point does moving to an FPGA become necessary?
  • What architectural approaches would you consider beyond kernel bypassing and memory optimization?

I'm also interested in tail latency (p99/p99.9), rather than just impressive median numbers from synthetic benchmarks.

Would love to hear from people who've worked on exchange infrastructure or low-latency trading systems. Not looking for proprietary details, just trying to understand the practical engineering limits and what approaches are worth exploring.


r/cpp_questions • • 2d ago

OPEN I understand c++ syntaxes, but I still can't code

0 Upvotes

I've watched multiple yt tutorials on coding in c++, and for the syntaxes I understand it; I understand things like variables, pointers, header files, syntaxes like cin and cout.

However, I still struggle to know how to code in general. I wanted to code a game on snake, yes the one many used to play on a nokia, but I find myself confused and unfamiliar with what to write.

I don't want to use AI, not even for helping me. So can someone explain to me how you dealt with the issue


r/cpp_questions • • 3d ago

OPEN Starting C++ with a little programming background.

18 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 • • 3d ago

OPEN i'm having trouble with MSVC modules and static initialisation

0 Upvotes

UPDATE: I managed to narrow down code. Updated post body.

AFAIK, non-local variables exported from a module should be initialised before consumer of said module runs it's code; it was done to eliminate the notorious static initialization order fiasco. However, it doesn't seem to work in my project and I wonder if it's MSVC bug or there's something I'm missing:

// paths.cppm
export module paths;

import std;

export namespace paths
{
        const std::filesystem::path root_dir = []() {
                return std::filesystem::path(L"readme");
        }();
}
--------------------
// fileloader.cpp
export module fileloader;

import paths;
//import std; // reachable through paths?

export namespace fileloader
{

};

// this runs before paths::root_dir static initialiser!
static const bool init_files = []() { 
        for (const auto& entry : std::filesystem::directory_iterator(paths::root_dir)) {
                ;
        }

        return true;
}();

r/cpp_questions • • 4d ago

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

2 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 • • 3d 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 • • 3d 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 • • 5d ago

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

18 Upvotes

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


r/cpp_questions • • 4d 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).