I have Packet class contains virtual method and I have LogInRequest class which extends the packet class
Packet.h file
class Packet {
public:
Packet();
virtual ~Packet();
protected:
virtual char* toByte() = 0;
virtual void fromByte(char *d) = 0;
virtual Packet* handle() = 0;
short m_bodySize;
int64_t m_deviceId;
};
/*
* LogInRequestPacket
*/
class LogInRequestPacket: public Packet{
public:
LogInRequestPacket();
virtual ~LogInRequestPacket();
virtual char* toByte();
virtual void fromByte(char *d);
virtual Packet* handle();
};
Packet.cpp file
#include "Packet.h"
Packet::Packet() {
// TODO Auto-generated constructor stub
}
Packet::~Packet() {
// TODO Auto-generated destructor stub
}
/*
* LogInRequestPacket
*/
LogInRequestPacket::LogInRequestPacket(){
printf("LogInRequestPacket is being created... \n");
}
LogInRequestPacket::~LogInRequestPacket(){
}
char* LogInRequestPacket::toByte(){
}
void LogInRequestPacket::fromByte(char *d){
}
Packet* LogInRequestPacket::handle(){
}
I am trying to create this LogInRequestPacket from factory like this
Packet *packet = m_packetFactory->createInstance(static_cast<PACKET_TYPES>(type));
packet->fromByte(pdata);
And it seems like trying to call the protected virtual fromByte function instead of the child class’s fromByte function.
I am getting a red line at the line declaring “virtual void fromByte(char *d) = 0” in Packet class scope in Packet.h file and it complains “… is protected”
Also, it complains too with x within context
packet->fromByte(pdata);
How do I fix this problem. Thanks in advance…
When you try to call a method through a pointer or reference, the compiler will verify the access specifier of the function in the static type of the object, even if it will dispatch the call to the dynamic type.
In your
Packetclass you have stated that you don’t want user code (other thanPacket, friends and derived classes) to be able to call the methods, and the compiler is just telling you that. If those functions should be accessible from other code, make them public: