0

I was recently asked this in an interview. Given the code:

class A{
    public:
       void f() { cout << "f in A" << endl; }
};

class B : public A{
    public:
       void g() { cout << "g in B" << endl; }
};

int main()
{
    B *p2 = new B;    
}

Which function does pointer p2 point to ?

Thanks

9
  • 1
    I'm pretty sure it points to no function? Just the object B itself? Could be wrong. Commented Nov 24, 2012 at 22:01
  • 1
    That's not a function pointer. Commented Nov 24, 2012 at 22:03
  • @Pubby In memory, what will p2 point to then ? Also, what could be the intent of asking this question ? Commented Nov 24, 2012 at 22:04
  • Agreed. Sounds like you either remembered wrong, or it was a trick question. Commented Nov 24, 2012 at 22:04
  • @Aaron The question is right. Commented Nov 24, 2012 at 22:05

3 Answers 3

2

p2 is not a function pointer. p2 is just pointing to the memory allocated by new B, not a function.

Sign up to request clarification or add additional context in comments.

Comments

1

Hmpf. p2 points to an instance of class B. So it could also point

-implementation specific and by accident- point to function g (if you apply some strange casts),

but this is rather pointless. p2 just points to an instance of class B, and if you like, you can invoke that instances method g. And if you are even more adventurous, you can even invoke method f of B's base class A's method f. Anything else is just implementation dependant and makes no sense.

Comments

0

p2 does not point to a function but to an instance of class B. Not only is it not a function pointer (as the other answers have pointed out), but the address it points to is not also the address of any function in almost any implementation. If class B had non-static data members, p2 would also coincide with the address of the first non-static data member (but it would not point to that as its not a pointer to that type of object!). However, this does not work for member methods: member function pointers don't depend on the object.

Very strange to have such a nonsense question in an interview. Perhaps the interviewers wanted to show their ignorance of basic programming.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.