What is this in a C++ structure

Thread Starter

bug13

Joined Feb 13, 2012
2,002
Hi team,

Here is the code:
Code:
struct Sum
{
    int sum;
    Sum() : sum(0) { } // <<== what is this???
    void operator()(int n) { sum += n; }
};
Sum s = std::for_each(v.begin(), v.end(), Sum());
Can I please have a name for this so I can google it and find out more about it?? thanks team!!
Code:
Sum() : sum(0) { } // <<== what is this???
 

WBahn

Joined Mar 31, 2012
32,852
I don't know C++, so I'm shooting in the wind here (keep that in mind). But you might see if it is a constructor or initializer of some kind.
 

MrSoftware

Joined Oct 29, 2013
2,273
I'm rusty so double check me by stepping this in your debugger, but I believe that's an assignment that runs before the constructor for Sum(). At first glance, I'm not sure why in this case it's important for that assignment to happen before the constructor for Sum, so perhaps you could get equivalent behavior by replacing that line with this one:

Sum() { sum = 0; }

Give that a try and see if it breaks anything.

edit --> Yes I believe I am correct. Here is some test code to play with:

Code:
#include "stdafx.h"
#include <vector>
#include <algorithm>
#include <iostream>

struct Sum
{
    int sum;
    // ctor
    Sum()   // Putting :sum(0) here is basically "sum=0" but runs before the code in braces below
    {
        sum = 0;
    }
    void operator()(int n) { sum += n; }
};

int main()
{
    std::vector<int> myInts;
    myInts.push_back(1);
    myInts.push_back(5);
    myInts.push_back(7);

    Sum s = std::for_each(myInts.begin(), myInts.end(), Sum());

    printf("Sum: %i\n", s.sum);


    return 0;
}
upload_2019-5-27_20-37-8.png
 
Last edited:

MrSoftware

Joined Oct 29, 2013
2,273
It's called an initializer list, sometimes it's just convenient, and sometimes it's necessary. The key takeaway is the initializer list will execute before the objects constructor. I believe there are additional cases where it is necessary, but here is some discussion to give you the general idea:

https://docs.microsoft.com/en-us/cpp/cpp/constructors-cpp?view=vs-2019#init_list_constructors

https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list

Here is some example code just so you can see the order:

Code:
#include "stdafx.h"
#include <vector>
#include <algorithm>
#include <iostream>

struct Sum
{
    int sum;
    // ctor
    Sum() : sum(1)
    {
        printf("Sum is first initialized to: %i\n\n", sum);
        sum = 0;  
        printf("Sum now equals: %i\n\n", sum);
    }
    void operator()(int n) { sum += n; }
};

int main()
{
    Sum a;
    printf("Sum after creation: %i\n\n", a.sum);
}
 

Attachments

402DF855

Joined Feb 9, 2013
271
Sum() : sum(0) { }
IMO the traditional method of initializing members in a constructor body used to be more popular. Nowadays the initializer list seems to be gaining, but they are ultimately equivalent. It's probably more of a question of style. I've written a million plus lines of C++ and very rarely had to use the initializer list. IIRC correctly the times I was forced to use it related to initializing reference variables, but I'd have to go back and review the pertinent source code.
C:
Sum::Sum()
{
      sum=0;
}
 

nsaspook

Joined Aug 27, 2009
16,326
It's called OOPs for a reason.
I don't think it's OOPs in general as 'C with Classes' is effective OOP. C++ (++C is a better name :D) is an old, bad (high complexity, too much “undefined behavior”) implementation language of a good idea that solves problems most of us will never see at the procedural coded embedded scale.
 

nsaspook

Joined Aug 27, 2009
16,326
You can see the frustration in his face about high complexity.

C++ is a good programming language for 'software programmers' that live to code on powerful processors. The problem IMO is with the guys that write low level code as primarily hardware engineers. Most commonly use a very restricted level of C++ abstraction capabilities (NO dynamic heap allocation functions, exceptions or non-deterministic run-times for I/O functions often seen in embedded programming) so that using C directly results in them being better hardware programmers with "not so powerful" processors.
 

MrSoftware

Joined Oct 29, 2013
2,273
I'm not sure we watched the same video? Well written C++ is every bit as fast and efficient as C. Dynamic memory allocation is just as much a feature of C as it is of C++. And nowhere is it written that you have to use exceptions!?
 

nsaspook

Joined Aug 27, 2009
16,326
I'm not sure we watched the same video? Well written C++ is every bit as fast and efficient as C. Dynamic memory allocation is just as much a feature of C as it is of C++. And nowhere is it written that you have to use exceptions!?
Well written C++ != well written C. C++ complexity matters on the point of well written to the strengths of the language. My objections are not based on achievable speed and efficiency. In the hands of a good programmer C++ is a winner for general applications but there things like hidden Dynamic memory allocation in STL and Boost that impose restrictions on code written to safety specifications where Dynamic memory allocation is not allowed.
 
