| View previous topic :: View next topic |
| Author |
Message |
Guest
|
Posted: Mon Aug 21, 2006 9:10 am Post subject: virtual functions in virtual base class |
|
|
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 ;
} |
|
| Back to top |
|
 |
red floyd Guest
|
Posted: Mon Aug 21, 2006 9:10 am Post subject: Re: virtual functions in virtual base class |
|
|
sreelakshmi.rajula (AT) gmail (DOT) com wrote:
| Quote: | 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 |
|
| Back to top |
|
 |
Guest
|
Posted: Mon Aug 21, 2006 9:10 am Post subject: Re: virtual functions in virtual base class |
|
|
| Quote: | 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. |
|
| Back to top |
|
 |
manish Guest
|
Posted: Tue Aug 22, 2006 9:10 am Post subject: Re: virtual functions in virtual base class |
|
|
use the following to print age
cout<<animal->GetAge();
in the main( )
instead of
animal->GetAge(); |
|
| Back to top |
|
 |
Ian Collins Guest
|
Posted: Tue Aug 22, 2006 9:11 am Post subject: Re: virtual functions in virtual base class |
|
|
manish wrote:
| Quote: | use the following to print age
cout<<animal->GetAge();
in the main( )
instead of
animal->GetAge();
What are you replying to? |
--
Ian Collins. |
|
| Back to top |
|
 |
|