![]() |
VOOZH | about |
Refer to the article C++ Interview Questions and Answers for the latest data.
There are many more differences, above is a list of the main differences.
Both references and pointers can be used to change the local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite the above similarities, there are the following differences between references and pointers.
References are less powerful than pointers as:
Due to the above limitations, references in C++ cannot be used for implementing data structures like Linked List, Tree, etc. In Java, references don’t have the above restrictions and can be used to implement all data structures. References being more powerful in Java is the main reason Java doesn’t need pointers.
References are safer and easier to use:
Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location (See questions 5 and 6 in the below exercise)
Easier to use: References don’t need dereferencing operator to access the value. They can be used like normal variables. ‘&’ operator is needed only at the time of declaration. Also, members of an object reference can be accessed with dot operator (‘.’), unlike pointers where arrow operator (->) is needed to access members.
Virtual functions are used with inheritance, they are called according to the type of the object pointed or referred to, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime. The virtual keyword is used to make a function virtual.
Following things are necessary to write a C++ program with runtime polymorphism (use of virtual functions)
Example: In the following program bp is a pointer of type Base, but a call to bp->show() calls show() function of Derived class because bp points to an object of Derived class.
In Derived
Time Complexity: O(1)
Auxiliary Space: O(1)
The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is a constant pointer that holds the memory address of the current object. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).
See https://www.geeksforgeeks.org/cpp/delete-this-in-c/
The vtable is a table of function pointers. It is maintained per class. vptr is a pointer to vtable. It is maintained per object (See this for an example). The compiler adds additional code at two places to maintain and use vtable and vptr.
You may also like:
We will soon be covering more C++.