class Myclass {
int x;
public Myclass (int y) {
cout << "This is great";
x = y;
}
int main () {
Myclass hold = new Myclass(1);
cout << hold.x;
...
1 2 3
// output
This is great
1
Question: How can the constructor display the message "This is great"? What I know is that everything is executed within the main function or the class with the main function. So I think the object invokes the constructor along with the message, but when does the message occur? After assigning the reference to the Myclass hold variable or something?
class Myclass
{
public:
int x;
Myclass (int y) : x(y){ cout << "This is great"; } //Use initialization lists.
~Myclass () { cout << "This is great"; } //output This is great in deconstructor
}
int main ()
{
Myclass *hold = new Myclass(1); //new produces a pointer to the newly allocated memory. You need a pointer.
cout << hold->x;
delete hold; // calls the deconstructor of the class.
}
How can the constructor display the message "This is great"?
The code within the constructor is called any time an object is constructed ( when an automatic variable is initialized or when a dynamic one is allocated with new )