I have an (apparently) very simple class initialization, with two constructors, and when I want to create a new Friendship, the this pointer of the first argument has the appropriate pointer value, but the second doesn’t.
I’ll explain better in code – this is one my constructors:
Friendship::Friendship(const User &u1, const User &u2){
*user1 = u1;
*user2 = u2;
}
When I do this in my Test class:
bool Test::insertFriendship(User *user1, User *user2) {
bool friendshipExists = verifyFriendship(user1, user2);
if(!friendshipExists) {
friendships.push_back(new Friendship(*user1, *user2)); // this is a ptr_vector container
return true;
}
return false;
}
It gives me a EXC_BAD_ACCESS error at the push_back line because apparently the ‘this’ pointer of the user1 WORKS when it gets to the constructor and it points to a valid memory address, but when it goes to do the user2, the ‘this’ pointer of user2 points to 0x0 and it fails because that’s basically trying to re-deference NULL when it gets to the operator = overload.
Ex: when it tries to create a new Friendship:
this->user1’s mem address = 0x100100b20
this->user2’s mem address = 0x0 – error!
while
u1’s mem address = 0x7fff5fbff900
u2’s mem address = 0x7fff5fbff898
I mean, these u1 and u2 mem addresses are valid so why the heck doesn’t it work when I try to do:
*user1 = u1; //works cos this is 0x100100b20
*user2 = u2; // fails cos this is 0x0 even though u2 is a valid mem address!
Anyone know why this strange behavior? Even if I switch user1 and user2 in my push_back, it still won’t work at the SECOND one. It’s always that pesky second one that never works.
Ah, this is my Friendship header file, nothing too complex.
#include "User.h"
#ifndef Friendship_h
#define Friendship_h
class Friendship {
friend class Test;
protected:
User *user1;
User *user2;
public:
Friendship(const User &u1, const User &u2);
Friendship(const Friendship &a);
~Friendship();
};
#endif
Since
user1anduser2aren’t initialized, you cannot dereference them yet. I think you meant: