简体   繁体   中英

Heterogeneous Lists, Virtual Functions, and Member Data

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!

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 from B 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM