Answer to Question #19979 in C++ for sree

Question #19979
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 &ldquo;line A&rdquo; you actually creating a temporary class object (of class Base) and calling its constructor (Base() ). The &ldquo;(void *)this&ldquo; 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 &ldquo;Base&rdquo; with some additional commands you have to write in line 16 :
&hellip;
& 16 Derived() : Base::Base() {
& 17 //here goes you additional commands code
& 18& }
&hellip;
Or like this
&hellip;
& 16 Derived() : Base() {
& 17 //here goes you additional commands code
& 18& }
&hellip;

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS