Vector of object pointers and virtual methods
First of all sorry if i've chosen wrong title, but wasn't sure how to name
it.
Code structure first:
//== 1st file ==
class A {
private:
int x;
public:
int GetX() { return x; }
}
//== 2nd file ==
class B {
private:
A ob1;
public:
virtual A & GetARef() { return ob1; }
}
class C : public B {
private:
A ob2;
public:
A & GetARef() { return ob2; }
}
class D : public B {
public:
// something else w/e
}
//== 3rd file ==
class E {
private:
std::map <UINT,C> m;
public:
C* GetCPtr(int idx) { retrun &m[idx]; }
}
//== 4th file ==
void foo(E & E_Obj) {
std::vector <B*> v;
v.push_back(D_Obj.GetCPtr(0));
v.push_back(/*some pointer to D class*/);
Boo(v); // FORGOT TO ADD IT ! Sorry
}
//== 5th file ==
void Boo(std::vector <B*> & v) {
std::cout << v[0]->GetARef().GetX(); // returns B::ob1 's x instead of
C::ob2 's x.
}
As wrote in comments, Boo gets wrong 'x'. I just wonder if it's because
that pointers go 'out of scope' or I misdesigned something wrong. How to
fix that, so I can get proper x (C::ob2 's one).
Sorry for kinda strange class names etc., but orginal code is much longer,
so I tried to show the situation only.
@edit Forgot to add that in Foo() it returns what i expect - C::ob2 's x.
No comments:
Post a Comment