Please consider the following (simple) code. The strange (?) behavior is in the main()
routine and detailed below.
data class
Packet.h
#include <string>
class Packet {
public:
Packet(int iParam, std::string sParam);
~Packet();
void setInt(int iParam);
void setString(std::string sParam);
private:
int iProperty_;
std::string sProperty_;
};
Packet.cpp
#include "Packet.h"
using std::string;
Packet::Packet(int iParam, string sParam) : iProperty_(iParam),
sProperty_(sParam) {}
Packet::~Packet() {}
void Packet::setInt(int iParam) {
iProperty_ = iParam;
}
void Packet::setString(std::string sParam) {
sProperty_ = sParam;
}
controller class
PacketController.h
#include <string>
class PacketController {
public:
PacketController();
~PacketController();
PacketController & andSetInt(int iParam);
PacketController & andSetString(std::string sParam);
private:
Packet packet_;
};
PacketController.cpp
#include "PacketController.h"
using std::string;
PacketController::PacketController() : packet_(0, "") {}
PacketController::~PacketController() {}
PacketController & PacketController::andSetInt(int iParam) {
packet_.setInt(iParam);
return *this;
}
PacketController & PacketController::andSetString(string sParam) {
packet_.setString(sParam);
return *this;
}
main()
int main() {
PacketController& ctrlRef = PacketController()
.andSetString("hello world")
.andSetInt(19);
PacketController ctrlVal = PacketController()
.andSetString("hello world")
.andSetInt(19);
PacketController& ctrlRef2 = PacketController();
ctrlRef2.andSetString("hello world")
.andSetInt(19);
return 0;
}
If execution is paused at the line return 0;
of main()
then the following values are seen on the internal packet_
objects:
ctrlRef - packet_:
iProperty_: 19
sProperty_: ""
ctrlVal - packet_:
iProperty_: 19
sProperty_: "hello world"
ctrlRef2 - packet_:
iProperty_: 19
sProperty_: "hello world"
So why is sProperty_
empty on the packet_
object in ctrlRef
? Is it something to do with the reference being seated on initialisation of the PacketController
object? But then why is iProperty_
on the packet_
object of ctrlRef
correctly set to 19
?