gman
gman

Reputation: 157

Problem with c++ template constructor

code:

#include<iostream>

using namespace std;

template<class T, int N> class point {
    T coordinate[N];
public:
    point(const point<T,N>&);
    const double& operator[](int i) const {
        return coordinate[i];
    }
};

template<class T, int N> point<T,N>::point(const point<T,N>&p)
{
    for(int i=0;i<N;i++)
        coordinate[i]=p.coordinate[i];
};

int main() {
    point<int,2> P2;
    point<double,3> P3;
    cout<<P2[0]<<P3[1];
    return 0;
}

output:

prog.cpp: In function ‘int main()’:
prog.cpp:17: error: no matching function for call to ‘point<int, 2>::point()’
prog.cpp:11: note: candidates are: point<T, N>::point(const point<T, N>&) [with T =
             int, int N = 2]
prog.cpp:18: error: no matching function for call to ‘point<double, 3>::point()’
prog.cpp:11: note: candidates are: point<T, N>::point(const point<T, N>&) [with T =
             double, int N = 3]
prog.cpp: In member function ‘const double& point<T, N>::operator[](int) const [with
          T = int, int N = 2]’:
prog.cpp:19:   instantiated from here
prog.cpp:8: warning: returning reference to temporary

Please help me sort out the faults.

Upvotes: 4

Views: 1939

Answers (3)

iammilind
iammilind

Reputation: 70096

When you declare a variable something like,

point<int,2> P2;

It uses default constructor; it can be used in 2 scenarios:

  1. You haven't declared ANY constructor in your class body. Thus compiler will generate a default one automatically and you can use it.
  2. You declare/define a default constructor explicitly (be it empty, if you don't do anything)

Since here you don't do anything: just declare an empty default constructor:

template<class T, int N> class point {
//...
public:
  point() {}  // <-- default constructor
};

This will clear your errors.

Also there is an Important Warning:

prog.cpp:8: warning: returning reference to temporary

That is because of your operator []. Change the line,

const double& operator[](int i) const

To,

const T& operator[](int i) const  // for <int, N> you should return 'int' not 'double'

Upvotes: 1

Ken Wayne VanderLinde
Ken Wayne VanderLinde

Reputation: 19347

The problem is that with these two lines

point<int,2> P2;
point<double,3> P3;

you are attempting to create two 'point' object via the default parameterless constructor.

However, this constructor is not automatically generated unless you do not specify any others. Implementing the default constructor will solve you problem

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249642

The compiler-generated default constructor is not being provided because you have created a constructor of your own. Therefore when you create P2 with no arguments to its constructor, you need to define a default constructor for it to compile.

Upvotes: 5

Related Questions