Pointer to Object in C++

Hello,

I expected the result will be 12 but I have 11.

I traced the program and p has the address of y but point to X object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

class X {
public:
	void f()
	{
		cout << "1" << endl;
	}
};
class Y : public X
{
	void f() {
		cout << "2" << endl;
	}
};
int main() {

	X x;
	Y y;
	X* p = &x;
	p->f();
	p = &y;
	p->f();

	return 0;
}



Last edited on
The code you've posted will print "11". Did you copy it correctly? Shouldn't line 14 print "2"?

X::f() is not virtual, so since p is a X *, p->f() will always make a static call to X::f(), regardless of the run-time type of *p. For the call to be dynamic, X::f() needs to be virtual.
@helios
Thank you and edited first post.
Topic archived. No new replies allowed.