0

I was trying to create vector like class. Here is my code

#include <bits/stdc++.h>
using namespace std;

template<class t>
class vec{
    t *start;
    int size=0;
    public:
      void add_value(t a){
            *(start+(sizeof(t)*size)) = a;
            cout << (start+(sizeof(t)*size))<< " = "<< *(start+(sizeof(t)*size))<<endl;
            size++;
            // cout << start<< endl;
        }

        void operator [](int i){
            cout << (start+(sizeof(t)*i))<< " = "<< *(start+(sizeof(t)*i))<<endl;
        }
        int length(){
            return size;
        }
};

int main(){
    vec<int> t;
    cout << t.length()<<endl;
    t.add_value(8);
    t.add_value(10);
    cout << t.length()<<endl;
    t[1];
}

This gives me correct output.

0
0x7fff0fe9b5d0 = 8
0x7fff0fe9b5e0 = 10
2
0x7fff0fe9b5e0 = 10

But when declare a int variable in main function like.

int main(){
    int i=0;  //newline
    vec<int> t;
    cout << t.length()<<endl;
    t.add_value(8);
    t.add_value(10);
    cout << t.length()<<endl;
    t[1];
}

output.

0
Segmentation fault (core dumped)

I also tried printing address of start variable and new int variable int those are different.

cigien
  • 57,834
  • 11
  • 73
  • 112

1 Answers1

0

You probably want something like this:

#include <iostream>

using namespace std;

template<class t>
class vec {
  t* start = new t[100];   // initialize the pointer (fixed size of 100, to be improved)
  int size = 0;                                      
public:
  void add_value(t a) {
    *(start + size) = a;
    size++;
  }

  t operator [](int i) {   // should return a t instead of a void
    return *(start + i);
  }

  int length() {
    return size;
  }
};

int main() {
  vec<int> t;
  cout << "t.length() = " << t.length() << endl;

  t.add_value(8);
  t.add_value(10);

  cout << "t.length() = " << t.length() << endl;
  
  // display all values in t
  for (int i = 0; i < t.length(); i++)
  {
    cout << "t[" << i << "] = " << t[i] << endl;
  }
}

All multiplication by sizeof(t) have been removed, because pointer arithmetic already does this for you.

This very poor and minimalist example works as you expect, but the maximum number of elements you can store in the class is 100. I leave the improvement as an exercise to you.

BTW there are many other improvements you need to do, especially you need a destructor and possibly the rule of three

Note:

You should replace all instances of *(start + x) with start[x] which does exactly the same thing but which is more idiomatic and more readable.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • Hey, how is the size fixed to 100? I tried it and its working fine even if i replace 100 with 1 and try to add more values. – Sushant Chandla Nov 04 '20 at 16:23
  • 1
    @SushantChandla you're writing beyond allocated memory which will result in _undefined behaviour_ (google that term) which includes "apparently working fine" – Jabberwocky Nov 04 '20 at 16:25