I wrote a simple template class, which works fine, if the objects are created without using pointers. However if I need to create a pointer to that class object, I get error: invalid conversion from ‘int’ to ‘Logger<int>*’ [-fpermissive]. I am attaching the code below. Any help is appreciated.
Thank you.
#include <iostream>
using namespace std;
template<typename T>
class Logger
{
public:
Logger (const T& d) {data = d;}
void print(){std::cout << "data: " << data << std::endl;}
private:
int data;
};
int main() {
/*
// Works
Logger<int> myLogger(5);
myLogger.print();
*/
Logger<int>* myLogger(5);
myLogger->print();
return 0;
}
If you wanted to allocate a pointer you'd need to use new (and remember to delete it when it is no longer needed so you don't leak it).
Logger<int>* myLogger = new Logger<int>(5);
I don't know what your use case is for doing this, but if you really need to dynamically allocate the object, I'd recommend using smart pointers if you can.
std::unique_ptr<Logger<int>> myLogger = std::make_unique<Logger<int>>(5);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With