Page 1 of 2

Looking for advice with C++ learning

Posted: Wed Aug 14, 2019 2:59 pm
by DarkElvenAngel
Hello everyone,

I want to expand my skills and learn more about C++, I feel that as a C programmer I now have the knowledge to take the step in. I tried many years ago with Visual C++ for Windows and it was overwhelming.

I'm looking for resources that can help I watched a introduction video but found myself fast forwarding through it because it was all things I already know from C.

I'd like to learn more about how the two can be used together and how locate resources if anyone has read any good books particularly related to Linux and the raspberry Pi

Thanks

Re: Looking for advice with C++ learning

Posted: Wed Aug 14, 2019 3:57 pm
by Heater
You are not alone. C++ is overwhelming. Having had to use it quite a lot over the years I've become convinced it is such a huge and complex language that nobody understands all it's features and how they interact with each other.

I hesitate to recommend any books or learning materials, C++ has evolved so much in recent years that the best way to write C++ programs has changed significantly. The books I'm familiar with may lead you in the wrong direction.

Personally I would hesitate to encourage anyone to start down this road. Getting to grips with C++ will take a lot of effort and time after which you will realize what a disaster of a language it is.

Re: Looking for advice with C++ learning

Posted: Wed Aug 14, 2019 8:26 pm
by deepo
I earn a living programming in C++ and I learned (most of) the language at work over many years.
So it's not easy pointing out a specific book to read.
But learning the object oriented programming concepts and then later the C++ specific syntax has helped me, i.e. learning about inheritance between objects and then how to express that in C++ later.

In regards to C in relation to C++ I guess it works for me that way that C++ is used to glue the code together while C is used inside the functions, i.e. for/while loops, switch/case etc.

On top of that comes the standard namespace stuff such as std::string, std::vector etc. Very helpful.
Don't bother with boost until you know about C++.
You need to get the basics down first is my advice.

/Mogens

Re: Looking for advice with C++ learning

Posted: Thu Aug 15, 2019 1:47 am
by DarkElvenAngel
Thanks for the replies,

Heater, I have heard those sentiments before in reference to C++. I'd still like to use the classes and some of the more advanced things C++ has to offer without going crazy.

Deepo, it makes sense it takes years to learn this language even as heater points out the books available don't show the right way of doing things. I actually own Microsoft Visual C++ 1.0 and Visual Studio 6.0 and I have all these wonderful reference books but all of them are dated and not useful. I managed to get by with Visual Basic but those software are also very much out of date.

In the view of a hobbiest not looking to go to deep down the rabbit hole and to learn on a relevant environment (I don't consider windows 95 though XP relevant) would perhaps a book on Arduino's C++ language be of any help? I'm only looking to write for the console, most likely curses and I really like the Raylib library.

I visited my local library and every C++ book is checked out.

Re: Looking for advice with C++ learning

Posted: Thu Aug 15, 2019 3:44 am
by Heater
DarkElvenAngel,
I'd still like to use the classes and some of the more advanced things C++ has to offer without going crazy.
That is a sensible approach to the problem.

Unfortunately for me I found that the complexity of C++ in all it's frightening magnitude seeps in to projects as they grow despite ones efforts to not go crazy. Perhaps it comes in via one using some library that make use more language features. Or perhaps it comes in via some contributor to the project. If you start to use something like the Qt GUI tool kit you suddenly find Qt'ness seeps all over your code. I used to think it was my fault, that I was not good at keeping projects under control, I'm happy to learn in recent years that others have the same problems.
...would perhaps a book on Arduino's C++ language be of any help?
The Arduino environment is a wonderful thing. It is a good example of using C++ but keeping out a lot of complexity for the user. Last time I checked the Arduino documentation it kept to a very small subset of C++ language features, making for a simple environment for the users. I don't think they even mentioned that the language was C++! Of course in the Arduino case one really has to do that because of the small size of the Arduino, there is no way to be allocating memory with "new", or using the standard library and so on.

Unfortunately extreme simplicity means that Arduino books are not really much use if you want to use C++ for desktop applications.

This looks like as good a place to start as any: https://www.learncpp.com/

Here is some good advice: https://www.freecodecamp.org/news/learn ... ece5b0005/

Re: Looking for advice with C++ learning

Posted: Thu Aug 15, 2019 5:57 pm
by DarkElvenAngel
These are useful links thanks I found the comic especially humorous as I work over ssh from my phone and write code in nano. (No really)

Re: Looking for advice with C++ learning

Posted: Fri Aug 16, 2019 7:55 pm
by DarkElvenAngel
Okay so I have read a bunch of these materials and now I'm thinking... If I want to I can ignore some of C++ standard libraries and use the C libraries?

I'm use to using printf and I honestly think that std::cout looks wrong to me (I want to format my strings) I tried this out and did a hello world and it compiled and ran just fine.

Now I am thinking if all I want from C++ are classes and maybe that string class could I just do that? I'm looking on my man pages and there are none for C++ libraries only C how do I know what include headers to use there must be a package missing.


This is my test Hello world code

Code: Select all

#include <iostream>
#include <stdio.h>

int main()
{
  printf("hello world\n");

  return 0;
}
I can just bet all the C++ programmers are cringing at what I've done like I've spawned a demon or something else horrid.

It would be awesome to have the man pages for C++ standard libraries so I can learn them to.

Re: Looking for advice with C++ learning

Posted: Fri Aug 16, 2019 8:11 pm
by deepo
printf is still valid for C++, so you don't need to use std::cout if you don't want to yet.
You can still use the std::string class, also with printf:

Code: Select all

#include <string>
#include <cstdio>

int main()
{
  std::string message = "Hello world!";
  printf("%s\n", message.c_str());

  return 0;
}
I use cplusplus.com when looking up C++ stuff:
http://www.cplusplus.com/reference/cstdio/printf/

/Mogens

Re: Looking for advice with C++ learning

Posted: Fri Aug 16, 2019 8:20 pm
by Heater
Never mind the C++ programmers, they are lost souls.

I see nothing wrong with using a C++ compiler for writing what is mostly C.

The C++ streams io can be useful "cout <<" etc. You can in fact get iostreams to format in all kind of complex ways, more so than printf.

However the last time I tried using cout I gave up with it as it was so slow.

The most useful things from C++ are the String class and Vectors. Perhaps Map
https://en.cppreference.com/w/cpp/header/vector
https://en.cppreference.com/w/cpp/container/map

You gain a lot by using such C++ classes even if you never write a class yourself.

Re: Looking for advice with C++ learning

Posted: Sat Aug 17, 2019 6:08 pm
by pica200
You are doing the right thing. iostreams are hopeless and bloated. Using C++ doesn't mean you have to go full in and use everything it offers. There are many more such pitfalls which may look nice but result in horrible machine code ;) I do the same and mostly write "C with classes".

I think this is a good starting point and it's official: https://isocpp.org/wiki/faq

Re: Looking for advice with C++ learning

Posted: Sun Aug 18, 2019 1:18 am
by swampdog
@DarkElvenAngel
https://en.cppreference.com/

C++ is a horribly complex language. Professors would have you know all of it then argue about the definition of a pointer. However, your printf() is prone to buffer overflow whereas a "cout" is not.

int i
string s
cout<<i<<s
..works in C++ even if you change "int i" to "double i".

C++ has strings. C++ has containers, any of which can hold a string. A vector<string> can hold an entire file and the code is trivial to write. A deque<string> can hold an entire file. You don't have to learn it but the (admittedly complex) STL (standard template library) will allow you to write the same code for both. You can have maps (dictionaries) along the lines of code saying "a["foo"] =7" where "a",["foo"],7 are any datatypes you desire.

The problem is constructors (ctor), destructors (dtor) and copy constructors (cctor). Consider..

struct foo {
int a
char b [13]
void *(ctor)(...)
void *(dtor)(...)
struct foo * (cctor)(...)
}
..for any C struct where ctor,dtor,cctor are function pointers. Whenever "foo" is brought into existence (instantiated in C++ terms) "ctor" is automatically called. When "foo" goes out of scope "dtor" is called. "cctor" exists to make a copy of "foo" for the lifetime "foo" exists.

That's C++ classes. Inheritance, polymorphism, virtual functions etc just extend on that. Most of those terms are irrelevant. Summary:

string
container
exceptions

..the latter for another day.

Re: Looking for advice with C++ learning

Posted: Sun Aug 18, 2019 7:36 am
by Heater
Of all the problems I have had in C/C++ I don't recall any of them being to do with printf. After all printf() generally produces the outout you want so if you get it wrong you notice immediately.

sprinf() and friends, which format strings into buffers, well that is a whole other story...

As much as I love C/C++ they are designed to make accidentally shooting yourself in the head as easy as possible what with silently performing:

Buffer overruns:

Code: Select all

    *buffer = 42;    // Is buffer really pointing at a valid location?
Out of bounds array access:

Code: Select all

    array[index] = 69;  // Is index really in range?
Integer overflows:

Code: Select all

    x = x + 100;    // Are you sure X does not overflow there?
Use before initialization:

Code: Select all

    x = y;          // Did you remember to initialize y?
Use after free():

Code: Select all

    free(myThing);  // Are you sure myThing is not still used elsewhere in your code?
    ...
    ...
    *myThing = 666;  // Elsewhere: Oops, use after free. 
Fall through on switch():

Code: Select all

    switch (x) {
        0: doSometing();
            break;
        1: doSometingElse();    // Oops, forgot a "break;"
        2: doSomeMore();
            break;
    }
Use after reallocation:

Code: Select all

    std::vector<int> v = {10, 20, 30, 40};

    int* p = &v[3];
    std::cout << *p << std::endl;    // OK

    for (int i = 0; i < 10; i++) {
        v.push_back(i);
    }

    std::cout << *p << std::endl;    // Oops, pointer no longer valid (Can you find out why?)
If you want to get into C/C++ be ready to spend a lot of time checking every line of your code carefully for these and and a host of other possible slip ups. And finding the cause of obscure bugs that you create as a result. Get familiar with tools like valgrind and the "sanitizer" tools that come with GCC and Clang.

At the end of the day, printf() will be the least of your worries.

Re: Looking for advice with C++ learning

Posted: Sun Aug 18, 2019 8:36 am
by jahboater
Heater wrote:
Sun Aug 18, 2019 7:36 am
If you want to get into C/C++ be ready to spend a lot of time checking every line of your code carefully for these and and a host of other possible slip ups. And finding the cause of obscure bugs that you create as a result. Get familiar with tools like valgrind and the "sanitizer" tools that come with GCC and Clang.

At the end of the day, printf() will be the least of your worries.
These issues apply to C as well, and the OP is a competent C programmer.
Nothing new in C++ here, except that there are things like smart pointers to help.

Get a book or books that deal with C++17.
However none of them are complete and cover all of the language and the STL.
The only definitive and complete documentation is the language standard itself.

Re: Looking for advice with C++ learning

Posted: Sun Aug 18, 2019 12:08 pm
by pica200
Some of the issues above are caught by the compiler already. -Wall and -Wextra are really helpful. And i have not seen a format string vulnerability in ages so don't worry about printf() ;) This is assuming you don't use a stone age version of gcc which has far worse detection than newer gcc.

You should of course not rely on the compiler but you should not ignore warnings either because they more often than not mean something is wrong with your code.

Re: Looking for advice with C++ learning

Posted: Sun Aug 18, 2019 6:54 pm
by jahboater
pica200 wrote:
Sun Aug 18, 2019 12:08 pm
Some of the issues above are caught by the compiler already. -Wall and -Wextra are really helpful.
I suggest at least:-

Code: Select all

-Wall -Wextra -Wconversion -Wuninitialized -Wcast-qual -Wcast-align -Wundef -Werror -Wfatal-errors
The last two options mean that you cannot finish the compilation until the code is clean, which always saves time in the long run.

Re: Looking for advice with C++ learning

Posted: Sun Aug 18, 2019 7:05 pm
by ProDigit
One of the reasons I bought the Pi, is because of this.
I ended up with Python, as I don't really like working with libraries(especially not with vast ones like C++, although with difficult code languages, using libraries is pretty much a must), but also, Python is a lot easier than C++.
I first learn syntax differences of the new language, before moving on to the advanced stuff.
Of Python there are a lot of youtube video tutorials, as well as lists of commands you can find online and print out (if you want to).
Aside from that, there's some basics you can learn from CodeAcademy, or other free online resources.

C is something I'd like to learn too.

Re: Looking for advice with C++ learning

Posted: Sun Aug 18, 2019 8:20 pm
by Heater
jahboater,
These issues apply to C as well, and the OP is a competent C programmer.
Sorry, I missed the part about being a C programmer.
Nothing new in C++ here, except that there are things like smart pointers to help.
But that is the tragic thing. Nothing new in C++ w.r.t correctness and safety.
I suggest at least:-

Code: Select all

-Wall -Wextra -Wconversion -Wuninitialized -Wcast-qual -Wcast-align -Wundef -Werror -Wfatal-errors
I try not to leave home without them. I need all the warnings I can get!

Unfortunately it is trivially easy to not have those warnings say anything about the issues I raised above.

Code: Select all

$
$ cat junk.cpp
#include <iostream>
#include <vector>
#include <cstring>

int main (int argc, char* argv[]) {

    std::vector<int> v = {argc, 10, 20, 30, 40};

    int* p = &v[3];
    std::cout << *p << std::endl;    // OK

    for (int i = 0; i < 10; i++) {
        v.push_back(i);
    }

    // OOPS, pointer no longer valid (Can you find out why?)
    std::cout << *p << std::endl;

    // OOPS! Out of bounds
    std::cout << argv[40] << std::endl;
    std::cout << argv[0] << std::endl;

    // OOPS! Missing case falls through
    int x = 100;
    switch (x) {
        case 0:
            x++;
            break;
        case 1:
        case 2:
            x++;
            break;
    }
    std::cout << x << std::endl;
    // OOPS! Not all cases covered above.

    char* m = (char*)malloc(16);
    strncpy(m, "Hello", 16);
    free(m);
    // OOPS! Use after free()
    std::cout << m << std::endl;

    char* chars = (char*)malloc(16);

    // OPPS! Use unitialized
    char c = chars[0];
    std::cout << c << std::endl;

    return 0;
}
$
$ g++ -O3 -o junk junk.cpp -Wall -Wextra -Wconversion -Wuninitialized -Wcast-qual -Wcast-align -Wundef -Werror -Wfatal-errors
$
For any non-trivial program it's pretty much impossible to be sure you do not have such mistakes. Enter valgrind, the sanitizers and gdb!

Re: Looking for advice with C++ learning

Posted: Sun Aug 18, 2019 9:56 pm
by jahboater
Heater wrote:
Sun Aug 18, 2019 8:20 pm
// OOPS! Missing case falls through
Works on my Pi!

Code: Select all

try.c: In function ‘parse_escape’:
try.c:2313:9: error: this statement may fall through [-Werror=implicit-fallthrough=]
 2313 |    base = 8;
      |    ~~~~~^~~
compilation terminated due to -Wfatal-errors.
I use /*fallthrough*/ when a break is deliberately missing to avoid that message.
For obvious reasons though, the compiler does not complain about:

case 1: case 2: case 3:

Re: Looking for advice with C++ learning

Posted: Sun Aug 18, 2019 10:08 pm
by Heater
The code I presented above has no complaints at all when compiled on my Pi:

Code: Select all

pi@pi3-buster-1:~ $ g++ -O3 -o junk junk.cpp -Wall -Wextra -Wconversion -Wuninitialized -Wcast-qual -Wcast-align -Wundef -Werror -Wfatal-errors
pi@pi3-buster-1:~ $
The idea that stuff in the comments changes ones compiler output is nuts of course. It became such common practice that compiler writers wedged in in there.

Re: Looking for advice with C++ learning

Posted: Sun Aug 18, 2019 10:15 pm
by jahboater
Heater wrote:
Sun Aug 18, 2019 10:08 pm
The code I presented above has no complaints at all when compiled on my Pi:
No, as I said
case 1: case 2: case 4: case 4:
will not elicit a complaint because there is no code.
Stuff like this will:

Code: Select all

  {
    case '0'...'7':
      --p;
      base = 8;
    case 'x':
      start = p;
and this does read quite nicely IMHO

Code: Select all

  {
    case '0'...'7':
      --p;
      base = 8;
      /*fallthrough*/
    case 'x':
      start = p;
Heater wrote:
Sun Aug 18, 2019 10:08 pm
The idea that stuff in the comments changes ones compiler output is nuts of course. It became such common practice that compiler writers wedged in in there.
It was introduced by static checkers such as lint decades ago (along with things like /*notreached*/).
Better than adding extra syntax or keywords that do nothing?
And obviously it makes no difference to the compilers emitted code.

Re: Looking for advice with C++ learning

Posted: Sun Aug 18, 2019 10:24 pm
by Heater
It's not clear to me that parsing the comments and matching it up to the code is any more simple than putting something into the syntax itself.

If you have warning as errors it certainly does effect the generated code :)

C++ now has an attribute for it:

Code: Select all

    case 2:
      g();
     [[fallthrough]];
    case 3: // no warn

Re: Looking for advice with C++ learning

Posted: Sun Aug 18, 2019 10:33 pm
by jahboater
Heater wrote:
Sun Aug 18, 2019 10:24 pm
It's not clear to me that parsing the comments and matching it up to the code is any more simple than putting something into the syntax itself.
Yes true, for a static checking program like lint.
For the compiler however, a comment is just a comment, much easier.
Though yes, its a different matter recently, now that compilers do much of the static checking.
Heater wrote:
Sun Aug 18, 2019 10:24 pm
C++ now has an attribute for it:

Code: Select all

    case 2:
      g();
     [[fallthrough]];
    case 3: // no warn
That's nice.

The comment form is meant to be for the human reader too by the way.
For that purpose it reads better as a standard comment I think.
No matter!

Re: Looking for advice with C++ learning

Posted: Mon Aug 19, 2019 9:03 am
by Heater
The frightening conclusion, when you step back an look at it, and try to forget all your years of C/C++ experience, is that every single statement of a C/C++ program is undefined behavior.

Unless that is, one can be sure that in the context the statement is in, and with the data it receives at run time, it will do some of the small subset of behaviors that are actually defined.

Being sure that it will never silently crash or give wrong results requires knowing every detail of the language definition, and the implementation, and every detail of every possible way that the statement gets used in your program and all possible data inputs it will ever see.

It's amazing we ever get a C/C++ program running at all!

Re: Looking for advice with C++ learning

Posted: Mon Aug 19, 2019 9:28 am
by PeterO
Heater wrote:
Mon Aug 19, 2019 9:03 am
Unless that is, one can be sure that in the context the statement is in, and with the data it receives at run time, it will do some of the small subset of behaviors that are actually defined.
I'm pleased to see that you've recognised this now, but I was thinking, "What would Heater's ideal language look like ?" and I came to the conclusion that every reference to a variable and to operators would need to include sufficient "meta data" in the source code to unambiguously define the desired behaviour. Only then could individual lines be taken in isolation and still be unambiguous.

Code: Select all

a = b + c;
needs to become something like

Code: Select all

 
[64 bit signed integer] a [64 bit signed operator] = [64 bit signed integer] b [ignoring overflow 64 bit signed integer operator] + [64 bit signed integer] b;
I can't see that catching on !
PeterO

Re: Looking for advice with C++ learning

Posted: Mon Aug 19, 2019 12:30 pm
by jahboater
PeterO wrote:
Mon Aug 19, 2019 9:28 am
needs to become something like

Code: Select all

 
[64 bit signed integer] a [64 bit signed operator] = [64 bit signed integer] b [ignoring overflow 64 bit signed integer operator] + [64 bit signed integer] b;
I can't see that catching on !
PeterO
Did you mean "checking overflow"?
I think Heater wants all integer arithmetic to be checked for overflow.

I like the fact that in C it is optional. You have the choice of fast code (with the programmer taking responsibility for avoiding overflow) or slow safe code with costly checks all over the place.