A
A
Alexander Buliterov2018-07-05 08:34:20
Microcontrollers
Alexander Buliterov, 2018-07-05 08:34:20

Is it possible to create an instance of a class (c++) with initialized fields?

Good afternoon!
There is a class that is essentially a Cish structure, i.e. fields without methods. Since the development is carried out under the microcontroller, where "640 KB of RAM may not be enough" and the class fields will not change in the process, I would like to "push" such variables into Flash.
natural entry

class type_class {
int field1;
int field2;
  type_class (int f1, int f2) {
    field1 = f1;
    field2 = f2;
  }
}
const type_class var(12, 34);

does not create a variable in Flash. Is there any way to get around this in C++?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2018-07-05
@bullitufa

$ cat > test.cpp <<EOF
class type_class {
        int field1;
        int field2;
public:
        constexpr type_class (int f1, int f2): field1(f1), field2(f2) {
        }
};
extern const type_class var;
const type_class var(12, 34);
EOF
$ g++ -S -O2 test.cpp
$ cat test.s
        .file   "test.cpp"
        .globl  var
        .section        .rodata
        .align 8
        .type   var, @object
        .size   var, 8
var:
        .long   12
        .long   34
        .ident  "GCC: (Debian 6.3.0-18+deb9u1) 6.3.0 20170516"
        .section        .note.GNU-stack,"",@progbits

Those. constexpr constructor, resulting in a ready-made initialized object in the .rodata section, as required.

M
maaGames, 2018-07-05
@maaGames

> class fields will not change in the process
, which means they need to be made static constants and, possibly, the class should be removed altogether, replacing it with namespace.
> "They say" it is possible through a template, but as they did not say)
In fact, the same static constants, only they can only be an integer and do not have an address.

template< int X, int Y >
class NAME
{
public:
    enum { field1 = X, field2 = Y };
};

typedef NAME<5,7> Name57;

int a = Name57::field1;
int b = Name57::field2;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question