Trian Etymes
Trian Etymes

Reputation: 69

C++ Pointer as a member of template class

I'm very new to Template Class and Template Function. So this time I tried to create my own Nullable class, that allows any object to have value, or null value.

template<typename _Type>
class Nullable
{
private: 
    _Type *_Pointer
public:
    Nullable::Nullable(const _Type &x)
    {
        this->_Pointer = new _Type(x);
    };

However, when I compile it, it returns me 2 errors:

at the line of the constructor above.

So please explain to me how to write a constructor correctly for Template class. And is it recommended to use Pointer as a member of Template Class? Thanks in advance.

Upvotes: 0

Views: 95

Answers (1)

R Sahu
R Sahu

Reputation: 206747

Problem 1

You are missing a ; in the line:

_Type *_Pointer;
              ^^ missing

Problem 2

When a constructor is defined inline, you can't use the scope operator.

Change

Nullable::Nullable(const _Type &x) { ... }

to

Nullable(const _Type &x) { ... }

A nitpick

You don't need the ; at the end of the constructor definition.

Nullable(const _Type &x)
{
    this->_Pointer = new _Type(x);
};
 ^^ Remove it.

It is not an error to have it there but it is not needed.

Upvotes: 3

Related Questions