0

I have templated class vector<typename T,size S> (I have to use this instead of std::vector). I would like to specify an alias which is in type ofvector<double,2> , but I also need to count the amount of all created and all currently live objects of this. Here's fragment of my templated class:

template<typename T, size S>
class vector{
  private:
    T *_values;
  public:
    vector():
      _values(new T[S]){
        for(int i =0; i < S; i++)
          _values[i] = T();
    }
    ~vector(){
      delete[] _values;
    }
};

So I thought about creating class named vector2D which inherits vector<double,2> and with two additional static variables to count its amounts. But how to do that? How to invoke superclass constructor and destructor so that it only contains incrementation/decrementation of these two static variables? vector2D is going to be used often in project I have to do. Maybe there is better solution?

P.S How to pretty initialize *_values? I tried *_values = { 0 } but it didn't work (of course assuming this is going to be a table of primitive types).

3
  • 1
    Is your question really just "how to invoke the parent's class constructor in the child class"? It's a little hard to reconciliate the need for re-inventing basic libraries with not being familiar with something this basic, so I suspect I'm missing something here.
    – user4442671
    Commented Apr 22, 2018 at 21:29
  • "but I also need to count the amount of all created and all currently live objects of this." Why? Commented Apr 22, 2018 at 23:20
  • These are my homework for programming course, so we invent wheel again just to see how does it works. Later we'll just use already invented solutions.
    – pjoter
    Commented Apr 23, 2018 at 10:50

1 Answer 1

1

I would like to specify an alias which is in type of vector<double, 2>

Well that's simple:

typedef vector<double, 2> vector2D

but I also need to count the amount of all created and all currently live objects of this.

That's simple as well. Here's a small example:

#include <iostream>

template <typename T, int S>
class vec {

    public:

    vec() {
        ++obj_counter;
    }

    static int obj_counter;

};

template <typename T, int S>
int vec<T, S>::obj_counter = 0;

typedef vec<double, 2> vec2d;

int main() {

    vec<int, 1> intvec1;
    vec<int, 1> intvec12;
    vec2d doublevec2;

    std::cout << vec2d::obj_counter << std::endl;

    return 0;
}

The advantage of this is the fact that obj_counter works for every type. In the above example if you type:

std::cout << vec<int, 1>::obj_counter << std::endl;

It will print 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.