0

So I was trying to set up an easy way for future developments to define log-messages. I thought of the following object-initialization inside a Header (as a global variable "SYSTEM_START"; not inside a function!):

const LogMessage SYSTEM_STARTED(0x0001, DEBUG, "System started");

which needs other declarations from a different header (just for the example here):

enum LogSeverity_E : uint8_t
{
    INFO = 0x01,
    DEBUG = 0x02
};

class LogMessage
{
  public:

    LogMessage( uint16_t messageId, LogSeverity_E severityId, const char* text = nullptr );

    const char* getText() const;
  private:

    uint16_t        messageId_;
    LogSeverity_E   severityId_;
    const char*     text_;
};

and its definition in a cpp:

LogMessage::LogMessage(uint16_t messageId, LogSeverity_E severityId, ConstCharPtr text) :
messageId_ { messageId }, severityId_ {severityId}, text_ { text }
{
    /* if I call a function here, e.g. a Singleton-function-call. What will happen if the object is initialized as a local/global variable like at the top? */
};

const char* LogMessage::getText() const
{
    return text_;
};

I am not working on a PC but on an embedded hardware with a special compiler. And what I saw here is that it calls this constructor even before jumping to main and so it also calls a singleton there as well.

I couldn't find any definition for this behaviour inside the cppreference nor elsewhere because everywhere the constructor-body for constant objects is just empty.

so as the comment in the constructor states: what happens if I call a function there in this specific example with const-objects as global variables? Is my explained behaviour that happens here a legal behaviour? Is even the usage of this code like this a legal behaviour? Or am I just lucky with my compiler and my embedded hw?

NetoBF
  • 127
  • 6
  • 3
    Objects are never const within the constructor (or destructor), as they would be impossible to construct or destroy if they couldn't be modified. – 1201ProgramAlarm Mar 22 '21 at 18:03
  • 2
    As a side-note, the constructor runs before `main` because program execution typically starts at `_start` which will do all sorts of setup, like calling global constructors, followed by calling `main`. – asynts Mar 22 '21 at 18:13
  • Does this answer your question? [C++ Singleton design pattern](https://stackoverflow.com/questions/1008019/c-singleton-design-pattern) – OznOg Mar 22 '21 at 19:41

0 Answers0