I'm new to c++ coming from Java so I'm not sure what I'm doing wrong here
the following line in person.h is giving me the error Transaction has not been declared.
void pay(Transaction transaction);
I have a Transaction object, do I have to declare / include it in the person.h file somewhere?
here is my person.h source
#ifndef PERSON_H_
#define PERSON_H_
#include "Transaction.h"
using std::string;
class Person {
public:
class Transaction;
Person();
virtual ~Person();
void pay(Transaction* transaction);
};
#endif /* PERSON_H_ */
In C++, seperating the declarations from the definitions is a big thing. Declarations tell how to use the code, and are in header (.h) files. Definitions are the code itself, and are in source (.cpp) files.
If a file only refers to Transaction by pointer or reference (as is common in a header), then you only need to predeclare the transaction class, with class Transaction;. If the file needs an actual Transaction value, then you need to #include "Transaction.h".
If it still says Transaction is an undefined symbol, that means you have a circular dependency: A series of headers that include each other in a loop. In that case, you need to alter one of the header files to only use pointers and references, and predeclare the classes in the other headers.
When you declare a class inside another class, you're declaring an internal class.
So
class Person {
public:
class Transaction;
};
Declares a class whose fully qualified name is Person::Transaction. Even if there is another class named Transaction at global scope, references to Transaction will be assumed to refer to Person::Transaction. Since you haven't defined that class, you get your error.
What you want is ::Transaction, either from including the header or from forward declaring outside your class declaration. Do either
class Transaction;
class Person {
};
OR
#include "Transaction.h"
class Person
{
};
The former only allows passing by reference. Passing by value or calling a function requires the full class definition provided by include.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With