Reputation: 369
I'm trying to create a custom vector class and overloading all operators. consider the following code:
template <class T>
class vector{
private:
T * arrayOfObj;
// other class members
public:
Vector(){
arrayOfObj = new T[100];
}
vector(int size);
// other functions for vector class, overloaded [], =, etc.
}
in another class, I need to return the vector but with a pointer like when we return an array:
#include "B.h"
class c {
vector<B> vect;
public:
B * getArray(){
return vect;
}
First, is it possible to retrun a vector like an array? Also, if I wanted to access the dynamic array encapsulated inside the vector class without using a public function to return the array, how should be my approach?
Upvotes: 2
Views: 275
Reputation: 22269
First, is it possible to retrun a vector like an array?
Sure, that's what std::vector::data()
does. It's as simple as doing return arrayOfObj;
in whatever method or operator overload.
Also, if I wanted to access the dynamic array encapsulated inside the vector class without using a public function to return the array, how should be my approach?
Not possible. Either you allow access to your internal storage via a public function or you don't allow that, your choice. In c::getArray()
you could also copy all elements of vect
into a new array - this way noone will alter vect
from the outside and you don't have to provide access to internal storage of vector
class.
There is also friend
mechanism that allows one function or class to access private members of another class, but it's usually worse than public access.
Upvotes: 3