473,406 Members | 2,220 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Virtual method implementation in C++

Dear all,
I am trying to underlying implementation of virtual functions in C++.
The way I understand polymorphism is

class Base
{
public:
virtual int func();
};

class Derived: public Base
{
public:
virtual int func();
}

int Base::func()
{
printf("In Base\n");
}

int Derived::func()
{
printf("In Derived\n");
}

void poly_func(Base * x)
{
x->func();
}
int main()
{
Derived ob1;
poly_func(&ob1);
}

Output :

This will call the function in the derived class instead of the base
class due to the virtual keyword in the base class with func().


Now my question is how does C++ implement such mechanism.
I read something about VTables in C++, that every class has a
different VTable which contain the appropriate function to be called.
So by pushing the pointer to the appropriate VTable you can figure out
the function to be called.
They said that at "run time" you would find out which object is really
being called and thus we need VTables. I dont understand this point.
In this case it is pretty obvious that &ob1 is being passed so
compiler can figure out at compile time which real function is to be
called based on the fact that the virtual keyword is there in the base
class. Can you give me an example where the compiler would not be able
to figure out the type of the object being passed at compile time and
thus show me the need of VTables.

I am not very familiar with OOPS concept so might not be aware of some
basic concepts.

Thanks a lot,
Kapil
Jul 19 '05 #1
2 8006

"Kapil Khosla" <kh*********@yahoo.com> wrote in message
news:91**************************@posting.google.c om...
Dear all,
I am trying to underlying implementation of virtual functions in C++.
The way I understand polymorphism is

class Base
{
public:
virtual int func();
};

class Derived: public Base
{
public:
virtual int func();
}

int Base::func()
{
printf("In Base\n");
}

int Derived::func()
{
printf("In Derived\n");
}

void poly_func(Base * x)
{
x->func();
}
int main()
{
Derived ob1;
poly_func(&ob1);
}

Output :

This will call the function in the derived class instead of the base
class due to the virtual keyword in the base class with func().


Now my question is how does C++ implement such mechanism.
I read something about VTables in C++, that every class has a
different VTable which contain the appropriate function to be called.
So by pushing the pointer to the appropriate VTable you can figure out
the function to be called.
They said that at "run time" you would find out which object is really
being called and thus we need VTables. I dont understand this point.
In this case it is pretty obvious that &ob1 is being passed so
compiler can figure out at compile time which real function is to be
called based on the fact that the virtual keyword is there in the base
class. Can you give me an example where the compiler would not be able
to figure out the type of the object being passed at compile time and
thus show me the need of VTables.

I am not very familiar with OOPS concept so might not be aware of some
basic concepts.

Thanks a lot,
Kapil


Simple, suppose main and poly_func were in two different files. Then when
the compiler compiled poly_func it wouldn't know anything about main, so it
wouldn't know that poly_func was being called with a pointer to Derived.

Or, what if you changed your code to this

int main()
{
Base obj1;
Derived obj2;
poly_func(&obj1);
poly_func(&obj2);
}

Now your poly_func function has to deal with both types of object. So the
same code has to decide whether to call Base::func or Derived::func, so the
decision must be made at run time.

john
Jul 19 '05 #2
Min
First, there is not such thing as class, every thing is a subroutine at
assembly level. So each method in class becomes a list of
functions/subroutine. From the compiler point of view, it will remember as
follow for each method: this function IS this method in that CLASS at
COMPILE time. But as you demonstrated, you can have a method belonging to
two classes due to inheritance. So basically, some genius came up with
VTABLE to find out what the proper one at RUN TIME.
What exactly is a VTABLE ?
VTABLE is constructed by the compiler at COMPILE-TIME because it knows about
each method definition and declaration. Each VTABLE is included in the exe
file. Think of a VTABLE as a list of function pointers. It has an index
and value; In your examples, we will have a VTABLE for Base and another
VTABLE for Derived.
VTABLE for Base
--------------
0 | 0xd3290dl |
|-------------|
1 | etc |
|-------------|

VTABLE for Derived
--------------
0 | 0xdfffffffff |
|-------------|
1 | etc |
|-------------|

VTABLE[0] = 0xd3290dl means function-0 ( the compiler remembers Base::func
as function-0 at COMPILE time) executable code can be found at this address
(0xd3290dl ). But for Derived Class, Derived::func is also function-0
because it is derived from Base. For that reason, both Base::func and
Derived::func have the same index. But, Derived::func implementation is
different. So the compiler inserts different address to figure out where
Derived::func code be found ( 0xdfffffffff for our example) Using different
addresses, the program can actually look up in the table and figure out the
location of the function implementation at RUN time.

