/r/Cplusplus

Photograph via snooOG

C++ is a high-level, general-purpose programming language first released in 1985. Modern C++ has object-oriented, generic, and functional features, in addition to facilities for low-level memory manipulation.

Welcome to r/CPlusPlus

C++ is a high-level, general-purpose programming language first released in 1985. Modern C++ has object-oriented, generic, and functional features, in addition to facilities for low-level memory manipulation.

 

Rules:

Rule 1 - Don't Be A Nuisance

  • Treat others as you would like others to treat you.

  • Participate in good faith, be respectful, and do not insult others.

  • Remember, there is a person on the other side.

  • If you're being toxic or just here to cause trouble, you will be removed from the community.

 

Rule 2 - Content & Quality

  • This sub is for discussions around the C++ programming language. All posts must be in some way related to C++.

  • Comments on posts need to stay on topic and not attempt to threadjack.

  • No low-effort, spam, or advertisement/selling posts or comments.

  • No NSFW Content.

  • No misinformation.

  • Follow Reddiquette.

 

Rule 3 - Good Faith Help Requests & Homework

  • When posting a question or homework help request, you must explain your good faith efforts to resolve the problem or complete the assignment on your own. Low-effort questions will be removed.

  • Members of this subreddit are happy to help give you a nudge in the right direction. However, we will not do your homework for you, make apps for you, etc.

  • Homework help posts must be flaired with Homework.

 

Credits:

Upvote/Downvote Icons: u/Avereniect

Background: u/Robo-Guardian

/r/Cplusplus

43,012 Subscribers

9

Runtime Polymorphism and Virtual Tables in C++: A Beginner-Friendly Brea...

0 Comments
2024/12/20
18:13 UTC

1

Set of user-defined class

I have a class and I want to create a set of class like below:
My understanding is that operator< will take care of ordering the instance of Stage and operator== will take care of deciding whether two stages are equal or not while inserting a stage in the set.
But then below code should work.

struct Stage final {

std::set<std::string> programs;

size_t size() const { return programs.size(); }

bool operator<(const P2pStage &other) const { return size() < other.size(); }

bool operator==(const P2pStage &other) const { return programs == other.p2pPrograms; }

};

Stage st1{.programs = {"P1","P2"}};

Stage st2{.programs = {"P3","P4"}};

std::set<Stage> stages{};

stages.insert(st1);

stages.insert(st2);

ASSERT_EQ(stages.size(), 2); // this is failing. It is not inserting st2 in stages

2 Comments
2024/12/20
12:04 UTC

3

Is anyone using scpptool?

This is an interesting project

duneroadrunner/scpptool: scpptool is a command line tool to help enforce a memory and data race safe subset of C++.

It's funny how C++ beats Rust without even trying.

2 Comments
2024/12/15
02:19 UTC

2

Process getting killed when writing out to .csv file

I have a script that performs Bayesian analysis(about 175k) iterations & writes out the results to 3 .csv files. After running the analysis & when it is about to write the results to the 3 files the process is getting killed. I tested for memory leaks on 100 iterations using valgrind & no issues were detected & I got 3 .csv files as output.

How do I pinpoint the issue that is getting the process killed with 175k iterations?

3 Comments
2024/12/14
22:51 UTC

2

(OPEN SOURCE) Release v1.0.4 -- Beldum Package Manager && C++ Backend Webserver

Hello Developers!

We're thrilled to announce the release of Beldum Package Manager v1.0.4! 🎉

This version introduces exciting new features, including support for the MySQL package, making it easier than ever for developers to experiment with C++ libraries like mysql/mysql.h. Whether you're new to backend development or a seasoned pro, Beldum provides a streamlined approach to managing packages and dependencies for your projects.

In particular, Beldum pairs perfectly with backend webserver development in C++. For those diving into webserver creation, we've also got you covered with our C++ Webserver, designed to showcase how powerful C++ can be in handling backend infrastructure.

Ideal for WSL and Linux Infrastructure
Beldum truly shines when used in WSL (Windows Subsystem for Linux) or Linux environments, providing a smooth and reliable experience for developers who want to build and test their applications in robust development infrastructures.

What’s New in v1.0.4?

  • MySQL Package Integration: Simplified setup for testing and using mysql/mysql.h in your C++ projects.
  • Raspberry Pi Pico Development: Included pico-sdk for those interested in practicing low level integrations.
  • Open XLSX Data Development: Easily test data science techniques and data manipulation with the Open XLSX library which is now included in the Beldum Package Manager.
  • C++ Backend Webserver Tools: Seamless support for backend projects when paired with the C++ Webserver.
  • Improved Compatibility: Enhanced performance and smoother operations on Linux and WSL setups.

Get Started Today!

Whether you’re testing new libraries or developing robust backend solutions, Beldum Package Manager is here to make your workflow smoother.

Try it out and let us know what you think! Feedback and contributions are always welcome. Let’s build something amazing together.

As always, feel free to reach out to the development team for any questions you may have to get started with C++ using the Beldum Package Manager

Happy Coding!

VikingOfValhalla

1 Comment
2024/12/14
22:41 UTC

6

Standard practice for header files?

Hi.

As many other posters here I'm new to the language. I'm taking a university class and have a project coming up. We've gone over OOP and it's a requirement for the project. But I'm starting to feel like my main.ccp is too high level and all of the code is in the header file and source files. Is there a standard practice or way of thinking to apply when considering creating another class and header file or just writing it in main?

9 Comments
2024/12/12
17:12 UTC

7

Methodology when installing an existing project

Hello everyone,

I started a job a few weeks back and my mission is to develop additional tools for an existing project

The thing is... I kind of know how to develop in c or c++ but as long as I remember I've never known how to make an existing project work on a computer.

I don't have any methodology, I don't really know where to start, i'm just progressing almost blindfolded, it's painful, I'm hardly making any steps

I've seen this matter is always difficult to manage. And I've seen people talking about cmake, but I don't see any mention of that in the project I'm working on

Could someone please help me figure it out ? What are the steps ?

10 Comments
2024/12/10
18:53 UTC

17

New with C++

So Im new in C++, I know the basics of the language including some of the oops concepts. and some data structures thanks to my uni... So, I have been trying to build some small games with C++ with tutorials as to learn the language more while making some projects along the way..

While watching the tutorials there are some moments when I literally dont understand what did the person do and how did he made the particular logic work, even tho I eventually figure out and understand the logic...but these kinds of moments really makes me feel dumb

So my question is should I continue making these small projects or is there any better way to learn C++?

9 Comments
2024/12/08
12:40 UTC

3

Using an IDE to learn C++

8 Comments
2024/12/07
23:46 UTC

19

No more C++ courses next semester but I want to dig deeper because I love the language. Where do I go from here?

Hey all! I’m a freshman in electrical engineering (EE) and have just finished up the first and only computer science course required for my major (CS 135/Computer Science I). We covered everything up to the basics of OOP and I was wondering if I could get some advice on where to go from here? I’m very interested in programming and would love to learn about things like operating systems and 3d computer graphics. Are there any resources out there that could possibly help me? Any advice/guidance is much appreciated 🙏

7 Comments
2024/12/06
20:15 UTC

2

UB with Static Inline variables

I'm confused about how static inline variables work when their type matches the type currently being defined. For example:

struct Vector2 {
    int x, y;

    // this fails to compile 
    static inline const Vector2 ZERO = Vector2{0, 0};

    // this is fine, is defined in a source file
    static const Vector2 ZERO_noInline;
};

The reason the static inline line fails makes sense to me. The compiler doesn't have enough information about the type to construct it. That's just a guess though. I can't find anything online that says this isn't allowed.

However, defining this variable inline is nice if it's a class template. You might be surprised that this DOES compile on clang and gcc, but not MSVC:

template <typename T>
struct Vector2 {
    T x;
    T y;

    // compiles on clang and gcc, not MSVC
    inline static const Vector2<T> Zero{0,0};
};

int main() {
    std::cout << Vector2<int>::Zero.x << std::endl;
}

So my main question is: it compiles, but is it UB?

3 Comments
2024/12/06
16:27 UTC

8

Learning c++

Hi, I'm sort of new to c++, I'm just looking for a tutorial that give assignments to the beginner/intermediate level.

Thank you.

8 Comments
2024/12/05
22:55 UTC

1

Creating a vector of arrays, a good idea?

I'm currently working on a program in which I need to store order pairs, (x, y) positions, I would normally use a 2d array for this but this time I want to be able to grow the container. So I made a 2d vector, but when I was writing a function to insert new pairs, I realized that I didn't want the 2nd vector dimension to be able to grow. So I had the crazy idea of creating a vector of arrays. To my surprise it's possible to do, and seems to work the way I want, but I got to thinking about how memory is allocated.

Since vectors are dynamic and heap allocated, and array static on the stack. It doesn't seem like this is best way or safest way to write this code. how does allocation for the array even work if my vector needs to allocate more memory?

