Please tell me why the output is as below for the following program. I am not getting the virtual classes in c++. observe the below code:
class B
{
public:
B(char c = 'a') : m_c(c) {}
public:
char get_c() const { return m_c; }
void set_c(char c) { m_c = c; }
private:
char m_c;
};
class C: public B
{ };
class D: public B
{ };
class E
: public C
, public D
{ };
int main()
{
E e;
C &c = e;
D &d = e;
std::cout << c.get_c();
d.set_c('b');
std::cout << c.get_c() << std::endl;
return 0;
}
O/P: aa
I expect output would be ab. What would be the reason for getting “aa”??
If i have c.set_c(‘b’) instead of d.set_c(‘b’) then I will get O/P : “ab”, Here also, I am not getting why is it as such. Both c, d are referring to one object only.
class C:virtual public B{};
class D:virtual public B{};
If the class C, class D are inherited virtually from B, then
O/P would always be “ab”
consider
class C : public BandC* c = new Cthencpoint to an storage that begin with aBsinceC*is alsoB*. and this istrueforclass D : public B.Now for
class E : public C, public DandE* e = new E(). memory ofeis something like:as you can see in above case we have 2 instance of
Bone forCand another forDand now it is obvious when you call((D*)e)->set_c( 'b' )you only changeBinstance ofDandBinstance ofCwill remain unchanged.now when you say
class C : public virtual B, C++ shareBinstance with any other class that virtually inherit fromB. so in this caseeis something like:and as you can see we have only one
Bso calling((C*)e)->set_cand((D*)e)->set_cwill both act on sameB.