Author Topic: Add files with classes to C::B  (Read 4321 times)

Offline ossLover

  • Single posting newcomer
  • *
  • Posts: 8
Add files with classes to C::B
« on: February 01, 2010, 01:23:01 pm »
OS: WinXP (SP2) 32-bits

Hello guys,

I played with C::B to try out some new techniques, now I have the following problem.
When compiling the following code:
Code
template <class T>
class GenVar
{
    public:
        T a;
        T b;

    public:
        GenVar(void) : a(0), b(0) {}

        void operator=(const GenVar<T>& var);
        GenVar<T> operator+(const GenVar<T>& var);
};

template <class T>
void GenVar<T>::operator=(const GenVar<T>& var)
{
    a = var.a;
    b = var.b;
}

template <class T>
GenVar<T> GenVar<T>::operator+(const GenVar<T>& var)
{
    GenVar<T> temp;
    temp.a = a + var.a;
    temp.b = b + var.b;
    return (temp);
}

int main()
{
    double x = 3.56789;
    double y = 2.56784;
    GenVar<double> m, n, p, q;

    m.a = n.a = 2.00234;
    m.b = n.b = 5.98457;

    p = m+n;
    q = p;
    cout<<"Adding class objects using templates: a is "<<p.a<<" b is "<<p.b<<endl;

    return 0;
}
It compiles fine.

But when putting the class in seperate files GenVar.cpp and GenVar.h I get the following error:
unreferenced to `GenVar<double>::operator+(GenVar<double> const&)'
undefined reference to `GenVar<double>::operator=(GenVar<double> const&)'

This happens when it reaches:
Code
p = m+n;
q = p;

In GenVar.h I have the following code:
Code
template <class T>
class GenVar
{
    public:
        T a;
        T b;

    public:
        GenVar(void) : a(0), b(0) {}

        void operator=(const GenVar<T>& var);
        GenVar<T> operator+(const GenVar<T>& var);
};

And in GenVar.cpp I have the following code:
Code
#include "GenVar.h"

template <class T>
void GenVar<T>::operator=(const GenVar<T>& var)
{
    a = var.a;
    b = var.b;
}

template <class T>
GenVar<T> GenVar<T>::operator+(const GenVar<T>& var)
{
    GenVar<T> temp;
    temp.a = a + var.a;
    temp.b = b + var.b;
    return (temp);
}
These files are in the same directory as main.cpp.

I think it's a linking problem, but please help me out, I already don't have hair on my head, cause ripped it all off  :(
Thank you.

Offline oBFusCATed

  • Developer
  • Lives here!
  • *****
  • Posts: 13406
    • Travis build status
Re: Add files with classes to C::B
« Reply #1 on: February 01, 2010, 01:28:05 pm »
Not a C::B problem,
read more about C++ templates (hint: the templates are "header only" most of the time)
(most of the time I ignore long posts)
[strangers don't send me private messages, I'll ignore them; post a topic in the forum, but first read the rules!]

Offline Jenna

  • Administrator
  • Lives here!
  • *****
  • Posts: 7252
Re: Add files with classes to C::B
« Reply #2 on: February 01, 2010, 01:30:11 pm »
Not a C::B problem,

Therefore violating our forum rules.

Topic locked !