Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to a template class

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;
}
like image 378
Geek Avatar asked Jun 19 '26 04:06

Geek


1 Answers

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);
like image 96
Cory Kramer Avatar answered Jun 20 '26 20:06

Cory Kramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!