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))]