Search code examples
c++objectmembers

Share object across members


I'm trying to make the following example code work. I've read thru several tutorials and Q&A's, but I can't get it to work. In all likelyhood my understanding of classes are lacking, but I learn by doing. Hope I don't offend anybody :-)

I'm working on serial port communication, and I'm trying to use the callback version of this library: http://www.webalice.it/fede.tft/serial_port/serial_port.html

The specific question is in the commented code.

UPDATED - I figured it out, the code below is working :-)

Here's the SerialPort.h file:

#include "AsyncSerial.h"

class SerialPort
public:
    void portOpen();
    void portWrite();
private:
    CallbackAsyncSerial serial;
};

And SerialPort.cpp:

#include "SerialPort.h"

void SerialPort::portOpen() {
// serial = CallbackAsyncSerial("COM1", 115200);  Doesn't work
serial.open("COM1", 115200);  //This works :-)
}

void SerialPort::portWrite() {
    serial.writeString("Hello\n");
}

void main() {
    SerialPort objt;
    objt.portOpen();
    objt.portWrite();
}

Thanks for your help!


Solution

  • "//How do I make the object "serial" accessible in the other members?"

    Make it a member variable itself

    class SerialPort
    public:
        void portSet();
        void portOpen();
        void portWrite();
    
    private:
        CallbackAsyncSerial serial;
    };
    

    void SerialPort::portOpen() {
        serial = CallbackAsyncSerial("COM1", 115200);
    }