Embedded_Dude
Embedded_Dude

Reputation: 227

Virtual Functions Doubts

I have this simple code to test VF

class A
{
public:
virtual const char Get (){return 'A';}
};

class B : public A
{
public:
const char Get (){return 'B';}
};

class C : public B
{
public:
const char Get (){return 'C';}
};

class D : public C
{
public:
const char Get (){return 'D';}
};

inside main ()

D dD;
std::cout<<dD.Get()<<std::endl; //prints D

A & rA = dD;
std::cout<<rA.Get()<<std::endl;//prints D

C cC;

A & rA2 = cC;
std::cout<<rA2.Get()<<std::endl; //print C

B & rB = dD;
std::cout<<rB.Get()<<std::endl;
/*????? it prints D, shouldn't it print B ?????*/

rB points to address dD, rB will only refer to the object (B and A) of the dD object (won't see C&D).

When rB.Get () is called, shouldn't it goes to the most derived function which is in B, not in A and execute it?

Upvotes: 1

Views: 73

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145457

When a function is virtual in a class Base it's virtual in all derived classes, classes derived from derived classes, and so on, regardless of the use or not of the word virtual in the derived classes.

In your case this means that Get is virtual in all your classes A, B, C and D. Hence the cases rA and rB are examples of the same kind of situation.

The return type can vary slightly: a raw reference or pointer as return type can be specialized in a derived class. Since it then varies in specificity in the same direction as the containing class it's called a covariant return type. C++ does not, however, support variance of arguments.

Upvotes: 1

Related Questions