Share object across members

90 Views Asked by At

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!

2

There are 2 best solutions below

4
On BEST ANSWER

"//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);
}
0
On

To make it accessible to other members it should be a member variable. That means to declare it within the class SerialPort definition.