Ok., So if I don't write a copy constructor for above class then what will happen? Will it do just shallow copy?
Please see below code
1 2 3 4 5 6 7 8 9 10
Test testObj;
testObj.a ="no copycon";
Test b = testObj; //will call default copycon
cout << testObj.a << endl; //will print no copycon
cout << b.a<< endl;; //will print no copycon
testObj.a = "changed text";
cout << testObj.a << endl;// will print changed text
cout << b.a; // still prints no copycon
Why the last line still prints "copycon"? As per my understanding it should changed and should display the changed string i.e. "changed text".
Isn't it?
ok thanks. But how to change above code so that I get an effect like if i change just the member of object testObj, and same change gets automatically reflected to the member of another object "b".
#include <iostream>
usingnamespace std;
class Test
{
public:
char *a;
Test(void)
{
a = newchar; //pointer a is initialized
}
~Test()
{
delete(a);// memory is freed
a = NULL; // pointer a points to nothing
}
};
void main ()
{
char b='s';
Test testObj;
*(testObj.a) = b; // operator * is used to acces the data pointed by the pointer a
cout<<*(testObj.a)<<endl;
system("pause");
}
#include <iostream>
usingnamespace std;
class Test
{
public:
char *a;
void Initialize(void) //insted of contructor we use a normal function
{
a = newchar; //pointer a is initialized
}
~Test()
{
delete(a);// memory is freed
a = NULL; // pointer a points to nothing
}
};
void main ()
{
char b='s';
Test testObj;
testObj.Initialize(); //initialize the class
*(testObj.a) = b; // operator * is used to acces the data pointed by the pointer a
cout<<*(testObj.a)<<endl;
system("pause");
}