To many readers, this might sound the same thing, i.e.
class_type *var = NULL; *var = &some_work; is same as class_type *var = &some_work;
But in actual, it is not. When the declaration and initialization are done at the same step, the compiler calls the copy constructor whereas if done in another step, the compiler calls the default constructor.
To understand this, let’s consider an example:
Example 1: When initialisation is not done at the same step of the declaration
Example 2: When initialization is done with the declaration
prog.cpp: In constructor 'A::A(int)': prog.cpp:8:5: error: uninitialized reference member in 'int&' [-fpermissive] A(int w) ^ prog.cpp:5:10: note: 'int& A::p' should be initialized int& p; ^
Note: In this code, as soon as an object is created compiler will allocate memory to p by running the constructor of class A. Now as we know reference variable needs to be initialized at the same step so it will pop up an error message called “reference member is not initialized” .
As we have seen in code 1, initialisation is not done at the same step of the declaration, but still, our code runs. But in general, it is a rule that “reference member should be initialised and declared at the same step.”
So the answer to the above question is both yes and no.
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.
- Can we access private data members of a class without using a member or a friend function?
- Get name of current method being executed in Java
- Hide scroll bar, but while still being able to scroll using CSS
- Difference between Definition and Declaration
- C++ | asm declaration
- Const member functions in C++
- Count the number of objects using Static member function
- Is sizeof for a struct equal to the sum of sizeof of each member?
- Some interesting facts about static member functions in C++
- Passing by pointer Vs Passing by Reference in C++
- Reference to a pointer in C++ with examples and applications
- Passing Reference to a Pointer in C++
- Locality of Reference and Cache Operation in Cache Memory
- Difference between Call by Value and Call by Reference
- Insecure Direct Object Reference (IDOR) Vulnerability
- Different ways to use Const with Reference to a Pointer in C++
- How to add reference of an object in Container Classes
- Why do we need reference variables if we have pointers
- Return by reference in C++ with Examples
- When do we pass arguments by reference or pointer?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.