Constructor

1
2
3
4
5
6
7
8
9
10
11
12
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?
closed account (S6k9GNh0)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.
}
Last edited on
Well...Would you please explain why and answer my question? Forget about the destructor as I have not really mastered the use of it.
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 )
It is output when you construct the object (when you call new).

FYI, the output would actually be:
This is great1

since there is no \n in your couts.
Thanks bazzy and firedraco and now it clear it up.
Topic archived. No new replies allowed.