C++ Interview Questions and Answers
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
- For a single object:
-
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
- Syntax requires the size to be passed in bytes:
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 avoid*
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
- Example:
4. Initialization:
-
new
:- For built-in types: Memory is initialized to default values (e.g., zero for
int
,false
forbool
). - For class types: It calls the class constructor.
- Example:
int* ptr = new int(); // Memory initialized to 0
- For built-in types: Memory is initialized to default values (e.g., zero for
-
malloc()
: The memory allocated bymalloc()
is not initialized. It may contain garbage values.- Example:
int* ptr = (int*) malloc(sizeof(int)); // Memory is not initialized
- Example:
5. Deallocation:
-
new
: Memory allocated bynew
is deallocated using thedelete
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
- For a single object:
-
malloc()
: Memory allocated bymalloc()
is deallocated using thefree()
function.- Example:
free(ptr); // Deallocate memory allocated by malloc
- Example:
6. Error Handling:
-
new
: Ifnew
fails to allocate memory, it throws astd::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; }
- Example:
-
malloc()
: Ifmalloc()
fails, it returnsNULL
(anullptr
in C++).- Example:
int* ptr = (int*) malloc(sizeof(int)); if (ptr == NULL) { std::cout << "Memory allocation failed!" << std::endl; }
- Example:
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
andmalloc()
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:
Feature | new | malloc() |
---|---|---|
Language | C++ | C and C++ |
Syntax | new Type or new Type[size] | malloc(size) |
Type Safety | Type-safe (returns correct type) | Not type-safe (returns void*) |
Initialization | Initializes memory (for built-in types, default initialization) | No initialization (may contain garbage values) |
Constructor Call | Calls constructor (for class types) | Does not call constructor |
Deallocation | delete or delete[] | free() |
Error Handling | Throws std::bad_alloc exception | Returns NULL if allocation fails |
Usage | Preferred in C++ for type safety and object initialization | Used 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:
-
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.
- The
-
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.
- Every non-static member function has access to the
-
Type of
this
:- The type of the
this
pointer is a pointer to the class. For a classMyClass
,this
is of typeMyClass*
. - If the member function is
const
, the type ofthis
becomesconst MyClass*
.
- The type of the
-
Usage in Constructor and Destructor:
- Inside a constructor or destructor,
this
points to the object that is being constructed or destructed.
- Inside a constructor or destructor,
-
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; }
- When a member function has a parameter with the same name as a class member, the
-
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 athis
pointer.
- The
-
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; }
- You can return the
-
this
in Const Member Functions:- If a member function is declared
const
, it means the function does not modify the object. Therefore, the type ofthis
changes to a pointer toconst
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; }
- If a member function is declared
Summary of this
Pointer Features:
Feature | Details |
---|---|
Type | A pointer to the class object (ClassName* ). |
Access | Available implicitly inside non-static member functions. |
Usage | Used to refer to the current instance’s data members and methods. |
Constructor/Destructor | Refers to the object being constructed or destructed. |
Availability in Static Methods | Not available in static methods because they do not operate on instances. |
Const Methods | For const methods, this becomes a pointer to const ClassName* . |
Distinguishing Member vs Parameter | Used to differentiate between class members and function parameters with the same name. |
Returning this | Can 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.
Tags
- C++
- C++ interview questions
- C++ constructors
- Inline keyword
- Reference in C++
- Class and object in C++
- Call by value vs call by reference
- Abstract class
- Virtual functions
- New vs malloc
- This pointer in C++
- C++ templates
- C++ struct vs class
- Exception handling in C++
- Operator overloading in C++
- Polymorphism in C++
- C++ pointers
- C++ iterators
- C++ STL
- Scope resolution operator
- C++ memory management
- C++ exception handling
- C++ overloading
- C++ function overriding