Once again I need to do something like this -
I need to initialize first the vector, so I pass its data() address to the parent class.
#include <vector>
struct A{
A(int *a) : a(a){}
int *a;
};
struct B : A{
B() : A( v.data() ){}
std::vector<int> v { 1024 };
};
#include <cstdio>
int main(){
B b;
b.v[55] = 5;
printf("%d\n", b.a == b.v.data() );
printf("%d\n", b.a[55]);
printf("%d\n", b.v[55]);
}
Problem here is that the vector is initialized after parent class and v.data() contains junk. I am even surprised this compiles.
I know I can use composition / decorator for this or protected member setPtr(int *a), but I wonder if there is another way to do it.
Please do not comment about raw pointers. This is just an example for dependencies between parent and child classes.
Aucun commentaire:
Enregistrer un commentaire