Quiz : What value should you expect for VTABLE[0] for Derived ? if Derived
does not over write Base:func.
Answer: 0xd3290dl or the same base VTABLE[0] for Base because both have the
same code.

Quiz 2:

Derived* de = new Derived;
Base* ba = (Base*) de;
ba->func();

Question: What should "ba->func()" be ? Derived::func or Base::func ?
Answer: Derived::func because type casting does not change the VTABLE, so
the address is still pointing to Derived::func.
Things to Ponder
============
1. If there is only one VTABLE and only one Executable code for each method,
How does multiple-instances share the code ?
2. How do you solve the problem with Multiple-Inheritance ?
Repeated-Multiple-Inheritances ? or Cyclic?

Ok this is as far as I can go without too much detail. It would be better
for you to pick up a Compiler text book and look up under OO implementation.
There are many ways to implement it and done differently depending on the
lang spec. Trust Me, it is very confusing especially if you are thinking in
C++. You need to start from a simple case and add a OO feature at time.
Eventually, you will understand why VTABLE which is designed in a way solve
a number of problems. Finally, you will understand why certain OO feature
can't be done.
"John Harrison" <jo*************@hotmail.com> wrote in message
news:bd************@ID-196037.news.dfncis.de...

"Kapil Khosla" <kh*********@yahoo.com> wrote in message
news:91**************************@posting.google.c om...
Dear all,
I am trying to underlying implementation of virtual functions in C++.
The way I understand polymorphism is

class Base
{
public:
virtual int func();
};

class Derived: public Base
{
public:
virtual int func();
}

int Base::func()
{
printf("In Base\n");
}

int Derived::func()
{
printf("In Derived\n");
}

void poly_func(Base * x)
{
x->func();
}
int main()
{
Derived ob1;
poly_func(&ob1);
}

Output :

This will call the function in the derived class instead of the base
class due to the virtual keyword in the base class with func().


Now my question is how does C++ implement such mechanism.
I read something about VTables in C++, that every class has a
different VTable which contain the appropriate function to be called.
So by pushing the pointer to the appropriate VTable you can figure out
the function to be called.
They said that at "run time" you would find out which object is really
being called and thus we need VTables. I dont understand this point.
In this case it is pretty obvious that &ob1 is being passed so
compiler can figure out at compile time which real function is to be
called based on the fact that the virtual keyword is there in the base
class. Can you give me an example where the compiler would not be able
to figure out the type of the object being passed at compile time and
thus show me the need of VTables.

I am not very familiar with OOPS concept so might not be aware of some
basic concepts.

Thanks a lot,
Kapil
Simple, suppose main and poly_func were in two different files. Then when
the compiler compiled poly_func it wouldn't know anything about main, so

it wouldn't know that poly_func was being called with a pointer to Derived.

Or, what if you changed your code to this

int main()
{
Base obj1;
Derived obj2;
poly_func(&obj1);
poly_func(&obj2);
}

Now your poly_func function has to deal with both types of object. So the
same code has to decide whether to call Base::func or Derived::func, so the decision must be made at run time.

john

Jul 19 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: Prabu | last post by:
Hi, I'm new to python, so excuse me if i'm asking something dumb. Does python provide a mechanism to implement virtual functions? Can you please give a code snippet also...:) Thanx in advance...
32
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
175
by: Ken Brady | last post by:
I'm on a team building some class libraries to be used by many other projects. Some members of our team insist that "All public methods should be virtual" just in case "anything needs to be...
5
by: Marcel Hug | last post by:
Hi NG ! I'm new in C# and I'm reading a book about the fundamentals and concepts. In the chapter Methods it's written to use virtual, if i would like to override the method in a subclass. This...
7
by: alexander.stippler | last post by:
Hi I wonder if their will be a performance penalty in the following situation due to virtual function calls: class Interface { public: virtual void methodA() = 0; virtual void methodB() =...
2
by: Heinz Ketchup | last post by:
Hello, I'm looking to bounce ideas off of anyone, since mainly the idea of using Multiple Virtual Inheritance seems rather nutty. I chalk it up to my lack of C++ Experience. Here is my...
4
by: David Zha0 | last post by:
Hi, "when we call a virtual method, the runtime will check the instance who called the method and then choose the suitable override method, this may causes the performance drop down", is this...
3
by: keith | last post by:
Dear mentors and gurus, I noticed at the end of section 22.4 of the 'FAQ-Lite' it says "Note that it is possible to provide a definition for a pure virtual function, but this usually confuses...
0
by: akshaycjoshi | last post by:
I am reading a book which says Even though unboxed value types don't have a type object pointer, you can still call virtual methods (such as Equals, GetHashCode, or ToString) inherited or...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.