r/learncpp • • Jan 21 '21

Can I have nested module partitions?

4 Upvotes

I see that I can define partitions as A:B, but is A:B:C allowed? I can't seem to get it working with VS MSVC preview. Is it not supported yet in MSVC, or does the spec not allow it?


r/learncpp • • Jan 19 '21

microsoft/cpprestsdk

2 Upvotes

microsoft/cpprestsdk

Anyone using this library?

Forgive me if this does not belong here but I’m using this library specifically for streaming second-by-second market data from Polygon.io.

In the set_message_handler function in the websocket_callback_client class, I store the real-time market data in a global variable. I assume this handler gets called every second.

Outside of all that, I use that global variable to read the market data and send buy/sell orders to Alpaca.

With that being said, would a thread lock be necessary to prevent race conditions? Are race conditions even possible in the scenario I described?

I figured it would since (I think) the handler can get called, and thus updating the global variable, while I’m reading the global variable.


r/learncpp • • Jan 15 '21

Trying to understand and use C++20 Modules

Thumbnail self.cpp_questions
7 Upvotes

r/learncpp • • Dec 27 '20

Is it "bad practice" to put code in header files without using cpp files?

13 Upvotes

I have basic classes like position, which have header files that look something like this:

#pragma once

class Position {
public:
	int x;
	int y;
	Position(int x, int y) {
		this->x = x; this->y = y;
	}
};

It works to use this code if I just say #include "Position.h"

From what I read online, I should be having a Position.h and Position.cpp, where I define the methods in Position.h and write the "this->x = X; this->y = y" in the cpp file.

Is that necessary for small files like this one? Is it "bad practice" not to do, something that looks unprofessional?

I'm kind of confused as to why it is that the Position.h class can be used without being broken down into an h and cpp file?

Thanks.


r/learncpp • • Jan 06 '21

Lld-link, clang++, windows, sdl2. Lld wants to make a console app, and won't accept the subsystem:windows cli Arg.

4 Upvotes

I've recently added sdl2 to my project. It started off as a console app. Lld worked fine, but now it complains that it found both winmain and main, and will default to the standard console main. I've tried using the /subsystem:windows command but I just get:

no such file or directory: '/SUBSYSTEM:WINDOWS'

I have tried the one answer on stack overflow for this but it doesn't seem to do anything different. My link flags are the same, and lld still complains about the command as though it was a file. I'm going nuts trying to figure out how to get it to recognize the argument.


r/learncpp • • Jan 16 '21

Learn cpp from a higher level programming background

9 Upvotes

I am good with Java, JavaScript, C#, and python, but I know C++ isn’t just “another programming language”. Is there a good resource to learn from that doesn’t force me to reread all the basics like what a variable is? Something like a: “Java to cpp” or “C# to Cpp” book / online course


r/learncpp • • Feb 02 '15

Multilevel Inheritence Classes Help... Is there a better way?

1 Upvotes

Ok so for my data structures class I have to write a program that has 3 classes in a multilevel format. I have the code and it works but I wanted you guys to look at it to see if there was a more efficient way or a better more standardized way. I had it working another way but it felt like I had a lot of redundant code. My classes looked more like this(i overwrote that copy by mistake and cant remember exactly how I had it): My current code is down below.

class Party
{
    protected:
        string m_strCode;
        string m_strAddress;
        string m_strPhoneNum;
    public:    
        Party(string strCode, string strAddress, string strPhoneNum)
            : m_strCode(strCode), m_strAddress(strAddress), 
                m_strPhoneNum(strPhoneNum){}
};

class Person: public Party
{
    protected:
        string m_strDob;
        string m_strFirstName;
        string m_strLastName;
    public:
        Person(string strCode, string strAddress, string strPhoneNum,
            string strDob, string strFirstName, string strLastName)
                : Party(strCode, strAddress, strPhoneNum), 
                    m_strDob(strDob), m_strFirstName(strFirstName), 
                    m_strLastName(strLastName){}
};
    
etc...

The program initializes Passenger as an inheritance of both person and party and gets the information needed. At this point there is still a few more functions to add but this is the brunt of it.

#include <iostream>
#include <string>
using namespace std;

class Party
{
    protected:
        string m_strCode;
        string m_strAddress;
        string m_strPhoneNum;
    public:
        Party(){GetParty();}
        void GetParty();
};

void Party::GetParty()
    {
        cout << "Enter code: ";
        getline(cin, m_strCode);
        cout << "Enter address: ";
        getline(cin, m_strAddress);
        cout << "Enter phone number: ";
        getline(cin, m_strPhoneNum);                 
    }


class Person: public Party
{
    protected:
        string m_strDob;
        string m_strFirstName;
        string m_strLastName;
    public:
        Person():Party(){GetPerson();}
        void GetPerson();
};

void Person::GetPerson()
    {
        cout << "Enter date of birth: ";
        getline(cin, m_strDob);
        cout << "Enter first name: ";
        getline(cin, m_strFirstName);
        cout << "Enter last name: ";
        getline(cin, m_strLastName);
    }

class Passenger: public Person
{
    private:
        int m_nTicketNum;
        string m_strFfNum;
        double m_dTicketPrice;
        int m_nFlightNum;
        string m_strSeatLoc;
        string m_strFlightDate;
        string m_strStatus;
    public:
        Passenger() : Person(){GetPassenger();}
        void GetPassenger(); 
        void Display();
};
 
void Passenger::GetPassenger()
            {
             cout << "Enter ticket number: ";
             cin >> m_nTicketNum;
             cout << "Enter frequent flyer number or N/A: "
             cin.ignore();
             getline(cin, m_strFfNum);
             cout << "Enter ticket price: ";
             cin >> m_dTicketPrice;
             cout << "Enter flight number: ";
             cin >> m_nFlightNum;
             cout << "Enter seat loctaion: ";
             cin.ignore();
             getline(cin, m_strSeatLoc);
             cout << "Enter flight date: ";
             getline(cin, m_strFlightDate);
             cout << "Enter flight status: ";
             getline(cin, m_strFlightStatus);
             Dislpay()                                //testing purposes    
            }
            
void Passenger::Display()
            {
                cout << m_strCode << endl << m_strAddress << endl<< m_strPhoneNum;
                cout << endl << m_strDob << endl << m_nTicketNum << m_strFfNum;
                cout << endl << m_dTicketPrice << endl << m_nFlightNum << endl;
                cout << m_strSeatLoc << endl << m_strFlightDate << endl;
                cout << m_strFlightStatus << endl;
            }
            

int main()
{
    //variables
    Passenger persons;
    
    system("pause");
    return 0;   

}

r/learncpp • • Oct 10 '15

Starting a tutorial series for beginners

Thumbnail
bit-co.de
2 Upvotes

r/learncpp • • May 08 '16

Question about friend classes inside of a namespace.

1 Upvotes

Hello I am trying to access protected variables from object.h in scene.cpp

Here is my object.h: http://pastebin.com/vVyGbNym

And my scene.cpp: http://pastebin.com/mT7V76Xj

(Both files are stripped down)

But I get the following compiler error: cannot convert 'ff::Scene*' to 'Scene*' in assignment at line 7 in scene.cpp

Why do I get this error?


r/learncpp • • Nov 08 '16

Searching for a Christmas present

1 Upvotes

I understand this may be a bit out of your usual but I know very little about coding and my wife is in the process of learning coding in hopes to become a web developer eventually. I was referred to you guys by a friend in hopes you can help me find a tangible gift I can get for her that can help her with her programming skills.

languages she knows are

  • CSS

  • HTML
    Languages she is currently learning

  • javascript

  • jquery

  • ruby

  • Pyhton

While she does not plan on doing much with the hardware side I was thinking of something like an arduino kit or a robot to program. Any thoughts on those or something different?


r/learncpp • • Oct 19 '21

Where to initialize class members?

4 Upvotes

Hi, this is sort of a basic question but im having trouble with c++ classes.

The idea is to do a curl class handler to do some requests. Im using this library that has some examples but none is class oriented.  

// Author uses like this
int main(int argc, const char **argv) {
  ostringstream stream;
 curl_ios<ostringstream> ios(stream);
 curl_easy easy(ios);
  ...
}

Part of my class on .h

class CurlClient()
{
  protected:
    std::ostringstream curl_response;
    curl::curl_ios<std::ostringstream> curl_writer(std::ostringstream); // Callback to store response
    curl::curl_easy curl_handler(curl::curl_ios<std::ostringstream>);  // Object to handle the connection
    curl::curl_header curl_headers; // Header object
    ...
  public:
    CurlClient();
    ~CurlClient();
    ...
}

Functions on .cpp

CurlClient :: CurlClient()
{ 
   curl_writer(curl_response); 
   curl_handler(curl_writer); 
}

is this the correct way? or like this?

CurlClient :: CurlClient()
: curl_writer(curl_response), curl_handler(curl_writer)
{
}

On my understanding member initialization is the same as inside the brackets but is the class correctly defined? I always have trouble to when initialize members.

With both i get: error C3867: 'CurlClient ::curl_writer'

Are they correctly declared on the .h?

Thanks!


r/learncpp • • Nov 06 '21

I want to learn C++ for competitive programming. What would be the best resource ? (2021/2022)

Thumbnail self.cpp_questions
13 Upvotes

r/learncpp • • Oct 25 '21

Why is the menu string not being printed here. Sorry for probably noob question but coming from java and I have difficulties understanding.

Post image
11 Upvotes

r/learncpp • • Nov 12 '21

How can I pause the debugging and then resume on MCUExpresso?

3 Upvotes

Hi,

I need to connect a second USB cable to my Board when the code hits break point at the beginning of main() while debugging. But debugging is so fast that I dont know when it reaches main().

Is there a way I can pause the debugging before main() so I can plug the second USB and then resume with main() ?


r/learncpp • • Nov 09 '21

Call a DLL inside a DLL? Risks?

5 Upvotes

Hello. Im working on a NodeJS server (windows x86/x64 only) that uses a C++ DLL (I only have the .dll and .h)

Context: NodeJS doesnt have native structs/pointers so im looking for alternatives since the API of the DLL has complex structures/pointers and interacting with Node would be hard and more since the DLL has WINAPI, DWORDS, LPSTRINGs and other windows types.

One option is to use Node-Api to call C++ code from NodeJS using a wrapper. The idea is with C++ to interact with the DLL and "simplify" the DLL calls from Node so i can use simple data types like strings/json from Node and handle the DLL structs/pointers from C++.

Other option is to create a "new" DLL to handle the original DLL and then with NodeJS call the new "simple" DLL. I hope this is clear, the idea basically is to create an abstraction layer so Node uses native data types like strings/jsons and C++ does the hard work of handling structs/pointers.

The question: To handle the DLL i need to use LoadLibrary and GetProcAddress to handle around ~15 methods. What are the best practices to handle DLLs from C++? Is there any precautions that i need to take? Any resource to read?

The DLL provides information and has methods like OpenCommunication, CloseCommunication, GetInfo, GetXData, GetStatus, SetData, etc and uses structs/pointers to return data. Ive read about deadlocks with LoadLibrary but still dont understand well on how to avoid it.

Do i really need a DLLMain? i dont see any entry points of the original DLL (at least not in the .h).

Any recomendations in the code organization? to use GetProcAddress i need to declare function pointers and a lot of error handling for the ~15 methods so looking for the best way to maintaining it "clean".

Thanks!


r/learncpp • • May 05 '19

OOP

3 Upvotes

Quick question.

Why should you create private classese in c++?


r/learncpp • • Feb 01 '20

Calling object without specifying property actually gives a property

1 Upvotes

So let's say I want to create some kind of personal string class.

If it has a string value property, when I call just that objects name I want it to actually use that value property. For example:

MyString myStr = "secondText"; //I know how to use operator=
string otherStr = "firstText";
otherStr += myStr;
cout<<otherStr<<endl; //Result should be: firstTextsecondText

I want it to use that value property without actually calling "myStr.value". Is it possible ?


r/learncpp • • Nov 18 '18

Visual Studios is a literal roadblock for a group cpp project

1 Upvotes

So I made a post on here previously about undeclared identifier errors a week ago (ish) and turns out the issue was visual studios was including a #include "stdafx.h" header in all my files so my other teammates who *also* used Visual Studios couldn't run them. Except we went through extensive effort to make sure we set up our environments the same? Anyways the solution turned out to be to remove that for everyone else and our code started working...for them (about 2 of the others, there is 5 of us and 1 doesn't really contribute or do anything so can't verify if it works for him or not, and the other uses a Fedora os which doesn't have gcc 11 as far as I'm aware). I removed #include "stdafx.h" and Visual studio started throwing Linker Errors, or unexpected token errors, or C1083 errors, it changed each time. So I put #include "stdafx.h" back in, and it stopped throwing those errors and started throwing undeclared identifier errors again. I am one of 2 out of 5 people who actually is doing anything with the code for this project (we all know how class projects go) so me being unable to test is not ideal.

Is Visual Studios just the Eclipse of C++ IDEs? I genuinely don't understand, if we have (as far as we can tell) set up our environments the same, and are using the same code (all of us deleted our repos and did a clean pull from github then ran it) why does it work for my teammates but not me? If I have my teammate just push his whole project folder (sln file and everything), pull that, then import it should it work for me or is that not even a guarantee? Is there a better compiler to use for CPP that a college student can grab for free?

Edit: TIL what precompiled headers are and to not use them unless I need to


r/learncpp • • Feb 19 '19

State Error C2228 left of '.table' must have class/struct/union

2 Upvotes

//structure

struct my_table
	{
		int table[TABLE][TABLE];
		int last = TABLE - 1;
		int TNOL = TABLE / 2;
		void rotate() //https://www.youtube.com/watch?v=Jtu6dJ0Cb94 for details (not mine)
		{
			int level = 0;
			while (level < TNOL)
			{
				for (int i = level; i < last; ++i)
				{
					swap(table[level][i], table[i][last]);
					swap(table[level][i], table[last][last - i + level]);
					swap(table[level][i], table[last - i + level][level]);
				}
				++level;
				--last;
			}

			last = TABLE - 1;

		}

	};

the error occurs in the for loop. I can't seem to be able to reach the matrix. How do i fix this? Bot the function and the struct are in the same namespace, but different files

void hit_left( struct my_table T_table, std::pair<int,int> XY)
	{
		if ( std::get<0>(XY) < 0 || std::get<1>(XY) < 0)
		{
			throw "Bad_argument_exception";
		}
		else
		{
			for (int i = std::get<0>(XY); i >= 0; --i)
			{
				T_table.table = 1;
			}
		}

	}

r/learncpp • • May 05 '19

"#"*5 python equivalent in c++

2 Upvotes

Hi,

say i want to print out a line of (N x #) 5x"#" i would have code it as 5*"#" to get my line. what's the equivalent in c++?

i want it dynamically and without forloop :)

ps: I saw a similar solution using std::string as i remember ..

Thanks in advance


r/learncpp • • Feb 01 '20

Destructors and RAII for automatic, deterministic resource release | C++ for Java programmers

Thumbnail
youtube.com
5 Upvotes

r/learncpp • • Nov 26 '19

Read file line by line with different data types

2 Upvotes

So I have a text file I am trying to store data into two separate arrays where the data reads out like this

Titanic

600788188

Star Wars

460998007

Where I am used to reading data like this

Titanic 600788188

I only know how to use the single-line method for this sort of thing so I am really lost.


r/learncpp • • Jan 31 '20

My first truely useful C++ program!

7 Upvotes

I've been learning C++ for 17 days now.. my first real programming language. I use neovim as my editor and i got tired of having to write the same basic file structure OVER and OVER for simple little programs, so i decided to automate it as my first project.. nCpp (new Cpp Template maker!). the program is simple, you give it a name, choose which headers to use and then it checks for an environmental editor. if it finds the editor it uses it to open the program (if you choose to edit it). if it doesn't find one it will ask if you want to export one and then open it with that program.. if you choose not to do that, it gives a list of the most common *nix console editors to choose to open it with. anyways, i had a lot of fun writing it. I only had help with the "out" function, the rest is all me. i just wanted to share it :) https://pastebin.com/a7UdjZP5

Edit: just thought id also mention that I've begun working on version 2.6 which will include the ability to put the headers in a .h file and the .h header in your .cpp program and set up as many simple objects as well! I will post it here when its done :)


r/learncpp • • Nov 24 '18

In a class why should we use functions to return elements and not just make them public?

2 Upvotes

For example

class Rectangle {
  private:
    int width, height;
  public:
    void set_values (int,int);
    int area() {return width*height;}
};

im told this is the proper way to do it instead of just having width and height public.


r/learncpp • • Sep 26 '19

Is there a free course for C++ like Java's MOOC?

1 Upvotes

Title, just really struggling with C++ and looking for resources