thedarkside ofthemoon
thedarkside ofthemoon

Reputation: 2291

C++: Could polymorphic member remains the same?

I have a class that has a member that is an instance of another class that has a vector as member; like here:

class C1
{
private:
  std::vector<int> m_intVec;
  // ...
};

and

class C2 : public I1 // this is an interface
{
private:
  C1 m_c1;
  // ...
public:
  void getC1(C1& c1Out) const
  {
    c1Out = m_c1
  }
};

The interface looks like this:

class I1
{
public:
  virtual ~I1() {}
  virtual void getC1(C1& c1Out) const = 0;
};

I call the C2 class using polymorphism:

int main(int argc, char** argv)
{
  // ...
  I1* i1 = new C2;
  // ...
  while (1)
  {
    // set the member c1 // this is not happening all the time
    // ...
    C1 c1Obj; 
    i1->getC1(c1Obj);
    // ...
  }
  // ...
}

My questions here are: Could c1Obj have the value in the previous iteration? (in other words: Can the i1's member have the same value as previous iteration, if it was not reset?) If yes, can someone explain it to me why? any ideas how to fix this?

If the answer is no, why for some cases I get the same results: I am blurring a region in images, and in some cases the blurred region is the same as previous, and I do not know if it is a bug, or not.

Upvotes: 0

Views: 55

Answers (1)

Rakib
Rakib

Reputation: 7625

NO, this is not possible. c1Obj is guaranteed to be created each time in the loop, and destroyed once the loop scope ends. You are doing it wrong:

I1 i1 = new C2;

should be

I1* i1 = new C2;

and

 i1.getC1(c1Obj);

should be

 i1->getC1(c1Obj);

Note: i1 (actually c2) will contain same m_c1 object, so ater i1->getC1(c1Obj); statement, c1Obj will be always same.

Upvotes: 1

Related Questions