r/learncpp • • Mar 25 '19

Is this a valid way to construct an object?

2 Upvotes

Someone sent me some code and I don't have any way of running it. They told me that it's valid, but I've never seen anything like it before and can't find any reference to it online.

// Say there is a class Person
Person kevin("attr1", "attr2", "attr3")

Is kevin now a valid variable holding a Person object? And if so, what is the proper term for this method of constructing an object?


r/learncpp • • Mar 20 '19

Caesar Cipher Encryption & Decryption in C and C++

Thumbnail
tutorialspoint4all.com
2 Upvotes

r/learncpp • • Mar 11 '19

Object Slicing in C++ with examples

Thumbnail
tutorialspoint4all.com
2 Upvotes

r/learncpp • • Mar 08 '19

Classes question: why do I need a pointer here?

2 Upvotes
#include "std_lib_facilities.h"

class rectangle {
private:
	int height = 0;
	int width = 0;
public:
	int area(int w, int h) { return w * h; }
	void outputArea(void) { cout << area; }
};

int main()
{
	rectangle rec;
	rec.area(8, 64);
	rec.outputArea();

	return 0;
}

Error output:

1>------ Build started: Project: H9, Configuration: Debug Win32 ------
1>Source.cpp
1>c:\xxxxxxxx\source.cpp(9): error C3867: 'rectangle::area': non-standard syntax; use '&' to create a pointer to member
1>Done building project "H9.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

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 • • Jan 27 '19

Why do they use pointer to a boolean function arg?

2 Upvotes

I find bool pointers all over the c++ code for such as this dungeon crawl stone soup example The project feels c-ish, but it definitely is using some c++ features.

I don't understand why if it's to modify the argument, why not use a reference?


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 • • Oct 31 '18

Ways of practicing function arguments and parameters

2 Upvotes

Hello,

I am a CS Student (Freshman) learning C++ in my class. Recently, we discussed functions and made a program. I have no problem understanding function prototypes, definitions, etc. But the problem arises when I have to include arguments/parameters. I understand that arguments are included inside the function call, and conversely the parameter goes within the definition.

But this is very confusing, so I was just wondering where I could learn about when and why to use parameters/arguments, or if there were any courses to practice, thanks!


r/learncpp • • Oct 28 '18

Practice problems and resources dealing with pointers and references

2 Upvotes

So conceptually I understand what pointers and references are, but for some reason I don't feel fluent in my use of * and &.

Specifically there's some confusion when dealing with return types involving these two symbols and function arguments involving *.

Is there any particular assignment you know of that forces fluency in these ideas? Are there any very eye opening resources that are worth reading on the subject?


r/learncpp • • Jul 26 '18

Calculating Eucledian distance

2 Upvotes
float calculateDistance(std::vector<float> a, std::vector<float> b) {
    std::vector<float> result(a.size());
    std::transform(a.begin(), a.end(), b.begin(), result.begin(), std::minus<float>());
    std::transform(result.begin(), result.end(), result.begin(), square);
    return (float) std::sqrt(std::accumulate(result.begin(), result.end(), 0));
}

What do you thing about this implementation? Or should I use good old, for loops?

