Can we print the address of object of class in C++?

Viewed 22221

How can we Print the address of object of class in the member function of that class in C++?

class A
{
     int x;
   private:
     A(){x=2;}
}
int main()
{
   A B;
   return 0;
}

How to print the address of B in member function or in main().

12 Answers

With C++20 you can use std::to_address:

#include <memory>
#include <iostream>

class A{};

int main()
{
    A B;
    std::cout << std::to_address(&B) << '\n'
}

Which has the advantage of being able to accept raw pointers, smart pointers, iterators, and pointer-like objects. Making it useful for cases that require generic code.

#include <iostream>
using namespace std;
class A{
     public:
     A(){
      cout<<this<<endl;
     }
};

int main()
{
   A* a = new A();
   cout<<a<<endl;

   return 0;

}

I see that there are a lot of answers for your question already, but I don't know why none of them point that you have a private constructor for class A, and the way the object B is being instantiated should throw a compilation error. At least, it did in my case. There is a whole lot of concepts around using private constructors, https://stackoverflow.com/a/2385764/3278350 gives a good idea.

Related