Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Warning about "initializing pointer member 'height' with the stack address of parameter 'b' [-Wdangling-field]"

The result was correct.
Can this warning be ignored and what errors might be raised and what would be better?

Here is my very simple code:

#include<iostream>
using namespace std;
class Person{
    public:

    Person(int a,int b):age(a),height(&b){//Warning specific location here:height(&b)
        cout<<"initialize"<<endl;
        cout<<"height"<<*height<<endl;
    }
    
    Person(const Person &p){
        age = p.age;
        height = new int(*p.height);
    }
     
    int age;
    int *height;
};


void test02(){
    Person p1(10,150);
}

int main(int argc, char const *argv[])
{
    test02();
    return 0;
}

Please forgive my poor level of code. If you have any ideas about the programming style or this issue, please feel free to share them.
Any help will be appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The idea behind this code is I’m trying to figure out how do I initialize a pointer variable.

The results of the code meet my expectations.

>Solution :

You are initializing the pointer to point to variable b but that is a parameter taken by value. The b object is destroyed after the function(constructor) exits, leaving the pointer dangling.

You want

Person(int a,int b):age(a),height(new int(b)){
        cout<<"initialize"<<endl;
        cout<<"height"<<*height<<endl;
    }

If you come from Java/C# background, C++ has very different value semantics – new should be only used if you need to manage lifetime manually and even then smart pointers are preferred. T object; is not some hidden pointer to heap, = means deep copy for T. If you need references, use T& or T* – unless you ask for reference semantics, you do not get it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading