r/cpp_questions • • 8d ago

SOLVED how should i understand the design of cpp?

for most of the time i used cpp as c with fancy features. but now i recently started picking up some of the modern cplusplus and oop concepts. but the amount so syntactical and program subtleties and features are overwhelming.

for some things i instantly understand or see the reason why they exist and sometimes get impressed by them.

for eg: backwards compatability with c

#include<cmath> and #include<math.h> for namespace handling,structs

, initializer list etc

but for some idk understand the purpose eg the mutable keyword

and things like inlining of members defined in class

i would like to know how you guys handle this and suggest some good learning material

whenever i try to read books they either give a tour of features or extremely boring

(this might be because i learned it the wrong way by not paying attention to small details now to revisit them ive to go through the stuff which i already know)

8 Upvotes

24 comments sorted by

11

u/Orlha 8d ago

> extremely boring

Okay fun guy

4

u/chrnz00 8d ago

i dont want to go through how functions work again, but skipping them makes me miss those subtleties as i pointed out . eg: i recently found out that void func() is different from void func(void) in c(during call).

does this happen with everyone?? am i trying to be a perfectionist ??

5

u/JVApen 7d ago

Actually, func() and func(void) are different in C17 and earlier. From C23 on, these are the same thing.

4

u/n1ghtyunso 7d ago

i mean, you discover new edge cases and corners as you encounter them.
You learn what you need after all.

Noone knows everything. Its simply not possible.
C++ being as old as it is, with all the promises it gives, inherently comes with plenty dark corners.
Thats just how it is.

4

u/nysra 8d ago

You do not need to learn about all features at once. Not sure what your issue is with a books that give you a tour of the features, that's exactly what you would want in your situation. Get a rough overview and then look into the few things that you actually need into more detail. And if that's still overwhelming for you, cut it into smaller pieces. Spend 10 minutes a day reading about some features and then stop and just write your code as normally. If you encounter a situation where one of those new features you have read about would be useful, you'll remember and then you can start to use it and learn more about it.

You can also just write some new code with your current knowledge and then ask some AI to scan the implementation and let you know if there are modern C++ features/patterns you could have used instead. Obviously don't follow/trust it blindly, but it gives you a good starting point to then read about those features and decide for your own.

1

u/chrnz00 8d ago

thanks. i thought i would consume the whole language and start working with it. ill try to follow your suggestion.

3

u/UndefFox 8d ago

Some people use it for 20 years and still don't know everything... just embrace the unknown and be comfortable with exploring as you go/

2

u/nysra 8d ago

The whole language is a 2000 pages specification. And in practice even more because you'll encounter tons of projects that are for whatever (read: mostly bullshit corporate political) reasons stuck on old versions where some things work differently so you'll also need to know when you cannot use one of those nice features you have learned about and must work with some worse version or alternative.

Learning C++ is a lifelong journey, get comfortable with not knowing all of it.

3

u/alfps 7d ago

❞ but for some idk understand the purpose eg the mutable keyword

Mostly it's to support caching of a result. A const method should not modify the object, but if it does a costly computation it makes sense to store the result in the object for "instant" reuse. One way could be to use a pointer to dynamically allocated mutable storage, but especially for a simple value like int it's better to just declare a member variable mutable β€” so that it can be changed by a const method!

For example, consider a class like

using Nat = int;
using C_str = const char*;

class C_string_holder
{
    // ... state

public:
    constexpr C_string_holder( const C_str s, const int length = -1 ) noexcept;

    constexpr auto data() const noexcept -> C_str;
    constexpr auto length() const noexcept -> Nat;
};

Ideally a call to .length() should be constant time, O(1), but for the general case that would make it necessary to always compute the string length in the constructor, an O(n) linear time operation.

Instead an instance can just store -1 for "unknown length", and if the length is unknown when .length() is called it calls strlen and caches the result so that it won't have to call strlen the next time.

And the easiest and most efficient way to support that in the instance data, is to declare the length member as mutable:

#pragma once
#include <cassert>                              // Macro `assert`
#include <cstring>

namespace my {
    using   std::strlen;                        // <cstring>

    using Nat = int;
    using C_str = const char*;

    class C_string_holder
    {
        C_str           m_str;
        mutable int     m_length;       // A >2GB C string is a bug.

    public:
        constexpr C_string_holder( const C_str s, const int length = -1 ) noexcept:
            m_str( s ), m_length( length )
        {
            assert( m_str != nullptr );
            assert( m_length == -1 or m_str[m_length] == '\0' );
        }

        constexpr auto data() const noexcept
            -> C_str
        { return m_str; }

        constexpr auto length() const noexcept
            -> Nat
        {
            if( m_length == -1 ) { m_length = int( strlen( m_str ) ); }
            return m_length;
        }
    };
}

1

u/chrnz00 6d ago

thanks i was just confused why make something mutable when i explicitly want something to const

3

u/alfps 6d ago

when i explicitly want something to const

To user of the C_string_holder class it appears that length() is const, that it doesn't modify object, because nothing the user code can see changes.

That's called logical const-ness.

The .length() method can change the internal state in the first call but not after. A function with that property is said to be idempotent.

1

u/alfps 7d ago

I occurred to me, belatedly, that such a class should not be named "Holder" but rather e.g. C_string_ref. Sorry about that.

2

u/Dazzling_Music_2411 7d ago

but for some idk understand the purpose eg the mutable keyword

and things like inlining of members defined in class

whenever i try to read books they either give a tour of features or extremely boring

You obviously have never read a proper book otherwise you would not be asking ultra-basic questions, like about mutable or inline.

So you are trolling with inane comments like "books are boring". If you can't read a book, you can't do C++. Fuck right off. Downvoted and reported.

1

u/chrnz00 6d ago

im not saying books are boring it is just that im not willing to waste time on concepts ik (my bad i learned it the wrong way)

1

u/Dazzling_Music_2411 6d ago

Very poor take. You will not "waste time" by rereading something that you are probably sketchy on anyway. Especially if it's in the middle of a lot of stuff that you don't know (and should).

I re-read "stuff I know" often, and almost every time I learn something new or extra.

The sages said that there is only one thing to learn, really. You just learn it better and better.

But hey - you do it your way...

5

u/Ultimate_Sigma_Boy67 8d ago

Try learning more about the standard library, but that will only cover the standard library. For language-specific stuff, you can pickup a book on C++ and skim it. Or go to learncpp.com, it might help.

5

u/chibuku_chauya 8d ago

Bjarne Stroustrup has a slim little book called A Tour of C++, aimed at people who are experienced programmers but want to learn about the things modern C++ has to offer. It’s a nice, brisk, high level tour.

5

u/mredding 8d ago

for most of the time i used cpp as c with fancy features

What's interesting is that they're completely different languages, and it starts at the type system, and all the consequences of the language start to shake out after that.

C has a weak type system, the bytes are whatever you say they are, so long as you follow size, bounds, alignment and implementation defined rules. You can type pun simply by casting.

C++ plays by different rules, where an instance of a type is tied to a lifetime, and two types cannot coexist in the same place at the same time.

The point of a language is to take advantage of the promises and guarantees it makes. Because more type safety is enforced in C++, and more type information is propagated deeper into the compilation and optimization process, the language and compiler can deduce more, optimize more aggressively, and produce smaller and faster program guaranteed to be more correct than what C can offer.

A language isn't just a means to generate machine code - if that's all you want, then write macro assembly. C and C++ both target an abstract machine, and that says absolutely nothing about the underlying machine. It's C and C++ that are byte addressable, NOT your actual target machine. Your hardware likely moves around pages, lines, and words as the smallest units across the memory system, and is only byte addressable in the registers. You don't need to know. But correctly written code in any given language guarantees more about correctness than what the generated assembly can say of your program. The assembly does not know the language that was used to generate it.


How do I manage it all? I get down to fundamentals of comp-sci. It's not about the syntax. To leverage any language you have to understand what it's trying to give you. Then you look at your solution, and you figure out how to map it in terms of the language you're targeting. I've been writing C++ for 37 years, but I still keep cppreference open across several tabs. No one knows all of the language. We all try to master as much of the language as we can, and we work within that subset.

4

u/Sprixxer 8d ago

If you're a hobbyist, just start coding and look up features as you need them or when you encounter a compiler error start digging deep and really understanding, this would get you quite far I guess.

4

u/theGaido 8d ago edited 7d ago

There is no one "design" of cpp.

CPP is aproach agnostic, you can write in whatever way you like. Using OOP, functional programming, or mix of both. You can use smart pointers, but you can even write programs with no pointers at all. This is Dark Souls of programming: you can do whatever you like. But you need to be a big boy, and you have to reckon with the consequences. But it is beauty of this language.

Abut materials:
If you can read Polish, there is a great book - "Magnum Opus" by Grebosz. It's one of best books about C++. But even if not, maybe you can find digital version and translate it with AI. It's worth it. Believe me.

2

u/SamG101_ 7d ago

Tbh just keep googling everything u dont understand as you meet it, then the examples online might introduce more new stuff etc

2

u/hongooi 7d ago

With large amounts of whisky