Hello folks,
I have this header file:

class Agent {
private:

    struct AgentStruct {
        std::string agentName;
        double pID;
        double mID;
        AgentStruct *nextAgent;
    } *AgentP;

public:

    Agent(std::string);
    void SetNextAgent(AgentStruct*);
    Agent* GetNextAgent();
    void SendMessage();
    void ReceiveMessage();

};

and I have the implementation here:

/*
 * The constructor we are required to implement.
 */
Agent::Agent(std::string name) {
      AgentP->nextAgent=NULL;
      AgentP->agentName=name;
      AgentP->pID=setPID();
      AgentP->mID=AgentP->pID;
}

I get a segmentation fault.
Any ideas?

thanks!

You have never allocated memory for AgentP member.
This should fix the problem

Agent::Agent(std::string name)
:AgentP(new AgentStruct())
 {
      AgentP->nextAgent=NULL;
      AgentP->agentName=name;
      AgentP->pID=setPID();
      AgentP->mID=AgentP->pID;
}

Why are you using pointers?

how can I do it without pointers?

>>how can I do it without pointers?

Like this:

class Agent {
private:

    struct AgentStruct {
        std::string agentName;
        double pID;
        double mID;
        AgentStruct *nextAgent;
    } AgentP; //notice no * star sign.

public:

    Agent(std::string);
    void SetNextAgent(const AgentStruct&); //notice pass-by-reference
    Agent* GetNextAgent();
    void SendMessage();
    void ReceiveMessage();

};

//...
/*
 * The constructor we are required to implement.
 */
Agent::Agent(std::string name) { //no need to create AgentP
      AgentP.nextAgent=NULL; //notice dot instead of arrow.
      AgentP.agentName=name; //in C++0x, this could also all be in the initialization list instead.
      AgentP.pID=setPID();
      AgentP.mID=AgentP.pID;
}

Of course, if there is another reason (that you didn't mention) why you need to use a pointer for AgentP, it is fine to do it, but remember to delete it in the destructor of the Agent class (or better, use a smart pointer).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.