Richard Slabbert
Richard Slabbert

Reputation: 71

C++: implications in main() of using forward class declarations

I have three C++ classes: Position, Employer and Person. Each person has an employer and a position in that employment. As you can see below I have used forward class declarations to join the Employer and Position classes to the Person class.

I am new to forward declaration of classes, but found the When to use forward declaration post to be very insightful with regards to when and how to use forward declaration.

However, I am primarily concerned with how to use setPosition() in my main function?

person.h

class Position;
class Employer;

class Person
{
public:
    // other public members
    void setPosition(Employer* newC, Position* newP)
    {
        m_position = newP;
        m_employer = newC;
    }
private:
    // other member variables
    Position* m_position;
    Employer* m_employer;
};

Here is snippets from main.cpp:

#include "employer.h"
#include "person.h"
#include "position.h"

int main()
{
    Employer StarFleet("StarFleet Federation", "space exploration");
    Person JLP("Jean-Luc Picard");
    Position cpt("StarFleet Captain", "Save the world");

    JLP.setPosition(StarFleet,cpt);

    return 0;
}

The issue is a get a compiling error:

error: no matching function for call to 'Person::setPosition(Employer&, Position&)' in main.cpp candidate is: void Person::setPosition(Employer*, Position*)

no known conversion for argument 1 from 'Employer' to 'Employer*'

I would like to know how you would go about using setPosition in main()?

I hope I have made myself clear. If you require any more of my code just let me know.

Upvotes: 0

Views: 106

Answers (1)

xinaiz
xinaiz

Reputation: 7788

Your function arguments are pointers, but you send variables by value. You must use their addresses:

JLP.setPosition(&StarFleet,&cpt);

Upvotes: 7

Related Questions