1

I have a class which has overloaded the array index operator[]. Now I have to create a pointer to that class, How can I use index operator [] using pointer to the class. Following code works fine, but if i un-comment the basicVector * a = new basicVector(10) line and put -> in place of ., I get errors.

Please see this link for compiler settings and code.

#include <iostream>       // std::cout
#include <queue>          // std::queue
#include <string>
#include <string.h>
#include <stdint.h>
#include <vector>

using namespace std;
class basicVector
{
private:
    uint32_t array_size;
    uint8_t * array;
public:
    basicVector(uint32_t n);
    ~basicVector();

    uint32_t size();
    uint8_t * front();
    uint8_t& operator[](uint32_t i);
};

basicVector::basicVector(uint32_t n)
{
    array_size = n;
    array = new uint8_t[n];
}

basicVector::~basicVector()
{
    delete [] array;
}

uint32_t basicVector::size()
{
    return array_size;
}

uint8_t * basicVector::front()
{
    return array;
}

uint8_t& basicVector::operator[](uint32_t i)
{
    return array[i];
}

int main ()
{   //basicVector * a = new basicVector(10);
    basicVector a(10);
    cout <<a.size()<<endl;

    for(uint8_t i=0; i < a.size(); i++)
    {   a[i] = i+50;    //how to do this correctly when "a" is pointer?
    }

    uint8_t * b = &a[3];    //how to do this correctly when "a" is pointer?
    *b = 45;

    for(uint32_t i=0; i < a.size(); i++)
    {   cout<<a[i]<<endl;   //how to do this correctly when "a" is pointer?
    }
    return 0;
}
2
  • 1
    Well, since it's a pointer you need to dereference it first. So: (*a)[i] = i+50; Commented May 7, 2018 at 14:18
  • Either (*a)[i] or a->operator[](i). Commented May 7, 2018 at 15:44

1 Answer 1

3

With the following declaration:

basicVector *a = new basicVector(10);

You could dereference the pointer (preferred):

uint8_t n = (*a)[5];

Or call the operator using the operator syntax:

uint8_t n = a->operator[](5);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.