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:
#include <iostream>
#include "pair.h"
#include "pair.cpp"
usingnamespace 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?
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)