Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22042

Why does using initialisation list in class constructor generated a segmentation fault?

$
0
0

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


Viewing all articles
Browse latest Browse all 22042

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>