C++ Interview Questions and Answers

author image Hirely
at 06 Jan, 2025

Question: What is the difference between new and malloc() in C++?

Answer:

In C++, both new and malloc() are used for memory allocation, but they have several key differences in terms of syntax, functionality, and behavior. Below is a detailed comparison:

1. Memory Allocation:

  • new: Allocates memory for an object or array of objects in the heap and returns a pointer to the allocated memory.

    • It initializes the object (if it’s a class) by calling the constructor.
    • It automatically calls the appropriate constructor for class types.
  • malloc(): Allocates a block of raw memory from the heap and returns a pointer to the allocated memory.

    • It does not initialize the memory or call constructors.
    • malloc() only allocates memory for a specific size, but it does not know about the type of object being created.

2. Syntax:

  • new:

    • For a single object: Type* ptr = new Type();
    • For an array: Type* ptr = new Type[size];
    • Example:
      int* ptr = new int;  // Allocates memory for a single integer
      int* arr = new int[5];  // Allocates memory for an array of 5 integers
  • malloc():

    • Syntax requires the size to be passed in bytes: ptr = (Type*) malloc(size);
    • Example:
      int* ptr = (int*) malloc(sizeof(int));  // Allocates memory for a single integer
      int* arr = (int*) malloc(5 * sizeof(int));  // Allocates memory for an array of 5 integers

3. Type Safety:

  • new: new is type-safe, meaning it automatically returns a pointer of the correct type without the need for type casting.
  • malloc(): malloc() is not type-safe. It returns a void* pointer, and you need to explicitly cast it to the correct type.
    • Example:
      int* ptr = new int;  // Type-safe, returns int*
      int* ptr = (int*) malloc(sizeof(int));  // Needs explicit type-casting

4. Initialization:

  • new:

    • For built-in types: Memory is initialized to default values (e.g., zero for int, false for bool).
    • For class types: It calls the class constructor.
    • Example:
      int* ptr = new int();  // Memory initialized to 0
  • malloc(): The memory allocated by malloc() is not initialized. It may contain garbage values.

    • Example:
      int* ptr = (int*) malloc(sizeof(int));  // Memory is not initialized

5. Deallocation:

  • new: Memory allocated by new is deallocated using the delete operator.

    • For a single object: delete ptr;
    • For an array: delete[] ptr;
    • Example:
      delete ptr;  // Deallocate memory for a single object
      delete[] arr;  // Deallocate memory for an array of objects
  • malloc(): Memory allocated by malloc() is deallocated using the free() function.

    • Example:
      free(ptr);  // Deallocate memory allocated by malloc

6. Error Handling:

  • new: If new fails to allocate memory, it throws a std::bad_alloc exception.

    • Example:
      try {
          int* ptr = new int[1000000000];  // May throw std::bad_alloc if memory allocation fails
      } catch (const std::bad_alloc& e) {
          std::cout << "Memory allocation failed!" << std::endl;
      }
  • malloc(): If malloc() fails, it returns NULL (a nullptr in C++).

    • Example:
      int* ptr = (int*) malloc(sizeof(int));
      if (ptr == NULL) {
          std::cout << "Memory allocation failed!" << std::endl;
      }

7. Usage Context:

  • new: new is the preferred memory allocation method in C++ because it automatically handles memory initialization and constructor calls for objects, and it supports type safety.
  • malloc(): malloc() is primarily used in C and is sometimes used in C++ for compatibility with C-style code, but it’s generally not recommended in modern C++.

8. Performance:

  • new and malloc() generally have similar performance characteristics, as both allocate memory from the heap. However, new might be slightly slower due to the additional overhead of constructor calls and memory initialization.

Summary of Key Differences:

Featurenewmalloc()
LanguageC++C and C++
Syntaxnew Type or new Type[size]malloc(size)
Type SafetyType-safe (returns correct type)Not type-safe (returns void*)
InitializationInitializes memory (for built-in types, default initialization)No initialization (may contain garbage values)
Constructor CallCalls constructor (for class types)Does not call constructor
Deallocationdelete or delete[]free()
Error HandlingThrows std::bad_alloc exceptionReturns NULL if allocation fails
UsagePreferred in C++ for type safety and object initializationUsed in C and legacy C++ code

Example Usage:

#include <iostream>

class MyClass {
public:
    MyClass() { std::cout << "Constructor called!" << std::endl; }
    ~MyClass() { std::cout << "Destructor called!" << std::endl; }
};

int main() {
    // Using new
    MyClass* obj1 = new MyClass();  // Constructor is called

    // Using malloc
    MyClass* obj2 = (MyClass*) malloc(sizeof(MyClass));  // No constructor is called

    delete obj1;  // Destructor is called
    free(obj2);   // Destructor is not called
    return 0;
}

