Difference between using this and not with virtual functions

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
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.
@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.
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.
¿why is it nonsensical?
¿why is it nonsensical?

Because the poor indentation caused me to read it wrong. :p
If B::func calls func2, it will result in infinite recursion.
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
Topic archived. No new replies allowed.