Re: Help regarding virtual function.
<trialproduct2004@yahoo.com> wrote in message
news:1146027134.773196.302380@v46g2000cwv.googlegroups.com...
Hi all,
Can someone tell me how virtual functions works.
Like how memory is getting allocated to virtual function.
It's implementation dependant, but usually (if not always) you only have one
copy of the function in the executable. That's why methods usually don't
add to an objects size.
On my system this program outputs
4 4
#include <iostream>
#include <string>
class Class1
{
int i;
};
class Class2
{
int i;
void Output() { std::cout << i; };
};
int main ()
{
std::cout << sizeof(Class1) << " " << sizeof(Class2);
std::string wait;
std::cin >> wait;
}
Methods do not usually add to a class's size for storage. They are just an
executable function in the executable usually called through some lookup
table.
And how to
call base class function through derived class pointer.
Study the output of this program.
#include <iostream>
#include <string>
class Base
{
public:
virtual void Output() { std::cout << "Base" << std::endl; };
};
class Derived: public Base
{
public:
void Output() { std::cout << "Derived" << std::endl; Base::Output(); };
};
int main ()
{
Derived Instance;
Base* BaseP = &Instance;
std::cout << "Derived call of Output()" << std::endl;
Instance.Output();
std::cout << "Base Pointer call of Output()" << std::endl;
BaseP->Output();
std::cout << "Base Pointer call of Base::Output()" << std::endl;
BaseP->Base::Output();
std::string wait;
std::cin >> wait;
}
Output:
Derived call of Output()
Derived
Base
Base Pointer call of Output()
Derived
Base
Base Pointer call of Base::Output()
Base
And why virtual function can be access only through pointer.
Look at the above program. As you see, Instance which is an instance of the
derived class has it's virtual function accesed and it's not a pointer.
What do you mean?