Polymorphism: member acces and getter give different results

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 read about trimming objects and making sure that I assign a value of 10 after the child is sliced. I still do not understand why direct access to the field and calling the function give different results.

Thank.

+4
source share
1 answer

There is no slicing - you get access through a pointer.

The behavior is that access to a member variable is not polymorphic. Therefore, it parent->valuealways refers to Parent::value, never Child::value. While value(c Child::getValue) refers to Child::value.

+6
source

Source: https://habr.com/ru/post/1673522/


All Articles