Difference between using this and not with virtual functions

Feb 12, 2016 at 7:28pm
I have two classes:
1
2
3
4
5
6
7
8
9
10
11
12
13
class A{
virtual void func(){
  std::cout<<"I'm A\n";
}
void func2(){
  func(); // Is there any difference from this.func();?
}
};
class B : public A{
void func(){
  std::cout<<"I'm B\n";
}
};

If I store B as an A pointer and call func2() from it, what will it print? Does it change if I change func2 in A (like in the comment)?
1
2
A* b = new B();
b->func2(); // What will this print? 
Last edited on Feb 12, 2016 at 8:16pm
Feb 12, 2016 at 7:38pm
If I would call func2() from B, what will it print?

As written, it won't compile. There is no function func that you could call in func2. You need an object to invoke a non-static member function.

Of course, you could just try it.
Feb 12, 2016 at 8:17pm
@cire Sorry, if I wasn't extremely clear. I was implying that the call would be from an object, but in my case it would be from a pointer stored as parent class pointer.
Feb 12, 2016 at 10:18pm
In the second code snippet in the OP, "I'm B\n" will be printed since the function is virtual. If the function weren't virtual, "I'm A\n" would be printed. The first snippet with func2 is still nonsensical.
Feb 12, 2016 at 11:27pm
¿why is it nonsensical?
Feb 12, 2016 at 11:44pm
¿why is it nonsensical?

Because the poor indentation caused me to read it wrong. :p
Feb 13, 2016 at 12:06am
If B::func calls func2, it will result in infinite recursion.
Feb 13, 2016 at 12:40am
Xriuk wrote:
func(); // Is there any difference from this.func();?

Yes. However, it is exactly the same as this->func(); the this-> is implied.

Also, b->func2() wouldn't compile; you're trying to call a private function. I assume you meant them to be public?
Last edited on Feb 13, 2016 at 12:42am
Topic archived. No new replies allowed.