1

Possible Duplicate:
Does C++ virtual function call on derived object go through vtable?

I have a question regarding c++ virtual table, specifically for gcc. consider following code

class A{
public:
virtual void doSomething(){}

}

class B : public A{
public:
virtual void doSomething(){}
}

//1 

A* a = new A()
a->doSomething();

Now the question is, since pointer a is pointing to object of A, does compiler ever bother do lookup in virtual function or is it smart enough to resolve this and get away with virtual table crap.?

thanks

Community
  • 1
  • 1
user424060
  • 1,545
  • 3
  • 20
  • 29
  • 8
    Not my -1 but Checking the generated assembly code is the only reliable way of answering your question and you can do that yourself easily. Practically, this should not matter the way you write your code in any way. – Alok Save Dec 30 '12 at 13:12
  • I have mentioned compiler in question, gcc – user424060 Dec 30 '12 at 13:17
  • If you know the dynamic type of the object is `A`, like in such a degenerate case, you can simply call the correct method yourself: `a->A::doSomething();` – StoryTeller - Unslander Monica Dec 30 '12 at 13:18
  • 1
    It's not valid to have an expression statement at namespace scope. Even if it was, suppose that `A`'s constructor altered the pointer `a`? The compiler cannot assume that this won't happen. – CB Bailey Dec 30 '12 at 13:21
  • Note that the correct answer there is not the accepted one, but this -> http://stackoverflow.com/a/4464163/673730 (cc. @Mat) – Luchian Grigore Dec 30 '12 at 13:27
  • It's not enought to know it is gcc, it also probably depends on compiler version. Optimizations are not standard, so they can come (and even go away) at whatever version. Only real way to find out for your version really is to look at assembly generated by it with different optimization flags (unless you're actually working on gcc and happen to know the exact answer). – hyde Dec 30 '12 at 13:31
  • @CharlesBailey, but altering `this` pointer would be UB, wouldn't it? – Lol4t0 Dec 30 '12 at 13:39
  • @Lol3t0: `this` is an rvalue so can't be altered. That doesn't mean that `A`'s constructor could alter the value of `a`, though. – CB Bailey Dec 30 '12 at 13:41

0 Answers0