0

I'm having some trouble figuring out how to assign values to member data when calling a virtual function through a heterogeneous list.

Here's an example of what I'm trying to do:

class A
{
 protected:
 virtual void func1();

 private:
 A * list;
}

class B: public A
{
 protected:
 void func1();

 private:
 int i1, i2;
}

Within main():

list = new A[10];

list[0] = new B;

list[0]->Func1();

Declaration of Func1():

void B::Func1()
{
 int a, b;

 cin >> a >> b;

 list[0]->i1 = a;
 list[0]->i2 = b;

 // or can I just do this:
 // i1 = a;
 // i2 = b;
}

I'm looking for the appropriate way to access member data of a derived class within a function of the derived class if calling via a pointer of the parent class from main. Any help would be much appreciated!

Victor Brunell
  • 5,668
  • 10
  • 30
  • 46

1 Answers1

1

While executing a virtual function you now that the type of the object is the type of class the function is defined in or a class derived thereof. That is, in your B::func1() function you know this points to a B object. The object may be of a type derived fromB but you still have everything present in B.

On the other hand, you don't know statically that list[0] points to B object. The code you have uncommented in your code does not work. The commented code looks OK

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • I see. So the compiler doesn't know syntactically which object a pointer to the base class that has an object attached to it dynamically is pointing to until runtime? So I can't access member data of a non-base class through the arrow operator attached to a base class pointer? – Victor Brunell Nov 21 '13 at 18:57