I am teaching myself to write classes in C++ but can’t seem to get the compilation to go through. If you can help me figure out not just how, but why, it would be greatly appreciated. Thank you in advance! Here are my three files:
make_pmt.C
#include <iostream>
#include "pmt.h"
using namespace std;
int main() {
CPMT *pmt = new CPMT;
pmt->SetVoltage(900);
pmt->SetGain(2e6);
double voltage = pmt->GetVoltage();
double gain= pmt->GetGain();
cout << "The voltage is " << voltage
<< " and the gain is " << gain << "." <<endl;
return 0;
}
pmt.C
#include "pmt.h"
using namespace std;
class CPMT {
double gain, voltage;
public:
double GetGain() {return gain;}
double GetVoltage() {return voltage;}
void SetGain(double g) {gain=g;}
void SetVoltage(double v) {voltage=v;}
};
pmt.h
#ifndef PMT_H
#define PMT_H 1
using namespace std;
class CPMT {
double gain, voltage;
public:
double GetGain();
double GetVoltage();
void SetGain(double g);
void SetVoltage(double v);
};
#endif
And for reference, I get a linker error (right?):
Undefined symbols:
"CPMT::GetVoltage()", referenced from:
_main in ccoYuMbH.o
"CPMT::GetGain()", referenced from:
_main in ccoYuMbH.o
"CPMT::SetVoltage(double)", referenced from:
_main in ccoYuMbH.o
"CPMT::SetGain(double)", referenced from:
_main in ccoYuMbH.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
First some taxonomy.
This
is defining a class without also defining the member functions. This
is defining the same class, with also defining its member functions (implicitly) inline. This
is defining the member functions (not inline).
Now, if you want to separate implementation from interface, your header needs to define the class, while your implementation file needs to define its member functions. So the pure class definition
goes into the header file and the implementation
goes into the implementation file – except for those member functions you want to implement inline. Since
inlineasks the compiler to substitute a function’s implementation for every call to it, the implementation must be present where the function is called. That’s why the implementations of inlined functions must be in header files.There are two ways to inline a member function. One is to define it within its class’s definition
which implicitly makes it
inline. The other is to explicitly inline itIn both cases the implementation must be in the header file.