Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ can we dereference this pointer? If so then how and if not then why?

Tags:

c++

gcc

I was working on a personal project with classes and didn't wanted to initialling each of the data members. So I made a call to *((Classname *)(this)) = {}; in the constructor. Hoping that it would behave the way

#include <iostream>

struct Test1
{
    int data1;
    int data2;

    void print()
    {
        std::cout << data1 << ' ' << data2 << std::endl;
    }
};


class Test2
{
    int data1;
    int data2;

    public:
    Test()
    {
        *(Test *)(this) = {};
    }

    void print()
    {
        std::cout << data1 << ' ' << data2 << std::endl;
    }
};

int main()
{
    Test1 t1;

    t1 = {}; /* I wanted the *((Classname *)(this)) = {}; to behave this way 
              * i.e. being able to initialise members with a initialisation list*/


    t1.print();

    Test2 t2;

    t2.print();

    return 0;
}

This while not generating any compilation errors ended up in a segmentation fault when creating class Test2 object.

Is there something that another way of initialising all the data-members to 0 or is there a restrictions that we cannot use this with initialisation lists? If so why? Or is this another one of undefined behaviours that I somehow stumbled upon?

[If it something compiler dependent, I am using gcc compiler (gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04))]

like image 265
Nitesh Meena Avatar asked Sep 03 '25 04:09

Nitesh Meena


1 Answers

UPDATE: I just realized you modified the code, and the new one does not make sense now. My answer is related to the original code.

Yes, you can dereference this and invoke member functions on it, such as this->f(); which is the same (*this).f(). Similarly, (*this) = ... is the same as this->operator=(...);.

The problem is that (*this) = {}; causes that {} creating a temporary of type Test initialized by default constructor. Consequently, you call the default constructor inside the default constructor, which causes a recursion that is never ended in your case.


If you want to initialize members to zero by default (that is, if not specified otherwise in constructor member initializer list), simply use (since C++11):

int data1 = 0;
int data2 = 0;
like image 165
Daniel Langr Avatar answered Sep 04 '25 18:09

Daniel Langr