A few days ago, I wanted to dive into the C++ world. I'm studying the base and derived class concepts. Could someone explain the nuance going on with the following two code snippets?
class A
{
private:
virtual int GetValue() { return 10; }
public:
int Calculate() { return GetValue()*1.5; }
};
class B: public A
{
private:
virtual int GetValue() { return 20; }
};
int main()
{
B b;
std::cout << b.Calculate() << std::endl;
return 0;
}
The output is 30 but 15 was expected
class A
{
private:
int m_data;
public:
A(): m_data(GetValue()) {}
int Calculate() { return m_data*1.5; }
virtual int GetValue() { return 10; }
};
class B: public A
{
public:
virtual int GetValue() { return 20; }
};
int main()
{
B b; A* ap;
ap=&b;
std::cout << ap->Calculate() << std::endl;
return 0;
}
The output is 15 but 30 was expected
Can someone explain and help me understand the reasoning? Something is wrong with my thinking on this concept, but I am unable to figure it out.