Here is the code:
#include <iostream>
#include <vector>
#include <array>
class Parent
{
public:
virtual void whatAmI(){std::cout << "A Parent" << std::endl;}
virtual long getValue(){std::cout << "value from Parent " << std::endl; return value;}
long value;
};
class Child : public Parent
{
public:
virtual void whatAmI(){std::cout << "A child" << std::endl;}
virtual long getValue(){std::cout << "value from Child " << std::endl; return value;}
long value;
};
class SomeClass
{
public:
Parent * parent;
};
int main()
{
Child c = Child();
SomeClass sc;
sc.parent = &c;
sc.parent->value = 10;
sc.parent->whatAmI();
std::cout << sc.parent->value << std::endl;
std::cout << sc.parent->getValue() << std::endl;
}
It returns:
A child
10
value from Child
0
I have read about object slicing, and made sure I would assign the value of 10 after the child has been sliced up. I still don't understand why the direct field access and the function call would give different results.
Thank you.