Explain this c++ code
c++, constructor, destructor, object
Solution
The second line invokes what is called a Copy Constructor. Much like lawyers, if you do not have one, one will be provided for you by the compiler.
It is a special type of converter that is invoked when you initialize a variable with another of the same type.
A b(a)
A b = a
Both of these invoke it.
A(const A& a)
{
cout << "Copy Constructor called" << endl;
//manually copy one object to another
}
Add this code to see it. Wikipedia has more info.
Problem
``` #include <iostream> using namespace std; class A { int n; public: A() { cout << "Constructor called" << endl; } ~A() { cout << "Destructor called" << endl; } }; int main() { A a; //Constructor called A b = a; //Constructor not called return 0; } ``` output: ``` Constructor called Destructor called Destructor called ``` Constructor is called once while the destructor is called twice What is happning here? Is this undefined behaviour?