Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why i am getting error while executing with the following code?

Technique 1 -> Results in error

I have three files MyType.h, MyType.cpp & main.cpp

MyType.h

#ifndef MYTYPE_H
#define MYTYPE_H

#include<iostream>
using namespace std;

template <class T,int iMax>

class A{
    T iData;
public:
    void vSetData(T iPar1);
    void vDisplayData();
};
#endif

MyType.cpp

#include"MyType.h"

void A::vSetData(T iPar1){
    if(iPar1 <= iMax)
        iData = iPar1;
}
void A::vDisplayData(){
    cout<<"\nData is: "<<iData<<endl;
}

main.cpp

#include"MyType.h"

typedef A<int,20> MyType;

int main(){
    int x = 12;
    MyType obj;
    obj.vSetData(12);
    obj.vDisplayData();
    return 0;
}

ERRORS: 10 errors. They are as follows:-

  • mytype.cpp(2) : error C2955: 'A' : use of class template requires template argument list
  • mytype.h(9) : see declaration of 'A'
  • mytype.cpp(2) : error C2955: 'A' : use of class template requires template argument list
  • mytype.h(9) : see declaration of 'A'
  • mytype.cpp(2) : error C2065: 'T' : undeclared identifier
  • mytype.cpp(2) : error C2146: syntax error : missing ')' before identifier 'iPar1'
  • mytype.cpp(2) : error C2761: 'void A::vSetData(T)' : member function redeclaration not allowed
  • mytype.cpp(2) : error C2059: syntax error : ')'
  • mytype.cpp(2) : error C2143: syntax error : missing ';' before '{'
  • mytype.cpp(2) : error C2447: '{' : missing function header (old-style formal list?)
  • mytype.cpp(6) : error C2955: 'A' : use of class template requires template argument list
  • mytype.h(9) : see declaration of 'A'
  • mytype.cpp(6) : error C2509: 'vDisplayData' : member function not declared in 'A'
  • mytype.h(9) : see declaration of 'A

Technique 2 -> Works fine.

AboveCodeInOneFile.cpp

#include<iostream>
using namespace std;

template <class T,int iMax>

class A{
    T iData;
public:
    void vSetData(T iPar1){
        if(iPar1 <= iMax)
            iData = iPar1;
    }
    void vDisplayData(){
        cout<<"\nData is: "<<iData<<endl;
    }
};

typedef A<int,20> MyType;

int main(){
    int x = 12;
    MyType obj;
    obj.vSetData(12);
    obj.vDisplayData();
    return 0;
}

Please let me know what mistake i am doing in Technique 1

like image 443
Abhineet Avatar asked Aug 07 '26 14:08

Abhineet


1 Answers

When defining a template class, the method definition must be seen by the compiler. So they have to be in the header file.

Edit

You have to include the method implementation, so it's seen by the compiler. You can do it by including them from another `MyType_impl.h" file:

template <class T, int iMax>
void A<T, iMax>::vDisplayData()
{
  cout<<"\nData is: "<<iData<<endl;
}
like image 109
René Richter Avatar answered Aug 10 '26 09:08

René Richter