Problem retrieving vector elements from another class

Hello everyone.

I have a class where I create a vector of class objects in a class, I created a public getter function like this

in Class A.cpp (this class has its respective get functions to access the objects contents)
1
2
3
const vector <Class A>& Class A::getVector () {
      return vector;
}


Then in my Class B I create a vector of objects of Class A and try to retrieve contents created in A

Class B.h
1
2
3
4
5
6
7
Class B {
private:
	vector <Class A> vectorB;
public:
	Class B();
	virtual ~Class B();
};


Class B.cpp
1
2
3
4
5
6
7
8
9
10
Class B::Class B() {
	Class A a ;
	vectorB = a.getVector();
	cout << vectorB[0].getValue() << endl;

}

Class B::~Class B() {

}


When I try to print the first element of the vector to see if I accessing its content, my program falls, it does not give an error, but debugging says it could not access to that value. The first couple of times worked and printed the value, but later started to fail.

Why is failing and how can I access it?
It's hard to say what the problem is when we don't see any real code.

Note that you are copying the vector on line 3 in "Class B.cpp". A::vector and B::vectorB are two different vectors so modifying one of them will have no effect on the other.

The variable a is a local variable inside the constructor so it will not exist after the constructor has ended, so I hope you are not keeping any references to a or to the vector returned by a.getVector().
Well, that is part of my real code, I just do not want to copy everything from class A since that class is working fine.

My problem comes in class B, because I just need to read the vector, I do not need to modify its contents, that is why function in class A is const.

If I use vectorB.at(0).getValue(), is says Throw an instance out of range.
Looks like the vector is empty.

The at function throws a std::out_of_range if the index is not valid.
http://www.cplusplus.com/reference/vector/vector/at/

If you use operator[] there are no such checks so if the index is invalid the behaviour is undefined, which means anything could happen.
Last edited on


The weird thing is that I call it from the main and it works, and the vector from class A is populated and print its contents.

Why it works from main???
I solved.

I created a instance from Class A in the main and call the functions to populate the vector and print it, in this way the vector is retrieved when I called from the Main.

The second way to get it work, but from class B, like the original, is call constructor of Class A in the Main, inside that constructor are the calls to the methods for fill and print the vector.

Thank you Peter87
Topic archived. No new replies allowed.