Class Linker Error

Started by
1 comment, last by orcfan32 18 years, 8 months ago
I am testing using classes and here's my problem: I get a linker error with undefined reference to my method, "void AddText(std::string)". Here's my code: FSTR.cpp:
#include <iostream>
#include <string>
#include "FSTR.H"
using namespace std;



int main()
{
  FSTR FSTR_M;
  FSTR_M.AddText("test");
  cin.get();
}

FSTR.H:
#include <iostream>

class FSTR
{
    public:
        FSTR();
        ~FSTR();
        
        void AddText(std::string Text);
};

FSTR::FSTR()
{

}

FSTR::~FSTR()
{

}

void AddText(std::string Text)
{
     std::cout<<Text;
}

Any clue why? Thnks in advance.
The best thing to do is just choose whatever you think you'd prefer, and go for it. -Promit
Advertisement
1. This isnt the reason i don't think but you should't have the class code and the definiton in the same source file, unless the methods are actually embedded in the class definition.

2. This:

void AddText(std::string Text)
{
std::cout<<Text;
}

should be...

void FSTR::AddText(std::string Text)
{
std::cout<<Text;
}

3. You should be passing the string by const reference most likely, so:

void FSTR::AddText(const std::string& Text)
{
std::cout<<Text;
}

Change your method definition to be the same as well.

The reason for the const reference is because 'const' signifies to the person using the function that the code inside the function doesn't change the string. The reference '&' means that you are not passing the string by value, which is slow, rather by name, as it where. By value is slow because a fresh string the same as the original is created, by reference is like using the original. For this the code in the method doesn't need to change, a reference is treated the same as by value.

There ya go bud,

ace
Thanks, it works now. I really don't understand classes at all, but I'm learning!
The best thing to do is just choose whatever you think you'd prefer, and go for it. -Promit

This topic is closed to new replies.

Advertisement