I have got the following code
#include <iostream>
#include <string>
template <typename T>
class demo
{
T data;
public:
demo();
demo(demo const&k );
demo(const T&k);
demo& operator=(const demo &k);
template<typename T1>
demo(const demo<T1>&k);
template<typename T1>
demo<T>& operator=(const demo<T1>&k);
~demo();
};
template <typename T>
demo<T>::demo():data(){}
template<typename T>
demo<T>::demo(demo const& k):data(k.data){}
template<typename T>
demo<T>::demo(const T&k):data(k){}
template<typename T>
demo<T>& demo<T>::operator=(demo const &k)
{
if ((void*)this == (void*)&k) { // assignment to itself?
return *this;
}
this->data=k.data;
return *this;
}
template<typename T>
template<typename T1>
demo<T>& demo<T>::operator=(demo<T1> const &k)
{
if ((void*)this == (void*)&k) { // assignment to itself?
return *this;
}
this->data=k.data;
return *this;
}
template<typename T>
template<typename T1>
demo<T>::demo(const demo<T1>&k):data(k.data){}
template<typename T>
demo<T>::~demo(){}
int main()
{
demo<std::string> k(std::string("hello"));
demo<std::string >l=k;
demo<int> x(10);
demo<double> p=x; //error here
}
Why do I get error here? As far as I know p
is being copy initialized to x
. So
demo<T>::demo(const demo<T1>&k):data(k.data){}
is invoked. But since data
is a private member I get an error 'demo<T>::data' : cannot access private member declared in class 'demo<T>'
. Why?
I know that member functions of a class can access private members , so why do I get an error? What should I do to correct the error?