soje
soje

Reputation: 25

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!

Upvotes: 2

Views: 85

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

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

Upvotes: 2

ScottMcP-MVP
ScottMcP-MVP

Reputation: 10425

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

Upvotes: 1

Related Questions