Case 1:
class Dog {
public:
Dog()
{
cout << "Dog Born" << endl;
}
virtual void bark()
{
cout << "Dog barking" << endl;
}
void SeeCat()
{
bark(); // first it check bark() in YellowDog else invokes in Dog class
}
};
class YellowDog : public Dog
{
public:
YellowDog()
{
cout << "Yellow Dog Born" << endl;
}
virtual void bark() // virtual keyword is optional
{
cout << "Yellow barking" << endl;
}
};
int main() {
YellowDog d;
d.SeeCat();
}
Output:
Dog Born
Yellow Dog Born
Yellow Dog barking
Case 2: why Virtual function in constructor should be avoided
class Dog {
public:
Dog()
{
cout << "Dog Born" << endl;
bark(); Since construtor of yellowdog is not yet constructed, so bark of Dog class gets called.
}
virtual void bark()
{
cout << "Dog barking" << endl;
}
void SeeCat()
{
bark();
}
};
class YellowDog : public Dog
{
public:
YellowDog()
{
cout << "Yellow Dog Born" << endl;
}
virtual void bark()
{
cout << "Yellow Dog barking" << endl;
}
};
int main() {
YellowDog d;
d.SeeCat();
}
Output:
Dog Born
Dog barking
Yellow Dog Born
Yellow Dog barking
Case 3: why Virtual function in destructor should be avoided
public:
Dog()
{
cout << "Dog Born" << endl;
}
virtual void bark()
{
cout << "Dog barking" << endl;
}
void SeeCat()
{
bark();
}
~Dog()
{
bark(); // It invokes bark of Dog class because Yellow Dog is already been destructed.
}
};
class YellowDog : public Dog
{
public:
YellowDog()
{
cout << "Yellow Dog Born" << endl;
}
virtual void bark()
{
cout << "Yellow Dog barking" << endl;
}
};
int main() {
YellowDog d;
d.SeeCat();
}
Output:
Dog Born
Yellow Dog B
Yellow Dog b
Dog barking
Comments
Post a Comment