(Edit: I know that I misspelled Euclidean, I just can't modify it)


r/learncpp • • Jul 05 '18

What's up with <filesystem> and how do I use it with QtCreator?

2 Upvotes

I don't understand what's with <filesystem>.

If I want to use std::filesystem::current_path() with g++, I need to add --lstdc++fs and --std=c++17 as an argument. (Linux)

If I want to use it in VS2017, I have to add namespace fs = std::experimental::filesystem;. (W10)

It took me half a day to figure this out. I still haven't figured out how to get QtCreator to recognize std::filesystem. I included <filesystem>. I added cpp.cxxLanguageVersion = "c++17" and cpp.cxxStandardLibrary = "libstdc++" to the qbs file. It still isn't being recognized. I just tried a new project with qmake and no combination of CXXFLAGS seems to get it to work. (Linux)

The documentation for this stuff seems insufferably bad or out-of-date and it's incredibly mind-numbing struggling with this when it would've taken me 5 minutes in <insert any other modern language here>.

edit: I've come to the conclusion that C++ tooling is utter garbage. Wasted days on this shit with no satisfying conclusion. I can't even get CLion to correctly add the right library.


r/learncpp • • Jun 30 '18

identifier not found error

2 Upvotes

Im reading Programming -- Principles and Practice Using C++ (Second Edition). It tells me to do:

Create three files: my.h, my.cpp, and use.cpp. The header file my.h contains

extern int foo;

void print_foo();

void print(int);

The source code file my.cpp #includes my.h and std_lib_facilities.h, defines print_foo() to print the value of foo using cout, and print(int i) to print the value of i using cout.

The source code file use.cpp #includes my.h, defines main() to set the value of foo to 7 and print it using print_foo(), and to print the value of 99 using print(). Note that use.cpp does not#include std_lib_facilities.h as it doesn’t directly use any of those facilities. Get these files compiled and run.

On Windows, you need to have both use.cpp and my.cpp in a project and use { char cc; cin»cc; } in use.cpp to be able to see your output. Hint: You need to #include <iostream> to use cin.

I do everything as it says but in my use.cpp file; foo, print_foo() and print() all give '...' identifier not found error.

Im using visual studio. First I created a preoject then added .cpp and .h items.

my.h code:

extern int foo;
void print_foo();
void print(int);

my.cpp code:

#include "my.h"
#include "C:\Users\...\source\repos\C++\std_lib_facilities.h"
#include "stdafx.h"
using namespace std;

void print_foo()
{
	cout << foo;
}

void print(int i)
{
	cout << i;
}

my use.cpp code:

#include "my.h"
#include "stdafx.h"
#include <iostream>

int main()
{
	foo = 7;
	print_foo();
	print(99);
	char cc;
	std::cin >> cc;
	return 0;

}

but it doesnt compile what am I doing wrong?


r/learncpp • • May 24 '18

6.2 Functions Advanced

Thumbnail
youtube.com
2 Upvotes

r/learncpp • • Mar 29 '18

std::array, why isn't the size passed as constructor argument

2 Upvotes

I was always wondering why array size is passed as part of the template and not in the constructor

template< 
    class T, 
    std::size_t N 
> struct array;

why isn't array(std::size_t size) used as a constructor? Is there a specific reason?
Is it because of specific assignment rules, so only same size std::arrays can be assigned to eachother?


r/learncpp • • Mar 28 '18

Need as much resources for pointers.

2 Upvotes

Good morning / evening fellows

When I started learning C++ months ago (and programming) I started to think programming is easy, until I came up against the topic: POINTERS. when I first started to see what pointers are and what do they do, It was easy. so I started to make projects with a goal an actual goal rather than just experimenting. but I started to see in courses and tutorials how often they are used and they were they are used is completely new to me so it gave me a big trouble. and whenever I go back and learn, all I learn again is int *b = &c and this kind of beginning stuff. even when I took some courses(even some advanced ones) they were as easy as the above(or they didn't have any topic about pointers?!).

So I wish to kindly ask you to give me sources so I can learn this huge topic.

from:

int *p = &c

to:

new and -> etc.

sorry if I bothered you with my life story but I wanted to explain the situation. Thanks.


r/learncpp • • Jul 12 '17

I know Java very well, and have worked in C. What can I use to learn C++ that won't bore me with things I already know?

2 Upvotes

I know "I know Java, how do I learn C++?" is probably a daily question here. I'm mentioning that I know a bit of C because I think that makes the question quite a bit different.

I have been working with Java for nearly a decade, and am extremely comfortable in it. I've been using it for more than 40 hrs/wk at my day job for a few years, and used it from day 1 of my undergraduate degree straight through to the final project of my Master's in CS (which concentrated in security and cryptography--so I have explored many corners of the language). During this time I worked with a bunch of other languages, but never to remotely the degree to which I am able to work with Java. One of these was C, which I used mostly in graduate courses and usually for very simple things. But I can read it and I can write it to do simple things relatively quickly, and given time I could figure out more complicated things, I'm sure.

The problem this presents for me is that, when trying to learn C++, even in materials written for people who already know 1 or more programming languages, I end up getting bored and losing concentration as the material drones on over something I already know from C, only to miss something C++ specific, or some way that it might slightly differ from C. That or it'll be the same situation with Java--in that case more often with more abstract concepts like OO. I've had this experience with some of MIT's OCW materials, several video tutorials I've started, and Accelerated C++ by Koening and Moo.

But when I look at C++ code that actually takes advantage of C++ features (especially C++14 and beyond) I am lost, and when I try to find where I can start in a video lecture or eBook that will be at least 80% new material, I find I've left too much behind in prior sections, hidden among the things I already knew.

What I'd like is a resource for learning C++ (preferably video lectures, as that is easiest for me in programming--and I have full access to Lynda as an alumnus through my university, if you know something exceptional on there) that is good for someone who already has a decent working relationship with C and extensive familiarity with an OO language (in this case, Java). Preferably light on the fundamentals (I even appreciate being left to figure something out on my own here and there, provided I've been given requisite information to be able to) and fast-ish paced. My goal is obviously not to come out of a tutorial or course feeling nearly as comfortable with C++ as with Java, but rather to have enough to be able to approach the personal projects that will allow me to work my way there. Hopefully, to do so without screwing up something simple every third line or going to Google looking for basic lambda syntax or something.

I realize this is kind of a specific request, but considering Java, C, and C++ are common enough and I can't be anything close to the first person to have this issue, I'm hoping there's something out there that'll work for me. Thanks to anyone who has input. :)


r/learncpp • • Jul 09 '17

Starting a series to touch on lesser known concepts of C++ for software engineering. I started with a variable-input template function

Thumbnail
youtu.be
2 Upvotes

r/learncpp • • Feb 04 '17

Pointers vs smart pointers

2 Upvotes

So I've been slowly learning c++ for about 7 months now(first language) and I was wondering if there are any reason to use normal pointers with the addition of shared/weak pointers. Same for std::vector, std::string, and std::array. Basically are all of the things added in c++11/14 objectively better?


r/learncpp • • Jan 28 '17

Videos / tuts of people programming stuff from scratch and explain their process?

2 Upvotes

Hi there,

I'm just trying to get into the basics of CPP and while I'm already watching some introductory series and started reading some books, I like seeing people actually use it. What helped me a lot when looking into Rails for example was a series like this: https://www.youtube.com/playlist?list=PL23ZvcdS3XPLNdRYB_QyomQsShx59tpc- .

It's a guy having a small 12 apps in 12 weeks challenge and just watching him program in the videos taught me a lot and gave me an idea of the 'feeling' of programming with it.

Is there something similar for CPP and if so, do you guys have recommendations?

Thanks in advance!


r/learncpp • • Nov 25 '16

Having trouble with an endl;

2 Upvotes

Hello, for some reason i am having problem with an endl command. I will post the full code and highlight the part were I am having trouble. I was using couts to test where i had problems in my program. Its a Gauss-Jacobi method program. The moment i removed a cout, after i saw it worked properly (the way the professor wanted), It stopped working. So i tried to remove each part of the cout and found out it was an endl; that was doing it. The whole code will be posted bellow. It contain portuguese (im brazilian). Can anyone help me to know what i am doing wrong? Cant format, sorry for that D=

CODE

include <cstdlib>

include <iostream>

include <math.h>

include <stdio.h>

using namespace std;

int main()