Output:

Constructor called!
Constructor called!
Destructor called!

Note: In the case of malloc(), the destructor for obj2 is not called because it was not properly initialized with new.

Question: What is the purpose of the this pointer in C++?

Answer:

The this pointer in C++ is an implicit pointer that is available inside all non-static member functions of a class. It points to the current instance (object) of the class for which the member function is being invoked. It allows you to access the members (variables and methods) of the current object and is essential for distinguishing between instance variables and local variables with the same name.

Key Points about the this Pointer:

  1. Refers to the Current Object:

    • The this pointer holds the address of the current object on which a member function is called.
    • It provides a way for non-static member functions to refer to the object they are operating on.
  2. Implicitly Passed to Member Functions:

    • Every non-static member function has access to the this pointer, even though it is not explicitly passed by the user.
    • For example, inside a member function, this is automatically available.
  3. Type of this:

    • The type of the this pointer is a pointer to the class. For a class MyClass, this is of type MyClass*.
    • If the member function is const, the type of this becomes const MyClass*.
  4. Usage in Constructor and Destructor:

    • Inside a constructor or destructor, this points to the object that is being constructed or destructed.
  5. Distinguishing Between Member Variables and Parameters:

    • When a member function has a parameter with the same name as a class member, the this pointer helps to differentiate between the two. It is used to access the instance variable while the parameter will refer to the local value.

    Example:

    class MyClass {
    private:
        int value;
    public:
        MyClass(int value) {
            this->value = value;  // 'this->value' refers to the class member, 'value' refers to the parameter
        }
    
        void printValue() {
            std::cout << "Value: " << this->value << std::endl;
        }
    };
    
    int main() {
        MyClass obj(10);
        obj.printValue();  // Output: Value: 10
        return 0;
    }
  6. this and Static Methods:

    • The this pointer is not available in static member functions because static functions do not belong to a specific instance of the class. Static methods can be called without creating an object, so they do not have a this pointer.
  7. Returning this:

    • You can return the this pointer from a member function, which can be useful for method chaining or fluent interfaces.
    • Example:
      class MyClass {
      private:
          int value;
      public:
          MyClass& setValue(int value) {
              this->value = value;
              return *this;  // Returning the current object itself for method chaining
          }
      
          void printValue() const {
              std::cout << "Value: " << value << std::endl;
          }
      };
      
      int main() {
          MyClass obj;
          obj.setValue(10).printValue();  // Method chaining
          return 0;
      }
  8. this in Const Member Functions:

    • If a member function is declared const, it means the function does not modify the object. Therefore, the type of this changes to a pointer to const object, i.e., const MyClass*. This ensures that you cannot modify the object in such methods.

    Example:

    class MyClass {
    private:
        int value;
    public:
        MyClass(int value) : value(value) {}
    
        void printValue() const {
            // this->value = 10; // Error: Cannot modify because 'this' is of type const MyClass*
            std::cout << "Value: " << value << std::endl;
        }
    };
    
    int main() {
        MyClass obj(10);
        obj.printValue();  // Output: Value: 10
        return 0;
    }

Summary of this Pointer Features:

FeatureDetails
TypeA pointer to the class object (ClassName*).
AccessAvailable implicitly inside non-static member functions.
UsageUsed to refer to the current instance’s data members and methods.
Constructor/DestructorRefers to the object being constructed or destructed.
Availability in Static MethodsNot available in static methods because they do not operate on instances.
Const MethodsFor const methods, this becomes a pointer to const ClassName*.
Distinguishing Member vs ParameterUsed to differentiate between class members and function parameters with the same name.
Returning thisCan be returned to support method chaining or fluent interfaces.

Example of this Pointer in C++:

#include <iostream>

class MyClass {
private:
    int value;
public:
    MyClass(int value) {
        this->value = value;  // 'this' differentiates the class member 'value' from the constructor parameter
    }

    void printValue() const {
        std::cout << "Value: " << this->value << std::endl;  // Accessing the class member using 'this'
    }

    MyClass* getThis() {
        return this;  // Returning the 'this' pointer (current object)
    }
};

int main() {
    MyClass obj(42);
    obj.printValue();  // Output: Value: 42

    // Returning and using the 'this' pointer
    MyClass* ptr = obj.getThis();
    ptr->printValue();  // Output: Value: 42

    return 0;
}

Output:

Value: 42
Value: 42

The this pointer is crucial for object-oriented programming in C++ as it allows member functions to access the object on which they are invoked and manage the relationships between instance variables and local variables or parameters.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as C++ interview questions, C++ interview experiences, and details about various C++ job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now