DEV Community

Cover image for Getting Cozy With C++

Getting Cozy With C++

Ben Lovy on July 28, 2019

Swallowing The Pill Some Background C++ is my self-learning white whale. I've tried many times over the years to make it a b...
Collapse
 
dwd profile image
Dave Cridland

As a long-time C++ developer, this is absolutely spot on. One change you might wish to make:

If having std::find is forcing you into defining an operator==() that you didn't otherwise want, you might want to look at std::find_if, which takes a UnaryPredicate - basically a functor accepting a single value. Conveniently, this can be a lambda.

So you'd do:

std::find_if(vec.begin(), vec.end(), [&t](Cell const & other) {
    return t.row == other.col && t.col == other.col;
}

It achieves the same thing (and, likely, with the same CPU instructions), but you've kept the required definition of equality for this purpose next to the point of use, instead of defining it globally.

Collapse
 
banzyme2 profile image
ENDEESA

Typo: t.row == other.col

Collapse
 
deciduously profile image
Ben Lovy

Ah, perfect! That does make sense, I'll probably refactor.

Collapse
 
vimmer9 profile image
Damir Franusic

Great article. I spent the last 8 years doing only c++ network programming. Then after thinking things through, I thought to myself that this is overly complex for what I'm doing and OOP is something I can live without. Also, I can easily replicate it with function pointers which I also use in C++ anyway.

This was just a quick intro, you should stick with C++ if you like it; you wrote a great post about it anyway. Now, here's the reason I'm writing this comment; there's an alternative to Valgrind which you could consider using once you get more acquainted with C++. Valgrind incurrs 20x slowdon or was 10x I don't rememeber honestly, but it can get quite slow and eat up a huge amount of memory. The other alternative that doesn't cause any noticeable slowdown are gcc/clang fsanitize methods

gcc -ggdb -o a.out a.cpp \
-fsanitize=address \
-fno-omit-frame-pointer

When I first started coding in C++ I also usw Valgrind; not even sure if fsanitize methods were available back then.

Happy programming and congrats on this great post.

DF

Collapse
 
deciduously profile image
Ben Lovy

Ah, thank you for the tip! I didn't know about that flag.

Collapse
 
vimmer9 profile image
Damir Franusic

It's a series of flags, check out the man pages of gcc/clang or look it up online.

Good luck with segfaults 😉

Collapse
 
codemouse92 profile image
Jason C. McDonald

Great article! Definitely saving this for newcomers to the language.

One other distinction that is easily forgotten is enum vs. enum class. The former is more of the C way of doing things, while the latter provides all the type safety you'd want out of an enumeration.

Collapse
 
deciduously profile image
Ben Lovy • Edited

Whoa! Thanks a bunch, I missed this detail entirely. We didn't go over this in this course, they only showed us the old-style enum.

This exactly what I want, and I'm glad I've got time to refactor before I submit this project!

Collapse
 
pgradot profile image
Pierre Gradot • Edited

I also wanted to point this out: try to use enum classes only. There are a lot of articles out there explaining why ;)

Also, take a look at Magic Enum to easily print enum values. Include it and then simply:

std::cout << magic_enum::name(value);

This change my life this year :D

Collapse
 
amorganpd profile image
amorganPD

Thanks for sharing your learnings!

So it looks like structs and classes do only differ in their default access and nothing else:

justsoftwaresolutions.co.uk/cplusp...

Looks like really only for C compatibility, which makes sense. I would default to class when writing for just C++ unless it's a small data structure.

Collapse
 
siy profile image
Sergiy Yevtushenko

Union sometimes useful in cases, when different types of data can be stored within same data structure. For example, sometimes it is convenient to have different "view" of same data, like integers as series of bytes and vice versa. In practice it's rarely necessary, quite low level and often error prone. There is an type safe alternative to unions - std:variant.

Collapse
 
deciduously profile image
Ben Lovy

Ah, that makes sense - I've been using std::variant. Seems like unions are most useful for interior with C that uses them.

Collapse
 
pgradot profile image
Pierre Gradot • Edited

As of C++17, you should use std::variant instead of plain old unions :)

Collapse
 
spqrbob profile image
Bob McCann

The Visual Studio IDE (visualstudio.microsoft.com/) is a heavy lift, but does have quite good support for C++. With all the good things everyone has to say about Visual Studio Code (code.visualstudio.com/), I wouldn't be surprised if there are some excellent C++ plugins for that platform as well. I have also heard and read good things about Jetbrains' CLion (jetbrains.com/clion/).

All of that being said (and linked), there are many folks who neither want nor need a memory-hogging GUI IDE getting in between them and their code. I have a close personal friend who is quite the Vim evangelist, and another who just uses notepad or whatever other simple text editor is at hand.

It sounds like you have a good start into the joy and frustration that is C++. Your article gave me flashbacks to my own college coursework in the language, working with threads and smart pointers and overloaded constructor/destructor/deep copy classes (lions and tigers and bears, oh my!). Good luck and have fun!

Collapse
 
deciduously profile image
Ben Lovy • Edited

Thanks for the tip! I'm currently using VS Code, and have spent a little time setting up a workflow in Emacs as well - for now that's more my speed. I also keep hearing good things about CLion, and have generally had good experiences with other JetBrains products, so that's probably where I'll look if VS Community isn't my style.

I've only ever mucked with threads from within the safe compiler-enforced confines of Rust, so I'm a little terrified to do it manually myself! Should be fun :)

Collapse
 
siy profile image
Sergiy Yevtushenko

Yeah, CLion is quite good. You might also take a look at NetBeans.

Collapse
 
lucpattyn profile image
Mukit, Ataul • Edited

struct and classes looks like the same thing, but using the keyword class instead of struct gives an indication to the reader (of your code) that you are trying to abstract a real world concept into your class. For example, it can be an abstraction/conceptualisation of the animal kingdom,
i.e, a human inherits its traits from a mammal which inherits from animal. Yes, you can use the keyword struct too, but usually struct should be used to conceptualise a data structure to pass around for use, for example a leaf node inside a tree. Yes, classes and structures are interchangeable but following a convention shows professionalism and intention behind the code.

Collapse
 
deciduously profile image
Ben Lovy

This is a really great response, and aligns pretty well with the intuition I'd sort of already been building. Thanks for putting it so clearly, I will keep this in mind.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀 • Edited

I want to learn Rust because I actually like how hard c++ is, and that is disturbing. But I keep telling myself I have come this far. It's like you said, it can be hard to know where stuff is coming from, that's my biggest bugbear with not the language but with my inexpensive. In JavaScript I can do some crazy things, but in C++ I feel like I wound back the clock several years and I'm a newbie. That excites me and terrifies me!

Collapse
 
mg_verycoolthx profile image
mg, thx

Thank you for this! I am new to C++ and to this entire field itself, and I found your perspective to be very useful in terms of grounding my love and appreciation for this language. As an aside, I've heard through the grapevine that the ecosystem surrounding C++ is on the mend and its popularity on the rise. It's hard not to be excited!

Collapse
 
deciduously profile image
Ben Lovy • Edited

I agree! I still plan to get my head around C++17 first, but C++20 does propose at least part of the way forward here.

I really like looking into all the new cute hipster languages with new cool features, and I've seen some new industry trends that might buck long-held standards, but I have never yet seen anything that could possibly replace C++.

Collapse
 
mg_verycoolthx profile image
mg, thx

Heyy, that's good for me, then! C++ is close enough to the hardware and far enough from it at the same time that it's really in an ideal position to be irreplaceable I think, barring a total revolution in computing altogether. Here's to a long life for our friend!

Collapse
 
pgradot profile image
Pierre Gradot

Hey!

A few (other) comments that may help :)

"C++ has structs and classes, but they're almost identical. The only difference is the default visibility: structs are public, classes are private, but through explicit annotations they're functionally equivalent otherwise."

Before talking why we have both, I wanted to point about a second important difference (this is not clearly said in your sentence): default inheritance is not the same. See here:

"If access-specifier is omitted, it defaults to public for classes declared with class-key struct and to private for classes declared with class-key class."

Try to modify the solution code to replace struct with class and see when it compiles and when it doesn't:

struct Foo {};

struct Bar : Foo {};

void doSomething(const Foo&);

int main() {
    Bar bar;
    doSomething(bar);
}

So "why struct AND class?". Well... C++ came from C and was supposed to be compatible. So we have struct and class for this reason only. Sorry.

From my experience, there is no real reason to use one why over the other. A quite common way is indeed to use struct for basic data type, where all members are public (and most of the time with no member function). Example:

struct Point {
  int x
  int y;
};

Class is used when you are modeling an object with behavior:

class NetworkConnection {
public:
   // ctor(s)
   void open();
   void close();
   void setTimeout(int);
private:
   // we don't care this is private
};

This is just a convention, there is no technical reason. Do what you want, simply be coherent.

By the way:

typedef struct Cell
{
    // ...
} Cell;

This is C-style code! Get rid of this typedef :)

struct Cell
{
    // ...
};

Finally:

"The biggest takeaway for me was that if you just use a pointer to a specific object, you don't need to actually include it, you can (and probably should) just forward-declare it."

First: try to use references at much as possible. If not possible, try to use smart pointers as much as possible.

Second: be prudent with this technique. Remember that including your class header should be enough for client code to compile. If you forward-declare a type in your HPP that is only needed in your CPP for the class implementation, no problem. If class users must also include the good headers, this can be painful.

Example with Foo.hpp:

#pragma once

class Foo;

struct Bar {
   Foo* foo;
};

If I include Foo.hpp in mySource.cpp, it won't compile. And I will have to wonder what other files I should include.

This may sound obvious but I saw code like this in real life...

Good luck with C++ ^^

Collapse
 
kristijanfistrek profile image
KristijanFištrek

I have huge appreciation for C++ ever since I wrote my first cout << "Hello World" << endl; back in freshman year in college ^

Collapse
 
deciduously profile image
Ben Lovy

Totally! It feels like you're driving a gigantic construction vehicle after practicing on a toy tractor. It just feels powerful right out of the gate.

Collapse
 
solanav profile image
solanav

Great article! (If "si vez algo di algo" is spanish, it's written "ves")

Collapse
 
deciduously profile image
Ben Lovy

Whoops, thanks! It's been altogether too many years since I studied it...

Collapse
 
mujeebishaque profile image
Mujeeb Ishaque

I do C++ at times. It scares me but whatever, I keep coming back to it after every 2 months or so.

A very good write-up indeed. Thanks for sharing.

Collapse
 
freecoder_dev profile image
Freecoder

Thanks a lot for this article!
If it can help someone, i share this useful GDB command line document.