virtual keyword in C++
Code:
class A {
public:
void hello() { std::cout << "Hello from A." << std::endl; }
};
And a derived class B:
Code:
class B : public A
{
};
You can create a B object and call the hello method.
Code:
B b;
b.hello();
The output will be "Hello from A." But you want to override the hello method. You'll write:
Code:
class B : public A
{
public:
void hello() { std::cout << "Hello from B." << std::endl; }
};
Now the output of b.hello() will be "Hello from B." But one of the advantages of inheritance is that you can pass a B object to a funcion that expects a pointer to A.
Code:
void say_hello(A* a)
{
a->hello();
}
say_hello(&b); // It's OK to do this.
The output will be "Hello from A," because A's hello function is being called. However, if A's hello function were virtual:
Code:
class A
{
public:
virtual void hello() { std::cout << "Hello from A." << std::endl; }
};
Then the output of say_hello(&b) would have been "Hello from B." Think of virtual functions as pointer to functions that can be overridden by derived classes and will work even when the derived object is passed (as a pointer) to a function that expects an object from the base class.
An Example:-
#include<iostream>
using namespace std;
class base
{
public:
int x;
base()
{
cout<<"inside base const\n";
}
};
//declaring both classes to be derived as virtual to prevent multiple copies of base to be inherited
class base1:virtual public base
{
public:
base1()
{
cout<<"inside base1 const\n";
}
};
class base2:virtual public base
{
public:
base2()
{
cout<<"inside base2 const\n";
}
};
class child:public base1,public base2
{
public:
child()
{
cout<<"inside child const\n";
}
};
int main()
{
child ch;
cout<<ch.x;
return 0;
}
Comments