virtual functions in virtual base class

S

sreelakshmi.rajula

Does it allow virtual functions in Virtual base class?
I am getting errors in the following code.Anything wrong in this code?I
want to print Eagle's age. Can anybody clarify my doubt?

class Animal
{
public:
Animal() { age = 0 ;}
virtual int GetAge() const { return age; }
private:
int age;
};
class Eagle : virtual public Animal
{
public:
int GetAge() { age = 4 ; return age; }
private:
int age ;
};
class Lion : virtual public Animal
{
public:
int GetAge() { age = 10 ; return age; }
private:
int age ;
};

class Griffin : public Eagle ,public Lion
{
};
int main()
{
Animal *animal = new Eagle();
animal->GetAge();
return 0 ;

}
 
A

amirkam1

virtual int GetAge() const { return age; }
This code should not give you any error, unless you remove const from
the GetAge method in most base class. As you have declared the function
to be const in base class but not in derived class, it is not
overriding.

Also the virtual inheritance does not resolve the error for ambiguous
functions. You need to override the function in the most derived
(Griffin) class and call the appropriate base version.
 
S

sreelakshmi.rajula

I am sorry. What you told is correct. Actually when I override GetAge()
function it'll give errors. But one more is how can I print Eagle's
age?
 
A

amirkam1

I am sorry. What you told is correct. Actually when I override GetAge()
function it'll give errors. But one more is how can I print Eagle's
age?

If the functions are overriden properly, then by means of virtual
mechanism the call to getAge will be resolved correctly. But in Griffin
class you will have to override the function and hardcode which version
of gateAge should be called (Eagle::getAge OR Lion::getAge()) to avoid
ambiguous error.
 
M

manish

use the following to print age
cout<<animal->GetAge();
in the main( )
instead of
animal->GetAge();
 
R

Richard

red floyd said:
Does it allow virtual functions in Virtual base class?
I am getting errors in the following code.Anything wrong in this code?I
want to print Eagle's age. Can anybody clarify my doubt?
[code redacted]

What errors are you getting? What were you expecting? Read FAQ
5.8. http://www.parashift.com/c++-faq-lite/how-to-post.html#faq-5.8

Why dont you just write a bot to post your "OT" responses? It would save
you a lot of time. In about 20 posts you have added help possibly once :
in all the rest you are "OT"ing and referring to netiquette
documents.

You clearly have a very high opinion of yourself.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top