Here some example code. (I know my code takes up tons of lines, but it's easier for me to read, and visualize the data)

int main()

{

std::vector< std::vector<int> > vec2

{

{22, 24},

{32, 34},

{42, 44},

{52, 54},

{62, 64}

};

std::cout << "vec2: A Vector Of Vector \n\n";

std::cout << "Vec2: Before \n";

for ( auto& row : vec2 )

{

for ( auto& col : row )

{

std::cout << col << ' ';

}

std::cout << '\n';

}

std::cout << '\n';

vec2.insert( vec2.begin(), { 500, 900 } ); // inserts new row at index 0

vec2.at( 1 ).insert( vec2.at( 1 ).begin(), { 100, 200 } ); // insert new values to row starting at index 0

vec2.at( 2 ).insert( vec2.at( 2 ).begin() + 1, { 111, 222 } ); // insert new values to row at 1st, and 2nd index

std::cout << "Vec2: After \n";

for ( auto& row : vec2 )

{

for ( auto& col : row )

{

std::cout << col << ' ';

}

std::cout << '\n';

}

std::cout << "\nI do not want my colums to grow or strink, like above \n";

std::cout << "-------------------------------------------------- \n\n";

std::vector<std::array<int, 2>> vecArray

{

{ 0, 1},

{ 2, 3},

{ 4, 5},

{ 6, 7}

};

std::cout << "vecArray: A Vector Of Arrays \n";

std::cout << "vecArray Before \n";

for ( auto& row: vecArray )

{

for ( auto& col : row )

{

std::cout << col << ' ';

}

std::cout << '\n';

}

vecArray.insert( vecArray.begin() + 1, { 500, 900 } ); // inserts new row

for ( auto& row : vecArray )

{

for ( auto& col : row )

{

std::cout << col << ' ';

}

std::cout << '\n';

}

std::cout << "\n\n";

system( "pause" );

return 0;

}

8 Comments
2024/12/04
18:23 UTC

2

How to make a template function accept callables with different argument counts?

I have the following code in C++:

struct Foo
{
    template <typename F>
    void TickUntil(F&& Condition)
    {
        const int StartCnt = TickCnt;
        do
        {
            // something
            TickCnt++;
        } while (Condition(StartCnt, TickCnt));
    }    
    int TickCnt = 0;
};

///////
Foo f;
//f.TickUntil([](int Current){ return Current < 5; });
f.TickUntil([](int Start, int Current){ return Start + 5 > Current; });
    
std::cout << "Tick " << f.TickCnt << std::endl;

As you can see, the line //f.TickUntil([](int Current){ return Current < 5; }); is commented out. I want to modify the TickUntil method so it can accept functions with a different number of arguments. How can I achieve that?

16 Comments
2024/12/04
09:38 UTC

3

Should I use std::launder in these cases?

I was reading this post about std::launder and wondered if I should use it in either of these functions.

inline int udpServer (::uint16_t port){
  int s=::socket(AF_INET,SOCK_DGRAM,0);
  ::sockaddr_in sa{AF_INET,::htons(port),{},{}};
  if(0==::bind(s,reinterpret_cast<::sockaddr*>(&sa),sizeof sa))return s;
  raise("udpServer",preserveError(s));
}

auto setsockWrapper (sockType s,int opt,auto t){
  return ::setsockopt(s,SOL_SOCKET,opt,reinterpret_cast<char*>(&t),sizeof t);
}

When I added it to the first function, around the reinterpret_cast, there wasn't any change in the compiled output on Linux/g++14.2. Thanks.

9 Comments
2024/12/02
01:39 UTC

10

What should I expect before starting learning C++ ?

I am a little bit familiar with C and Java, worked with Python and R, what should I expect before starting c++ ? any advice is welcome.

33 Comments
2024/12/01
22:56 UTC

4

Need help populating a struct array from a file using .h and a .cpp other than main.

Hey, I am a Freshman level CS student and were using C++. I have a problem with not being able to populate a struct array fully from a .txt file. I have it opening in main, calling the .cpp that uses the .h but something about my syntax isnt right. I have it operating to a point where it will grab most of the first line of the file but nothing else. I have been trying things for about 4 hours and unfortunately my tutor isnt around for the holiday. I have tried using iterating loops, getline, strcpy, everything I can think of. I need some help getting it to read so i can go on to the next part of my assignment, but I am firmly stuck and feel like Ive been beating my head against my keyboard for hours. ANY help would be greatly appreciated. I can post the .cpp's .h and .txt if anyone feels like helping me out. Thank you in advance.

https://pastebin.com/eHtAe6qN - MAIN CPP

https://pastebin.com/W632c8kp secondary cpp

https://pastebin.com/rDgz2DG1 .h

https://pastebin.com/qFnnZX5Z .txt

7 Comments
2024/11/29
20:30 UTC

3

Simple symmetric cipher: my way of learning c++

So, I started a small side project to learn C++ and improve my understanding. I am creating a symmetric cipher with a key of 256! complexity with several rounds of encryption and mutation of the key.

I am trying to be as close to the standard C++ as possible, so there are no external libraries involved (not even for unit testing).

If you are interested in checking it out and giving me some feedback, the repo is available at: https://github.com/chronos-alfa/chronocipher

3 Comments
2024/11/29
12:44 UTC

20

Tracking down my own dumb mistake

This morning I wasted about 25 minutes of my life debugging a bug I caused myself months ago.

When something broke, I reviewed the code I had just written and what I might have inadvertently changed in the process. When everything looked fine, I launched the debugger to review the new code, line by line. As everything appeared to work as expected, I slowly went up the class hierarchy, confirming every value was correct.

In the end, I realised one of the variables in the base class was uninitialised. It still worked as expected for months. Possibly, one of the later changes coincidentally changed the initial state of that memory space. That's what we call Undefined Behaviour (UB).

Mind you, I've been using C++ since 1995 🤦🏻

11 Comments
2024/11/28
07:37 UTC

0

What kind of laptop could I purchase

Im starting college in a couple weeks and I'm taking a program with a decent amount of programming.

My budget is 600$ to 700$ or a little over

My requirements that are provided by my school are 16gb of ram, atleast a half a tb of storage.

And preferably w8th upgradable ram and storage

3 Comments
2024/11/27
23:07 UTC

9

Mutators and accessors of an object from another class

Let’s say I have a class named Person, and in Person I have a member personName of type string. I also have a member function setPersonName.

Let’s say I have a class named Car, and in car I have a member driverOfCar of type Person. (driverOfCar is private, questions related to this further down).

In main, I declare an object myCar of type Car. Is there some way I can call setPersonName for the myCar object? The idea is that I want to name the driverOfCar.

The only way I could think of is if driverOfCar is a public member in Car. Is that something I should consider doing? Is there a better way to achieve utilizing the mutators and accessors of Person from Car? Eventually, I’ll have a ParkingLot class with Car objects. Should I just combine Person and Car?

13 Comments
2024/11/27
15:17 UTC

74

Is this code readable?

31 Comments
2024/11/26
18:30 UTC

3

Interview questions, Control applications

Hi

I have some experience developing control applications on platforms like STM32, mainly has been motor control, some I/O manipulations and comm protocols I have an interview with a company that makes power transformers using power electronics, they emphasized alot on c/c++ so if anyone can give me some examples and guidance of control related applications development in c/c++ Thanks all

1 Comment
2024/11/25
22:00 UTC

3

What should I do to start learning about 3D game engines or graphics engines?

I want to learn about this topic because I want to expand my knowledge. I've been working as a backend developer, and I want to explore other, more complex areas of programming. I don't think I'll create the next Unity—that's not my goal. I simply want to learn and build something useful, like an aerodynamic simulator or something similar. Could you recommend any books, tutorials, videos, or other resources that would help me get started on this topic?

I would be incredibly thankful if someone with expertise in this area could provide me with a roadmap to guide me from zero to as close to expert level as possible

8 Comments
2024/11/25
19:13 UTC

10

LEARNING C++

So, i basically just started college, and wanted to learn DSA and C++ for college.. I basically planned to watch this 6hr tutorial by Bro Code and then improve upon it by practicing more and more.. Is it a good approach or should i do something else... Any suggestions about resources or any book suggestions would be very helpful... I also know basic python.

12 Comments
2024/11/25
14:58 UTC

1

Can I include apple frameworks into a C++ project without xcode using G++ compiler? If so how?

You can do it in xcode, but I want to do it without xcode.

I don't know if they are static or dynamic, and I don't know the difference so ELI5.

The program I need to make is very simple, which is why I think even with my shockingly limited knowledge I can pull it off.

0 Comments
2024/11/22
06:38 UTC

9

A good order to read learncpp chapters?

I'm learning c++ through learncpp.com and I know that all of these subjects are important but do I really need to go through each chapter right now? I just want to learn the basics of c++ like functions, data types, conditional statements, or stuff like that, and how to use it. Then use what I know to go straight into making small beginner projects, then read and trying to understand others codes then learn more as I go on . So could anybody recommend a guideline for the basics for learncpp.com? If the best way is to go through each chapter I'll just stick to that ig.

Granted I am currently about halfway through chapter 1 still but I just want to know more of the main things

3 Comments
2024/11/21
06:45 UTC

1

How to best set up intellense for C++ in Vscode?

As you know in Vscode with Python, we can create an virtual environment and choose this environment, the intellense works well.

But with C++, I need to use json files and manually add each .header files for intellense working. It is too tedious and not effective, especially in the case with many header files.

Could you share how do you config for intellense in Vscode?

1 Comment
2024/11/19
17:28 UTC

Back To Top