I’ve a class with template:
template<class T> class MyClass {
public:
MyClass() { _genericObj = new T; }
~MyClass() { delete _genericObj; }
void doSomething() { _genericObj.do(); }
private:
T* _genericObj;
};
And another class:
class AnotherClass {
public:
AnotherClass(MyClass &obj) { this->_obj = obj; }
~AnotherClass() { }
doMagic() { _obj->doSomething(); }
private
MyClass* _obj;
}
Is it right to use in AnotherClass an instance of MyClass without angular parenthesis (for generality)?
If this example is wrong, how can I correct my code? Thank u so much.
You have to decide whether you need a concrete type, by specifying a template parameter for
MyClass, or whether you wantAnotherClassto be a class template too. You also have the problem that you are passing a reference to some kind ofMyClassin the constructor, but you are trying to initialize a pointer to it. The way to fix that really depends on what you want to achieve, these examples assume yourAnotherClasswill own a dynamically allocated object of typeMyClass<SomeType>:or
Note that in C++ names starting with an underscore are reserved for the implementation, so I have changed
_objforobj_.