I wish for a class A to contain some data, and class B will contain a pointer to that data. I am providing access to the data through a function returning a reference to the data object A. If I create an object B then i can access the object A, however if create a pointer to B then the equivalent operation produces a segmentation fault. Like this:
#include <iostream>
#include <vector>
class A {
public:
A(const int pInt) {mInt = pInt;}
void print() {std::cout << mInt << std::endl;}
private:
int mInt; //some data
};
class B {
public:
B() {mP1 = new A(1);} //initialise to 1
~B() {delete mP1;}
A& access() {return *mP1;} //return reference to the data
private:
A* mP1; //pointer to some data
};
int main() {
B vB;
vB.access().print(); //this works.
B *vBptr;
vBptr->access().print(); //Segmentation fault!
std::vector<B*> vVec;
vVec.resize(1);
vVec[0]->access().print(); //Segmentation fault!
}
I guess when creating B *vBptr then a B object is not getting initialised?
How then could I create a vector of pointers to B objects that are automatically initialised?
Cheers.
Two issues in your program
Your pointer has not been initialized, and though its a pointer of type B but is not pointing to a valid object of type B. Change it to
Here resizing does not allocate the storage for each of the elements of the vector. You can initialize the elements with the actual object by supplying the initialization to the resize method of the vector