Hi
I am reading about virtual functions.I understand virtual functions that:
* A member function of a class
* Declared with virtual keyword
* Usually has a different functionality in the derived class
* A function call is resolved at run-time
but i don't understand its mechanism.Especially late binding or pointer assignment(from derived to base class).This is code:
Code:
class Window // Base class for C++ virtual function example
{
public:
virtual void Create() // virtual function for C++ virtual function example
{
cout <<"Base class Window"<<endl;
}
};
class CommandButton : public Window
{
public:
void Create()
{
cout<<"Derived class Command Button - Overridden C++ virtual function"<<endl;
}
};
void main()
{
Window *x, *y;
x = new Window();
x->Create();
y = new CommandButton();
y->Create();
}
The output of the above program will be,
Base class Window
Derived class Command Button
Here when we remove virtual.
The output of the above program will be,
Base class Window
Base class Window
I want to learn What is happening in that line:y = new CommandButton();
We assign a commandbutton object to y but if we don't write virtual before function ,it calls base class's function.If we write virtual it calls derived class's func.
I don't understand this assignment.doesn't new operator return object's address?So what happened behind the code?
I hope i can explain my problem.I am really confused.
Any help will be greatly appreciated.