ProgrammingModerateHCL · Tech Mahindra pattern
In C++, what does new do that malloc does not?
- A. It never fails
- B. It calls the constructor of the object it allocates
- C. It frees the memory automatically
- D. It allocates on the stack instead of the heap
Correct answer: B. It calls the constructor of the object it allocates
new allocates memory and then runs the constructor (delete runs the destructor before freeing). malloc only returns raw bytes. new throws std::bad_alloc on failure by default rather than returning NULL.
More OOP with C++ and Java questions
- What is printed? java class A { void show() { System.out.print("A"); } } class B extends A { void show() { super.show()…
- What is printed? cpp class Base { public: void show() { cout << "B1"; } virtual void vshow() { cout << "B2"; } }; class Derived : public…
- In C++, Base has a non-virtual destructor and Derived : public Base owns a heap buffer freed in ~Derived. What happens on: Base p = new…
- What is printed? java String a = "hi"; String b = "hi"; String c = new String("hi"); System.out.print((a == b) + " " + (a == c) + " " +…
- What is printed? java System.out.print('a' + 1); System.out.print(" "); System.out.print("" + 'a' + 1);
- What is printed? cpp void f(int) { cout << "int "; } void f(double) { cout << "double "; } int main() { f('a'); f(2.5f); }