Using constructors in template class

The code below references to a header file and implementation .cpp file, which are not important. My question is what is the proper way to use a constructor in a main file. I have been getting "invalid use of" errors when using letters.Pair(a,b), where Pair(T a, T b) is a constructor that accepts arbitrary type T of variables 'a' and 'b'. So I played around a bit and suddenly found a syntax that works. I need verification for the syntax below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include "pair.h"
#include "pair.cpp"

using namespace std;
int main()
{
        char a = 'a', b = 'b';
	
        //Pair is a template class. Pair(T a, T b) is a constructor.

	Pair<char>letters(a, b);// *You initialize with constructors using this?

        //setFirst and setSecond are Pair class functions.

	letters.setFirst('t');// *You assign with functions using this? 

	letters = Pair<char>(a, b);// *You assign with constructors using this?

	cout << letters.getFirst() << ' ' << letters.getSecond();



	return 0;

}



Are the comments with the asterisks correct? As in this is always the way you initialize and assign? So letters.Pair(a, b) is not the right way to use constructors?
Last edited on
You can only use constructor when creating object and cannot call them arbitrary. In your case letters.Pair(a, b) letters is already constructed. There is nothing left to construct.

Line 18 in C++11 could be: letters = {a, b};

Last thing:
a) Never include implementation file in another file.
b) All templated functions should be defined in headers. If you have templated class, you do not need implementation file, your class will be header only (look into standard STL headers)
You have a problem with your includes...

DELETE #include "pair.h"

You have that line inside your pair.cpp file.

You only ever include the .cpp file of which ever class you are looking to import into the file that you are working on.

EDIT:

Well thats embarrassing...What I said was completely backwards...Delete the .cpp file you only include header files...never the .cpp!!!

So
DELETE #include "pair.cpp"

Don't know what kinda drugs influenced me to say the other way around haha..
Last edited on
Topic archived. No new replies allowed.