8 years ago.

C++ Programming issue

Hello,

I'm newish to C++ style programming. I've been programming in C for many years. I am trying to develop a class that has a pointer to a Mail instance as one the members. I would like to be able to assign the size of the Mail instance in my class constructor.. However, the compiler complains that the Mail member pointer and the new Mail call in the constructor must use a constant size declaration.

Code snippet is below. I'm stuck. Any ideas on how to solve this would be appreciated.

#include "mbed.h"
#include "rtos.h"
#include <stdint.h>

typedef struct
{
    char   msg[80];
    uint32_t timeInUsec;
} Msg;

class Log
{
public:
    Log(char* Name = NULL, uint32_t numMessages = 16);
    ~Log();
    
    int saveMsg(Msg msg, const char* format, ...);
    int printMsg(Msg msg, const char* format, ...);

private:
    char _name[16];
    uint32_t _numMessages;
    Mail<Msg, _numMessages>* _mailBox;
};

Log::Log(char* name, uint32_t numMessages)
{
    strncpy(_name, name, sizeof(_name) - 1);
    _numMessages = numMessages;
    _mailBox = new Mail<Msg, _numMessages>;
}

Log::~Log()
{
    delete _mailBox;
    return;
}

int Log::saveMsg(Msg msg, const char* format, ...)
{
    // do stuff
        
    return(0);
}

int Log::printMsg(Msg msg, const char* format, ...)
{
    // do stuff
        
    return(0);
}

int main (void) 
{
    uint32_t logSize = 16;
    
    Log myLog("Test", logSize);
    
    // do stuff
    
}

2 Answers

8 years ago.

I am not sure why the error, but some suggestions...... i do not know why you would want this Log(char* Name = NULL, uint32_t numMessages = 16); I can see Log(char* Name, uint32_t numMessages = 16); you have to have a name otherwise,

then you can create the class two ways Log("foo", 10); Log("foo); numMessages defaults to 16

also us an initialize list Log::Log(char* name, uint32_t numMessages) : _numMessages(numMessages) {

8 years ago.

I think the issue is that the Mail is made using a template. These require the values to be known at compile time, and the compiler is not smart enough to figure it out like this. One thing which should work is to also use a template yourself for your class. You can google around for C++ templates, in addition here is an example that uses it on mbed: https://developer.mbed.org/users/Sissors/code/FastIO/docs/89d6ae484a35/FastIO_8h_source.html

Eric,

Thanks for your reply. You are correct, the issue I am trying to resolve is how to get around defining the "_numMessages " value in the template as a constant. I would like to be able to resolve this at runtime. So far I have not had any luck with this issue. I may have to try some other approach.

posted by Tom Doyle 11 Apr 2016