60 347
Assignments Done
98%
Successfully Done
In April 2018

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 ?
Expert's answer
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& }
…

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 first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions