0

Not sure if the title is right or not, but here it goes:

If I have for example the following structure:

struct strA{
    int x;

    strA(int x);
}

strA::strA(int x){
    this->x = x;
}

And another structure that uses a pointer to the previous one:

#include strA

struct strB{
    int y;
    strA *var_strA;

    strB(int y);
    ~strB(){
        delete var_strA;
    }
};

strB::strB(int y){
    this->y = y;
    var_strA = new strA(123);
}

Then if I do from the main aplication a vector of strB items:

std::vector<strB> vectB;

main(){
    strB *itemB = new strB(456);
    vectB.push_back(*itemB);
    delete itemB;

    //more code
}

If I try to access the var_strA on the item in the vector, is empty. And also, I get an error when by deleting the item on the vector, since the destructor tries to delete var_strA again.

Comming from Java... I'm really getting lost with the damn pointers.

thanks in advance

Mauricio
  • 1
  • 2
  • 1
    Did you mean `delete itemB` rather than `delete strB`? – andrewdski May 24 '11 at 02:23
  • 1
    Why is var_strA even a pointer? Why is itemB even a pointer? Think about it. Java forces you to create objects dynamically. Java forces an extra level of indirection w.r.t. objects. C++ does not. You need to learn to appreciate that. Also, get one or more decent C++ books. For the purpose of learning and using C++, you should forget everything you know about Java. Trust me. I've been there and done that. – sellibitze May 24 '11 at 12:11
  • yes, there is no need that var_strA be pointer, but if itemB is not a pointer, how do I create new objects with the constructor? cause strB itemB = new strB(....) doesn work – Mauricio May 24 '11 at 13:42
  • nevermind, already figured out, and also checked an old c++ book I had gathering dust... :) – Mauricio May 25 '11 at 01:44

1 Answers1

1

You need a copy constructor and a copy assignment operator on that pointer-holding type, i.e. follow the rule of three. Here's a great resource here on SO: What is The Rule of Three?

Community
  • 1
  • 1
Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171