I have the following code:
class TestClass
{
public:
TestClass(){};
std::string GetTestString()
{
return (mTestString);
}
void SetTestString(const std::string& rTestString)
{
mTestString = rTestString;
}
private:
std::string mTestString;
};
TestClass* pGlobalVar;
void SomeFunction(TestClass MyClass)
{
pGlobalVar->SetTestString("cba");
std::cout << "Changed string: " << pGlobalVar->GetTestString() << std::endl;
std::cout << "Copied string: " << MyClass.GetTestString() << std::endl;
}
int main()
{
pGlobalVar = new TestClass();
pGlobalVar->SetTestString("abc");
std::cout << "Original string: " << pGlobalVar->GetTestString() << std::endl;
SomeFunction(*pGlobalVar);
delete (pGlobalVar);
}
This outputs the following:
Original string: abc Changed string: cba Copied string: abc
As I did not define a copy constructor for my class, I would expect that a flat copy would be made, including the pointer in the std::string. Apparently though the std::string copy constructor is used, since a change to the original string did not change the copy.
Can anyone explain to me why it did not make flat copy?
I’m using Linux with GCC 4.4.6.
Since you didn’t define a copy constructor, C++ did for you.
The auto-generated copy constructor calls the constructor for all its member variables (if they have one).
Analogously, auto-generated constructors call all their members’ constructors, and destructors call all their members’ destructors.