Last edited:

MrSoftware

Joined Oct 29, 2013
2,273
There is no requirement to use STL or Boost; those are libraries, not part of the language itself. You can avoid dynamic memory allocation in C++ just like you can in C.
 

nsaspook

Joined Aug 27, 2009
16,326
There is no requirement to use STL or Boost; those are libraries, not part of the language itself. You can avoid dynamic memory allocation in C++ just like you can in C.
Exactly my point. If you can't use many of the most popular programming libraries because of specific application limitations, why use the language if you need to 'roll your own' 'safe' libraries anyway. C is not a static language, The latest versions address some long standing problems and add 'class' capabilities in a C compatible way. (new C standard, C18)
https://www.externcode.com/c-standards/

This is not a anti-C++ rant. There are very good reasons C (C99 at least) is still used when C++ is also a valid option.

 
Last edited:

402DF855

Joined Feb 9, 2013
271
why use the language if you need to 'roll your own' 'safe' libraries anyway
Why not? Basic string and container classes can be designed quickly and reused for decades. I've managed to write a million plus lines of industrial C++ almost entirely without those libraries. Not all was embedded but some was. I'd rather use C++ on all of my projects, but clients still seem to cling to C, probably because they are not trained in C++.

But, I will at all costs avoid exceptions and templates if possible. And namespaces.
 

nsaspook

Joined Aug 27, 2009
16,326
Why not? Basic string and container classes can be designed quickly and reused for decades. I've managed to write a million plus lines of industrial C++ almost entirely without those libraries. Not all was embedded but some was. I'd rather use C++ on all of my projects, but clients still seem to cling to C, probably because they are not trained in C++.

But, I will at all costs avoid exceptions and templates if possible. And namespaces.
Why go to the effort of retraining if you are embedded C 'centric' already with controllers and it was worked for decades. While C++ has many uses even Bjarne admits it's not always the best good option for many controller projects where you need (and usually want) much less source code abstraction for predictable and traceable debugging from assembly back to source. The compile time optimization of code generated is very important for C++ efficiency and speed. This can cause negative effects with some very low-level debugging using the types of tools most hardware engineers use to debug systems that worry about hardware operation interaction perfection a lot more than sequencing HLL source code perfection. The C syntax that some programmers seem to hate is a blessing to the detailed mind of a hardware engineer that wants to see actual 'loop' type asm code produced when a 'for' loop is used and begins to worry when the HLL decides that it can eliminate (in a programmatic correct way) that entire slice of code with a constants table instead.
 

MrSoftware

Joined Oct 29, 2013
2,273
I think you're assuming too much. Your argument sounds like don't buy bread from Walmart because there's too much stuff in the store. You don't have to use every feature or every library of C++, just use what makes sense. Classes don't have to be complicated or convoluted, and loops in C++ can look exactly like loops in C. Just like C, you have full control over compiler optimization, such as through compiler settings and/or pragmas.
 

nsaspook

Joined Aug 27, 2009
16,326
I think you're assuming too much. Your argument sounds like don't buy bread from Walmart because there's too much stuff in the store. You don't have to use every feature or every library of C++, just use what makes sense. Classes don't have to be complicated or convoluted, and loops in C++ can look exactly like loops in C. Just like C, you have full control over compiler optimization, such as through compiler settings and/or pragmas.
If I'm actually only really programming in C (C with classes) while using a C++ compiler then what's the advantage over a supported for decades C compiler optimized for my chip family? I see little or no advantage unless I can use most of the full language, libraries, tools and actually program in C++. Bare metal C code in a forever while loop doesn't need much OOP to run correctly with a FSM. As I've said before, this is a not a anti-C++ rant. It's information on why people still use C on this end of the programming scale.
 
Last edited:

402DF855

Joined Feb 9, 2013
271
Why go to the effort of retraining if you are embedded C 'centric' already with controllers and it was worked for decades.
One can be an adequate embedded developer using C. But for those trained in OOD C++ can provide a boost in productivity. In my experience this boost can have a positive influence on job satisfaction. It also can, in theory, provide an avenue for a competitor to eat your lunch.

Unfortunately C++ may be rejected by those who are victims of poorly thought-out applications of it in practice. I've seen plenty of nightmares. We've all probably seen that in C as well. For example, just because you can use namespaces to delineate your massive class hierarchy doesn't mean you should. Templates and exceptions are often poorly applied and lead to frustration. I like to think of C++ as a superset of C, so any C code is for the most part C++. Classes and inheritance, along with the benefit of function overloading are really nice additions to the language. If you know how to use them, and that takes training, especially if one can learn from someone that knows how to do it right.
 
Top