Right now, I am learning the features of Inheritance in C++ and wanted to test out the recently learnt concept of Virtual Base classes. I tried the following simple code:
#include <iostream>
using namespace std;
class A
{
private:
int m_value;
string m_caller;
public:
A(int p_value, string p_caller) : m_value{p_value}, m_caller{p_caller}
{
cout<<"Instantiating A via "<<m_caller<<endl;
}
};
class B : virtual public A
{
private:
int m_value;
public:
B(int p_value1,int p_value2) : A{p_value1,"B"}, m_value{p_value2}
{
cout<<"Instantiating B."<<endl;
}
};
class C : public B
{
public:
C(int p_value1,int p_value2) : A{p_value1,"C"}, B(p_value1, p_value2)
{
cout<<"Instantiating C."<<endl;
}
};
int main()
{
C c1(1,2);
return 0;
}
Please note the B(p_value1, p_value2)
in the constructor of class C. This gave me the desired output:
Instantiating A via C
Instantiating B.
Instantiating C.
But, the moment I changed it to B{p_value1, p_value2}
, I got the following output:
Instantiating A via C
Instantiating A via B
Instantiating B.
Instantiating C.
I tried looking for the answer, but all the answers I got quoted some C++ standards. Being a beginner in OOPs, I am looking for a simpler explanation for this behaviour. Thanks a lot!
P.S. I am using C::B in Windows with compiler g++ 4.8.1.
Aucun commentaire:
Enregistrer un commentaire