We all know what virtual functions are in C++, but how are they implemented at a deep level?
Can the vtable be modified or even directly accessed at runtime?
Does the vtable exist for all classes, or only those that have at least one virtual function?
Do abstract classes simply have a NULL for the function pointer of at least one entry?
Does having a single virtual function slow down the whole class? Or only the call to the function that is virtual? And does the speed get affected if the virtual function is actually overwritten or not, or does this have no effect so long as it is virtual.
Aquarius_Girl
7,5164646 gold badges156156 silver badges293293 bronze badges
Brian R. BondyBrian R. Bondy
260k102102 gold badges548548 silver badges595595 bronze badges
12 AnswersHow are virtual functions implemented at a deep level?
From 'Virtual Functions in C++':
Whenever a program has a virtual function declared, a v - table is constructed for the class. The v-table consists of addresses to the virtual functions for classes that contain one or more virtual functions. The object of the class containing the virtual function contains a virtual pointer that points to the base address of the virtual table in memory. Whenever there is a virtual function call, the v-table is used to resolve to the function address. An object of the class that contains one or more virtual functions contains a virtual pointer called the vptr at the very beginning of the object in the memory. Hence the size of the object in this case increases by the size of the pointer. This vptr contains the base address of the virtual table in memory. Note that virtual tables are class specific, i.e., there is only one virtual table for a class irrespective of the number of virtual functions it contains. This virtual table in turn contains the base addresses of one or more virtual functions of the class. At the time when a virtual function is called on an object, the vptr of that object provides the base address of the virtual table for that class in memory. This table is used to resolve the function call as it contains the addresses of all the virtual functions of that class. This is how dynamic binding is resolved during a virtual function call.
Can the vtable be modified or even directly accessed at runtime?
Universally, I believe the answer is 'no'. You could do some memory mangling to find the vtable but you still wouldn't know what the function signature looks like to call it. Anything that you would want to achieve with this ability (that the language supports) should be possible without access to the vtable directly or modifying it at runtime. Also note, the C++ language spec does not specify that vtables are required - however that is how most compilers implement virtual functions.
Does the vtable exist for all objects, or only those that have at least one virtual function?
I believe the answer here is 'it depends on the implementation' since the spec doesn't require vtables in the first place. However, in practice, I believe all modern compilers only create a vtable if a class has at least 1 virtual function. There is a space overhead associated with the vtable and a time overhead associated with calling a virtual function vs a non-virtual function.
Do abstract classes simply have a NULL for the function pointer of at least one entry?
The answer is it is unspecified by the language spec so it depends on the implementation. Calling the pure virtual function results in undefined behavior if it is not defined (which it usually isn't) (ISO/IEC 14882:2003 10.4-2). In practice it does allocate a slot in the vtable for the function but does not assign an address to it. This leaves the vtable incomplete which requires the derived classes to implement the function and complete the vtable. Some implementations do simply place a NULL pointer in the vtable entry; other implementations place a pointer to a dummy method that does something similar to an assertion.
Note that an abstract class can define an implementation for a pure virtual function, but that function can only be called with a qualified-id syntax (ie., fully specifying the class in the method name, similar to calling a base class method from a derived class). This is done to provide an easy to use default implementation, while still requiring that a derived class provide an override.
Does having a single virtual function slow down the whole class or only the call to the function that is virtual?
This is getting to the edge of my knowledge, so someone please help me out here if I'm wrong!
I believe that only the functions that are virtual in the class experience the time performance hit related to calling a virtual function vs. a non-virtual function. The space overhead for the class is there either way. Note that if there is a vtable, there is only 1 per class, not one per object.
Does the speed get affected if the virtual function is actually overridden or not, or does this have no effect so long as it is virtual?
I don't believe the execution time of a virtual function that is overridden decreases compared to calling the base virtual function. However, there is an additional space overhead for the class associated with defining another vtable for the derived class vs the base class.
Additional Resources:
http://www.codersource.net/published/view/325/virtual_functions_in.aspx (via way back machine)
http://en.wikipedia.org/wiki/Virtual_table http://www.codesourcery.com/public/cxx-abi/abi.html#vtable
Not portably, but if you don't mind dirty tricks, sure!
WARNING: This technique is not recommended for use by children, adults under the age of 969, or small furry creatures from Alpha Centauri. Side effects may include demons which fly out of your nose, the abrupt appearence of Yog-Sothoth as a required approver on all subsequent code reviews, or the retroactive addition of
IHuman::PlayPiano() to all existing instances]
In most compilers I've seen, the vtbl * is the first 4 bytes of the object, and the vtbl contents are simply an array of member pointers there (generally in the order they were declared, with the base class's first). There are of course other possible layouts, but that's what I've generally observed.
Now to pull some shenanigans..
Changing class at runtime:
Replacing a method for all instances (monkeypatching a class)
This one's a little trickier, since the vtbl itself is probably in read-only memory.
The latter is rather likely to make virus-checkers and the link wake up and take notice, due to the mprotect manipulations. In a process using the NX bit it may well fail.
Ondrej Slinták
23.1k1919 gold badges8686 silver badges124124 bronze badges
puetzkpuetzk
9,04633 gold badges1919 silver badges2929 bronze badges
Does having a single virtual function slow down the whole class?
Or only the call to the function that is virtual? And does the speed get affected if the virtual function is actually overwritten or not, or does this have no effect so long as it is virtual.
Having virtual functions slows down the whole class insofar as one more item of data has to be initialized, copied, ⦠when dealing with an object of such a class. For a class with half a dozen members or so, the difference should be neglible. For a class which just contains a single
char member, or no members at all, the difference might be notable.
Apart from that, it is important to note that not every call to a virtual function is a virtual function call. If you have an object of a known type, the compiler can emit code for a normal function invocation, and can even inline said function if it feels like it. It's only when you do polymorphic calls, via a pointer or reference which might point at an object of the base class or at an object of some derived class, that you need the vtable indirection and pay for it in terms of performance.
The steps the hardware has to take are essentially the same, no matter whether the function is overwritten or not. The address of the vtable is read from the object, the function pointer retrieved from the appropriate slot, and the function called by pointer. In terms of actual performance, branch predictions might have some impact. So for example, if most of your objects refer to the same implementation of a given virtual function, then there is some chance that the branch predictor will correctly predict which function to call even before the pointer has been retrieved. But it doesn't matter which function is the common one: it could be most objects delegating to the non-overwritten base case, or most objects belonging to the same subclass and therefore delegating to the same overwritten case.
Virtual Board Games![]() how are they implemented at a deep level?
I like the idea of jheriko to demonstrate this using a mock implementation. But I'd use C to implement something akin to the code above, so that the low level is more easily seen.
parent class Fooderived class Barfunction f performing virtual function call
So you can see, a vtable is just a static block in memory, mostly containing function pointers. Every object of a polymorphic class will point to the vtable corresponding to its dynamic type. This also makes the connection between RTTI and virtual functions clearer: you can check what type a class is simply by looking at what vtable it points at. The above is simplified in many ways, like e.g. multiple inheritance, but the general concept is sound.
If MvGMvG
arg is of type Foo* and you take arg->vtable , but is actually an object of type Bar , then you still get the correct address of the vtable . That's because the vtable is always the first element at the address of the object, no matter whether it's called vtable or base.vtable in a correctly-typed expression.
40.5k1111 gold badges102102 silver badges213213 bronze badges
Usually with a VTable, an array of pointers to functions.
Lou FrancoLou Franco
75.9k1414 gold badges118118 silver badges178178 bronze badges
This answer has been incorporated into the Community Wiki answer
The answer for that is that it is unspecified - calling the pure virtual function results in undefined behavior if it is not defined (which it usually isn't) (ISO/IEC 14882:2003 10.4-2). Some implementations do simply place a NULL pointer in the vtable entry; other implementations place a pointer to a dummy method that does something similar to an assertion.
Note that an abstract class can define an implementation for a pure virtual function, but that function can only be called with a qualified-id syntax (ie., fully specifying the class in the method name, similar to calling a base class method from a derived class). This is done to provide an easy to use default implementation, while still requiring that a derived class provide an override.
Communityâ¦
Michael BurrMichael Burr
288k4141 gold badges447447 silver badges682682 bronze badges
You can recreate the functionality of virtual functions in C++ using function pointers as members of a class and static functions as the implementations, or using pointer to member functions and member functions for the implementations. There are only notational advantages between the two methods.. in fact virtual function calls are just a notational convenience themselves. In fact inheritance is just a notational convenience.. it can all be implemented without using the language features for inheritance. :)
The below is crap untested, probably buggy code, but hopefully demonstrates the idea.
e.g.
jherikojheriko
2,76811 gold badge1616 silver badges2727 bronze badges
I'll try to make it simple :)
We all know what virtual functions are in C++, but how are they implemented at a deep level?
This is an array with pointers to functions, which are implementations of a particular virtual function. An index in this array represents particular index of a virtual function defined for a class. This includes pure virtual functions.
When a polymorphic class derives from another polymorphic class, we may have the following situations:
Can the vtable be modified or even directly accessed at runtime?
Not standard way - there's no API to access them. Compilers may have some extensions or private APIs to access them, but that may be only an extension.
Does the vtable exist for all classes, or only those that have at least one virtual function?
Only those that have at least one virtual function (be it even destructor) or derive at least one class that has its vtable ('is polymorphic').
Do abstract classes simply have a NULL for the function pointer of at least one entry?
That's a possible implementation, but rather not practiced. Instead there is usually a function that prints something like 'pure virtual function called' and does
abort() . The call to that may occur if you try to call the abstract method in the constructor or destructor.
Does having a single virtual function slow down the whole class? Or only the call to the function that is virtual? And does the speed get affected if the virtual function is actually overwritten or not, or does this have no effect so long as it is virtual.
The slowdown is only dependent on whether the call is resolved as direct call or as a virtual call. And nothing else matters. :)
If you call a virtual function through a pointer or reference to an object, then it will be always implemented as virtual call - because the compiler can never know what kind of object will be assigned to this pointer in runtime, and whether it is of a class in which this method is overridden or not. Only in two cases the compiler can resolve the call to a virtual function as a direct call:
Note though that virtual calls have only overhead of dereferencing two pointers. Using RTTI (although only available for polymorphic classes) is slower than calling virtual methods, should you find a case to implement the same thing two such ways. For example, defining
virtual bool HasHoof() { return false; } and then override only as bool Horse::HasHoof() { return true; } would provide you with ability to call if (anim->HasHoof()) that will be faster than trying if(dynamic_cast<Horse*>(anim)) . This is because dynamic_cast has to walk through the class hierarchy in some cases even recursively to see if there can be built the path from the actual pointer type and the desired class type. While the virtual call is always the same - dereferencing two pointers.
EthourisEthouris
Here is a runnable manual implementation of virtual table in modern C++. It has well-defined semantics, no hacks and no
void* .
Note: XeverousXeverous
.* and ->* are different operators than * and -> . Member function pointers work differently.
34011 gold badge66 silver badges1414 bronze badges
Far cry new dawn download free. Each object has a vtable pointer that points to an array of member functions.
who
Something not mentioned here in all these answers is that in case of multiple inheritance, where the base classes all have virtual methods. The inheriting class has multiple pointers to a vmt.The result is that the size of each instance of such an object is bigger.Everybody knows that a class with virtual methods has 4 bytes extra for the vmt, but in case of multiple inheritance it is for each base class that has virtual methods times 4. 4 being the size of the pointer.
Philip StuyckPhilip Stuyck
6,29133 gold badges1919 silver badges3434 bronze badges
Burly's answers are correct here except for the question:
Do abstract classes simply have a NULL for the function pointer of at least one entry?
The answer is that no virtual table is created at all for abstract classes. There is no need since no objects of these classes can be created!
In other words if we have:
The vtbl pointer accessed through pB will be the vtbl of class D. This is exactly how polymorphism is implemented. That is, how D methods are accessed through pB. There is no need for a vtbl for class B.
In response to Mike's comment below..
If the B class in my description has a virtual method foo() that is not overridden by D and a virtual method bar() that is overridden, then D's vtbl will have a pointer to B's foo() and to its own bar(). There is still no vtbl created for B.
Andrew SteinAndrew Stein
10.2k44 gold badges2424 silver badges3838 bronze badges
very cute proof of concept i made a bit earlier(to see if order of inheritence matters); let me know if your implementation of C++ actually rejects it(my version of gcc only gives a warning for assigning anonymous structs, but that's a bug), i'm curious.
CCPolite.h:
CCPolite_constructor.h:
main.c:
output:
note since I am never allocating my fake object, there is no need to do any destruction; destructors are automatically put at the end of scope of dynamically allocated objects to reclaim the memory of the object literal itself and the vtable pointer.
DmitryDmitry
2,77833 gold badges2323 silver badges3636 bronze badges
Not the answer you're looking for? Browse other questions tagged c++polymorphismvirtual-functionsvtable or ask your own question.
In the application scenarios of SAP HANA, it is common to analyze and process the data located in other systems. Usually, customers would like to replicate the data from other systems to SAP HANA, and then do analysis and processing in SAP HANA. However, data replication not only costs time and memory, but also, usually, requires another replication system deployed which is always not easy. SDA, abbreviation for Smart Data Access, provides customers a new way to access the date in remote data source.
SDA is a new method of SAP HANA for accessing the data stored in remote data sources. With the help of SDA, SAP HANA can create so-called âvirtual tableâ mapping to tables located in remote data sources, and then SAP HANA can access the data directly by accessing the âvirtual tableâ. âvirtual tableâ can be manipulated by SAP HANA just like an ordinary table, which means the operations, such as select, update, insert, delete, and so on, are all available for âvirtual tableâ. Besides, join operation between local table and âvirtual tableâ is supported. When such join operation taken, optimizer of SAP HANA sends the relevant operations to remote data source for processing, and then the result set would be sent back to SAP HANA for further processing.
SDA was introduced in SAP HANA SPS06. At that time, the data sources supported by SAP HANA SDA includes: SAP HANAãSybase ASEãSAP Sybase IQãTeradata database and Apache Hadoop. And only read operation was permitted for virtual table. In SAP HANA SPS07, the data sources and operations supported by SAP HANA SDA are both extended. MSSQL Sever and Oracle are added to the list of supported data source, and write operation is permitted. The comparison of SDA in SPS06 and SPS07 is as below:
Noteï¼the data sources officially supported by SAP HANA are limited to specific versions above, other versions are not guaranteed to work well.
The first step of accessing remote data source is to create remote data source in SAP HANA. The communication between SAP HANA and remote data source is based on ODBC protocol. The subsequent blogs of this series will talk about how to deploy remote data source in SAP HANA server side. Here, letâs simply talk about how to create remote data source in SAP HANA Studio.
In SAP HANA Studio, there are two ways to create remote data sources, one is by GUI, another is using SQL statement.
(1) Create remote data source with GUI:
Firstly, Open the folder called âProvisioningâ. And then right click the âRemote Sourcesâ with mouse, select âNew Remote Sourceâ¦â:
Secondly, choose one adapter from the adapter list in the popup dialog, and fill in corresponding connection and authentication information of the remote data source.
Lastly, press the run button to create data source.
(2) Create remote data source with SQL:
CREATE REMOTE SOURCE <src_name>
ADAPTER <adapter_name> [CONFIGURATION FILE âfilenameâ]
CONFIGURATION <connection_info_string>
![]()
[opt_credentials_clause]
Example:
CREATE REMOTE SOURCE ORCL_11g_LNX
ADAPTER âodbcâ
CONFIGURATION FILE âproperty_orcl.iniâ
CONFIGURATION âDSN=oral11g_lnxâ
WITH CREDENTIAL TYPE âPASSWORDâ
USING âuser=OUTLN;password=Aa111111â²;
In above SQL statement, <adapter_name> can be one of: ASEODBC, IQODBC,TDODBC, HIVEODBC,ODBC. Obviously, ASEODBC is for Sybase ASE as data source, IQODBC is for Sybase IQ, TDODBC is for Teradata Database, HIVEODBC is for Hadoop. And ODBC adapter is for other common data sources. <connection_info_string> is used to specify the connection information for data source, the name of DSN is usually given here. <opt_credentials_clause> is used to specify the authentication information of data source. Attention please, only adapter ODBC requires the CONFGURATION FILE, the functionality of configuration file will be introduced in next section.
With the help of SDA, SAP HANA can communicate with the data sources who supports the ODBC protocol. However, just as discussed above, the supported data source of SAP HANA SDA is still limited now. For the supported specialized data source, SAP HANA has provided native code to support their operations. But SAP HANA SDA canât guarantee other data sources to work well. What stop SAP HANA SDA from supporting more ODBC data sources is that some operation and configuration of these ODBC data sources canât be processed by standard ODBC interface. For example, prepare a transaction for Sybase ASE requires some additional code which is not included in standard ODBC protocol. As SAP HANA provides such code, the operation for Sybase ASE is supported.
In order to decrease the influence of this issue, SAP HANA SDA applies Generic Adapter Framework to implement the communication with those unsupported ODBC data sources instead of calling the specialized native code for that data source in SAP HANA. With the help of Generic Adapter Framework, you can customize the feature and action of data source by setting a configuration file. For example, you can specify the supported operations, function mapping, data type mapping of the data source in the configuration file. For convenience of illustration, we call the configuration file âProperty Configuration Fileâ in the rest of this blog.
When creating data source, SAP HANA SDA will use the Generic Adapter Framework to communicate with remote data source if the ODBC adapter is chosen. SAP HANA SDA will search the property configuration file in the folder specified by environment variable DIR_EXECUTABLE, and the file name is specified by CONFIGURATION FILE option. By SPS07, SAP HANA SDA has provided the template of property configuration file for MSSQL and Oracle. They are called property_mss.ini and property_orcl.ini, and they are both located in the folder: $DIR_EXECUTABLE/config.
After data source created, SAP HANA SDA will parse the relevant property configuration file, all the features, function mappings, data type mappings and other properties will be linked together with the data source, and influence the communication between the SAP HANA and the data source.
A part of content of property_orcl.ini is below, we can figure out some format and function of property configuration file:
Creating a remote data source in SAP HANA usually involves steps belowï¼
Note: when modifying or creating the property configuration file, only the property which is different from default value needs to be set. The mistake in property configuration file may result in incorrect action or result of data source.
After data source created in SAP HANA Studio, âvirtual tableâ mapping to data in remote data source can now be created in SAP HANA Studio. Similar to creating data source, there are also two ways to create virtual table:
(1) Create virtual table with GUI:
(2) Create virtual table with SQL Statement below:
CREATE VIRTUAL TABLE <table_name> <remote_location_clause>
Example:
CREATE VIRTUAL TABLE sda.vt AT âORCL_11G_WINâ.âNULLâ.âOUTLNâ.âCANDIDATESâ;
In this blog, we have talked about basic content of SAP HANA SDA. In the subsequent blogs of this series, we will further talk about how to deploy SDA data source in SAP HANA Server, how to access Hadoop with the help of SAP HANA SDA, and so on. Please pay attention.
1. Whatâs New SAP HANA Platform Release Notes for SPS07:
2. Section 6.1.1 of SAP HANA Administrator Guideï¼
http://help.sap.com/hana/SAP_HANA_Administration_Guide_en.pdf
193,933
Contains AdsOffers in-app purchases
Virtual Table Tennis⢠is the only one based on 3D PHYSICS and supported ONLINE MULTIPLAYER table tennis game in the Google Play.
Main Features: ⢠Real-time multiplayer via Internet or Bluetooth! ⢠Based on the independent 3D physics system, motion of Ping-Pong can be perfectly simulated. ⢠As the design of AI system based on the human behaviors, it possesses various behaviors such as reaction, speed, strength, endurance, defense, etc. ⢠Accurate and visual control mode can truly simulate various ways of strike and smash in the match. Besides, players can make adjustments in âOptionsâ according to their own preferences. ⢠Players are confronted with AI opponents with various styles and capabilities in the game. ⢠Various game modes such as animation tutorials, free practices, Arcade Mode, Tournament Modes, and Multiplayer Mode! ⢠Five kinds of rackets and their various accessories can get different hitting effects and various game scenes with different styles. ⢠Twitter and Facebook integrated! ⢠3D sound system (earphone available) More play tactics and features are looking forward to your discovery.
Collapse
193,933 total
4
2
Read more
1414 gold badges4040 silver badges107107 bronze badges
Samiul Al HossainiSamiul Al Hossaini
34044 gold badges88 silver badges1818 bronze badges
5 Answers
You can pass the genre as string in the order you want and use regular expression to generate the movie_genre table.The sql fiddle here
psaraj12psaraj12
2,63111 gold badge1616 silver badges2626 bronze badges
If you need to get the full list, you want a Gordon LinoffGordon Linoff
cross join , with some additional logic:
827k3838 gold badges338338 silver badges443443 bronze badges
Not sure if this works for Oracle, but for SQL Server there is a neater implementation.
Example: SELECT a, b FROM (VALUES (1, 2), (3, 4), (5, 6), (7, 8), (9, 10) ) AS MyTable(a, b);
Ref:Section C. Specifying multiple values as a derived table in a FROM clause
Sena MSena M
Thus you can use DECODE function. Something like this:
If you wish to generate you strange formed resultset, you can use, say
More common way is to eliminate movies_genre at all:
A good outline ofr a persuasive speech. How can the answer be improved? Jan 18, 2010 Outline for Writing a Persuasive Speech; Outline for Writing a Persuasive Speech. A persuasive speech can be a very powerful tool. Some famous persuasive speeches were the âI Have A Dreamâ speech by Martin Luther King, Junior and Jimmy Valvanoâs famous ESPY awards speech. Public Speaking Dos and Donâts â good tips of.
Sanders the SoftwarerSanders the Softwarer
2,29811 gold badge99 silver badges2828 bronze badges
The
movie_genre table can also be created by the following -
What do you think about this??Is it more efficient than doing union on all the dual tables?
Samiul Al HossainiSamiul Al Hossaini
34044 gold badges88 silver badges1818 bronze badges
Not the answer you're looking for? Browse other questions tagged sqldatabaseoracle or ask your own question.Tiny Tennis Fun
Table tennis, also known as ping pong, is a game in which two or four players hit a little, light ball back and forth across a table using a small paddle. A point is scored when a player fails to return the ball to the other player. Basically, youâre playing tiny tennis on a table. Sound like a game you can only play with friends, or a wall? Not anymore! We have table-tennis games for all levels. The best part? You can play any time, anywhere â no table or paddles required! Thatâs an added bonus if youâre stuck at work and canât use your colleague's desk to set up your own tournament.
Looking to improve your ping pong skills? Try the classic King Ping Pong, where you move the virtual paddle and try to win the match. Feeling confident? Take your skills to the next level with Rio 2016. Experience the thrills and excitement of the 2016 Rio Summer Games in this online version. Virtually travel to Rio and lead your nation to victory! And if youâre looking for a fun twist on the classic table-tennis game try Bomb Pong. Itâs basically ping pong, but your ball is a bomb, so serve carefully!
Is playing a virtual game of ping pong too much of a social activity for you today? Then try Paddleball, also known as ping pong for one! Hit the ball with your paddle as many times as you possibly can.
Are you a ping-pong enthusiast? Then play a match of one of our table-tennis games!
Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |