To understand working of constructor, copy constructor, destructor, I wrote the following code.
#include <iostream>
using namespace std;
class Cat
{
public:
Cat();
Cat(Cat&);
~Cat();
int itsage;
};
Cat::Cat()
{
cout << "Constructor called\n";
cout << this << endl;
itsage=2;
}
Cat::Cat(Cat& theCat)
{
cout << "Copy constructor called\n";
cout << this << endl;
itsage=theCat.itsage;
}
Cat::~Cat()
{
cout << "Destructor called\n";
cout << this << endl;
}
Cat myFunction(Cat Frisky)
{
cout << "Inside myFunction\n";
cout << "Frisky's address : " << &Frisky ;
cout << "\nFrisky's age: " << Frisky.itsage << "\n";
Frisky.itsage=100;
cout << "Reassigned Frisky's age: "<< Frisky.itsage << "\n";
return Frisky;
}
int main()
{
Cat Mani;
cout << "Mani's address : " << &Mani ;
cout << "\nMani's age: " << Mani.itsage << "\n";
myFunction(Mani);
return 0;
}
I got output as follows:
Constructor called
0x61ff04
Mani's address : 0x61ff04
Mani's age: 2
Copy constructor called
0x61ff0c
Inside myFunction
Frisky's address : 0x61ff0c
Frisky's age: 2
Reassigned Frisky's age: 100
Copy constructor called
0x61ff08
Destructor called
0x61ff08
Destructor called
0x61ff0c
Destructor called
0x61ff04
Everything is ok to me except what is stored at address 0x61ff08
when there was second call to copy constructor? Means we can see what is stored at addresses 0x61ff0c
and 0x61ff04
which are nothing but Frisky
and Mani
. Then what is that invisible thing at 0x61ff08
?
I thought of making that object visible by making a small change in main
function.
#include <iostream>
using namespace std;
class Cat
{
public:
Cat();
Cat(Cat&);
~Cat();
int itsage;
};
Cat::Cat()
{
cout << "Constructor called\n";
cout << this << endl;
itsage=2;
}
Cat::Cat(Cat& theCat)
{
cout << "Copy constructor called\n";
cout << this << endl;
itsage=theCat.itsage;
}
Cat::~Cat()
{
cout << "Destructor called\n";
cout << this << endl;
}
Cat myFunction(Cat Frisky)
{
cout << "Inside myFunction\n";
cout << "Frisky's address : " << &Frisky ;
cout << "\nFrisky's age: " << Frisky.itsage << "\n";
Frisky.itsage=100;
cout << "Reassigned Frisky's age: "<< Frisky.itsage << "\n";
return Frisky;
}
int main()
{
Cat Mani;
cout << "Mani's address : " << &Mani ;
cout << "\nMani's age: " << Mani.itsage << "\n";
Cat Sweety = myFunction(Mani);
cout << "Sweety's age : " << Sweety.itsage ;
return 0;
}
But received an error as follows :
ppp.cpp: In function 'int main()':
ppp.cpp:47:25: error: invalid initialization of non-const reference of type 'Cat&' from an rvalue of type 'Cat'
Cat Sweety = myFunction(Mani);
~~~~~~~~~~^~~~~~
ppp.cpp:19:2: note: initializing argument 1 of 'Cat::Cat(Cat&)'
Cat::Cat(Cat& theCat)
^~~
I really didn't get what went wrong.