C++ | Constructors | Question 9

Predict the output of following program.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
#include<stdlib.h>
using namespace std;
  
class Test
{
public:
   Test()
   { cout << "Constructor called"; }
};
  
int main()
{
    Test *t = (Test *) malloc(sizeof(Test));
    return 0;
}

chevron_right


(A) Constructor called
(B) Empty
(C) Compiler Error
(D) Runtime error


Answer: (B)

Explanation: Unlike new, malloc() doesn’t call constructor (See this)

If we replace malloc() with new, the constructor is called, see this.

Quiz of this Question

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.