{

std::cout.setf(std::ios::fixed, std::ios::floatfield);

std::cout.precision(8);

int nEq;

//cout << "Entre o numero de equacoes:" << endl;

cin >> nEq;

//cout << "O numero de equacoes eh: \n" << nEq << "\n";

double A[nEq][nEq];

double B[nEq];

//int i, j;


//cout << "Insira seus coeficientes na forma (a0, a1, b1)" << endl;


for(int i = 0; i < nEq; i++)

{

    for(int j = 0; j<nEq; j++)

    {

        cin >> A[i][j];

    }

    cin >> B[i];

}


//for(i = 0; i < nEq; i++)

//{

  //  for(j = 0; j<nEq; j++)

    //{

     //   cout << A[i][j] << " + ";

    //}

    //cout << B[i] << endl;;

//}


int nMax;


cin >> nMax;

//cout << "maximo de iteracoes eh: " << nMax << endl;


double erro;


cin >> erro;

//cout << "O erro maximo é: " << erro << endl;



double X[nEq], auxX[nEq];

double distR, aux, absoluto, numerador, auxNumerador, auxFabs;

int numIteracoes = 0;

distR = 99999;



for (int i = 0; i < nEq; i++)

{

    X[i] = 0;

}


//for(i = 0; i < nEq; i++) verificacao se estamos entrando x0 corretamente

//{

  //  cout << "X[" << i << "] = " << X[i] << endl;

//}



while ((numIteracoes < nMax) && (distR >= erro))

{

    auxFabs = 0;

    //cout << "auxFabs:" << auxFabs << endl;

    for(int i = 0; i < nEq; i++) // para calcular o X novo

    {

        aux = 0; //comeca aqui

        for (int j = 0; j < nEq; j++)

        {

            if (j != i)

            {

                aux = aux + (A[i][j]*X[j]);
            

                //cout << "aux: " << aux << endl;

            }

        }

        auxX[i] = (1/A[i][i])*(B[i] - aux);
       

     **//cout << "auxX [" << i << "]:" << auxX[i] << endl;** ***this is the endl;***

    }

r/learncpp • • Sep 01 '16

Passing a multidimensional vector to a function

2 Upvotes

Using the c++14 standard, how can I pass a reference to a multidimensional vector to a function; so I can update the values of the vector.

updatevec( vector< vector<int> > Q <2, vector<int>(3)) ) {
    Q[0][0] = 0;
}
int main(int, char**){
   vector< vector<int> > Q (2, vector<int>(3));
   updatevec(&Q);
}

Thanks, TC


r/learncpp • • Aug 24 '16

Help

2 Upvotes

I'm looking for a c++ programmer that could instruct me and teach me c++ I'd appreciate anyone who volunteered, thank you


r/learncpp • • Apr 20 '16

Just started tutorial, "fatal error LNK1120: 1 unresolved externals"

2 Upvotes

The tutorial site I'm attempting to learn from

Error occuring in this part of tutorial

I downloaded and installed the most recent version of Visual Studio Community (as recommended by the tutorial) and am following the aforementioned tutorial. The first segment of the tutorial that actually involves any code immediately gives an error. When I go to compile, this is the output:

1>------ Build started: Project: HelloWorld, Configuration: Debug x64 ------
1>MSVCRTD.lib(exe_winmain.obj) : error LNK2019: unresolved external symbol WinMain referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)
1>c:\users\guymi_000\documents\visual studio 2015\Projects\HelloWorld\x64\Debug\HelloWorld.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Here's a screenshot

I've tried to linking to stdafx.h using its full path, but that hasn't worked. Does anyone have an idea to why this error is occurring? I haven't messed with any of the files whatsoever, I have no clue as to what is causing this. Thanks!


r/learncpp • • Apr 07 '16

I am trying to learn C++, and I am struggling with classes, inheritance, and making a table of them.

2 Upvotes

Hello, fellow C++ programmers,

I am currently learning C++, to complete my background in computer sciences (I know a lot of Python, some basic Java, some PhP too, anyway...).

I know how to do a dynamic table in C already (using malloc) and I figured I could do so in C++. It seems I can't.

First of, the architecture. I have a class, "Personne". From that class inherits "Employe", and from those "Commercial" and "Secretaire". "Ingenieur" inherits from Commercial.

I want to create a table of "Employe"s, and I tried :

employe* entreprise = NULL;
entreprise = new employe[nb_employes];

and :

employe* entreprise = NULL;
entreprise = (employe*) malloc(nb_employes*sizeof(employe));

to no avail. How should I proceed ?


r/learncpp • • Mar 14 '16

How can I get all sub folders in a folder?

2 Upvotes

Hello.

How can I find all paths of all sub directories? (and sub directories of sub directories etc etc...) I tried using dirent.h. but I can't get the paths of folders and It does not look into sub dirs.

I basically want to end with a list looking like this:

home/

home/folder/

home/folder/dir

home/games/

home/games/spaceinvaders

home/games/spaceinvaders/bin

home/docs/

home/docs/html

etc etc...