Hi,

Below code snippet belongs to copy constructor implementation. my question is in both cases (without and with copy constructor) if i execute this programme ,it will print the diff-2 memory addresses for both objects.

0x22ff20integer=0 (for object s1)
0x22ff10integer=0 (for object s2)

but i believe in case of without copy constructor it must have printed same memory address due shallow copy(bit wise copy) so now *s1.m_p (s1 object)and *s2.m_p(s2 object) must have same memory address.

Anybody can help me regarding this.

#include<iostream.h>


using namespace std;

class Derived1 
{ 
int *m_p;
public:
Derived1 ();
Derived1( const Derived1& obj);
void show()const  {cout<<"integer="<<*m_p<<endl;}
void Derived1::setVal(int val)
{
    *m_p = val;
}
~Derived1(){ 

delete m_p;}
};

 Derived1::Derived1( )
 {    
     m_p=new int(0);   
 }

 Derived1::Derived1( const Derived1 &obj)
       {
       m_p=new int(*obj.m_p);

       }

int main()
{

  Derived1 s1 ;
  cout<<&s1;
  s1.show();
  Derived1 s2=s1;
  cout<<&s2;
  s2.show();



}

but i believe in case of without copy constructor it must have printed same memory address due shallow copy

That's not the case because you aren't printing the address contained by the pointer, you're printing the address of the object that owns the pointer. Change your show() method to this so that you can see the difference in addresses contained by the pointer:

void show() const
{
    cout << "integer=" << (void*)m_p << endl;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.