0
votes

We have some classes, class A that have a constructor that looks like this:

A::A(int num, bool boods, double diablo, std::vector<ClassB* > &c) {
    createobj();
    setNum(num);
    setboods(boods);
    setDiablo(diablo);
    c= this->c;  //Where c, is just a vector of pointer objects of class B
}

void A::createobj() {
    E e("e", 59, 0, 100);  //Where E is a derived class inherited from class B
    B *e = &e;
    c.push_back(e); 
}

//Then over at main:

main() {
    std::vector<ClassB* > c;
    A a(100, true, 1.21, c);

    std::cout << c.size();  //prints out 1 as expected...

    for(auto i : c){
        std::cout << i->getName() << std::endl; //instead of printing "e"
                                                //I get this from the console 
                                                //�
                                                //Segmentation Fault
    }
}

I have been working on this for over 12 hours, any help is greatly appreciated and I will dance at your wedding.

c vector is a private vector of pointers that was declared in class A's .h and only holds ClassB* objects.

1
Please can you post the code for ClassB? - silleknarf
E e("e", 59, 0, 100); B *e = &e; -- What happens to e when the function returns? It goes away into a puff of smoke. So what will you be pointing to when that function returns? When you answer that, then you will see your code needs to be redesigned in some way where you are either not using pointers, or using smart pointers, or a phalanx of new and delete calls to keep everyone happy. - PaulMcKenzie
B *e = &e; For one thing, I'm actually surprised that compiled. That should be considered a re declaration. Secondly, I think the answer is what PaulMcKenzie said. - user10957435
@PaulMcKenzie Not using pointers is not an option, because it caused an object slicing issue, which is why I turned to pointers in the first place, will using smart pointers actually fix the issue? which kind of smart pointer? unique or shared? thank you for your help - Hugs
I stated a redesign of the code, which in such a redesign, pointers are not used. Nonetheless, you do see the issue, no? - PaulMcKenzie

1 Answers

1
votes

This is an issue:

void A::createobj(){
    E e("e", 59, 0, 100);  
    B *e = &e;   // <-- Is this your real code?  Anyway, the next line is bad also
    c.push_back(e);  // <-- The e is a local variable
}

You are storing pointers to a local variable e, thus when createobj returns, that e no longer exists.

One solution is to dynamically allocate your objects, and then you need to manage their lifetimes correctly by deallocating the memory somewhere in your code by issuing calls to delete:

void A::createobj(){
    E* e = new E("e", 59, 0, 100);  
    c.push_back(e);  // <-- ok 
}