Overloading the Subscript[] operator in C++ to set the size of a class(quantifier).

282 views Asked by At

Good day guys.

I have the following struct and class,

template <class T>
struct Node
{
    T DataMember;
    Node* Next;
};

template <class T>
class NCA
{
    public:
        NCA();
        ~NCA();
        void push(T);
        T pop();
        void print();
        void Clear();
    private:
        Node<T>* Head;
        void* operator new(unsigned int);
};

I would like to instantiate the class with a size

ie. NCA[30] as one would any array

4

There are 4 answers

0
Mark Ransom On BEST ANSWER

If the compiler were to allow you to use brackets in your object constructor, how would it know whether you were trying to make an NCA of size 30 or an array of 30 NCA objects? C++ does not allow you to override the bracket syntax, except as an operator once you already have an object.

1
PlasmaHH On

You can't.

You can only use the ctor to do it like:

NCA n(30);
1
Flexo On

That's not quite how operator[] works.

When you write NCA[30] you're writing type[30], where as to use operator[] you need an instance:

NCA inst;
inst[30];

What you can do though is use an integer template parameter to specify the size, e.g.:

#include <utility>

template <std::size_t N>
class NCA {
  char bytes[N];
};

int main() {
  NCA<1024> instance;
}
1
Robᵩ On

You can't. But, you can do something almost like that: initialize it with parenthesis, but not brackets:

NCA<int> myList(30);

Implement it like so:

template <class T>
class NCA
{
  ...
  public:
    explicit NCA(std::size_t count);
  ...
 };

template <class T>
NCA<T>::NCA(std::size_t count) {
  ... allocate Head, &c ...
  while(count--)
    push(T());
}