1 #include<iostream.h>
2 using namespace std;
3
4
5 class Base {
6 public:
7 Base() {
8 cout << hex << (void *)this<<"\n" ;
9 }
10 virtual void foo() { };
11 };
12
13
14 class Derived : public Base {
15 public:
16 Derived() {
17
18 Base::Base(); // line A
19 }
20 virtual void foo() { };
21 virtual void bar() { };
22 };
23
24
25 int main() {
26 Derived* p = new Derived();
27 p->foo();
28 p->bar(); // line B
29 return 0;
30 }
why its printing two different addresses ?
1
Expert's answer
2012-12-04T08:58:13-0500
In “line A” you actually creating a temporary class object (of class Base) and calling its constructor (Base() ). The “(void *)this“ address is the address of temporary object of class Base witch you creating in line 18. If you want to use the constructor of class “Base” with some additional commands you have to write in line 16 : … & 16 Derived() : Base::Base() { & 17 //here goes you additional commands code & 18& } … Or like this … & 16 Derived() : Base() { & 17 //here goes you additional commands code & 18& } …
Comments
Leave a comment