I am learning C++ and i currently have some questions that i don't know the answers. I create this header file Object1.h and can compile this file but when i run the Test.cpp, Visual Studio throw an error because of access violation by *sibling. The strange thing is I can run it using Dev C+ and it return only value 2.Therefore I want to ask why assigning *sibling will create an error and why i can't change Person B's address using setAddress(). I will really appreciate if any one can give me some answer or hints. Thanks in advance.
//This is Object1.h
#include <
iostream>
using namespace std;
class Person{
public:
Person(int ID);
void setAddress(string addr);
string getAddress();
void addSibling(Person *p);
Person getSibling();
int ID;
private:
string address;
Person *sibling;
};
Person::Person(int ID){
this->ID = ID;
}
void Person::setAddress(string addr){
this->address = addr;
}
string Person::getAddress(){
return address;
}
void Person::addSibling(Person *p){
*sibling = *p;
}
Person Person::getSibling(){
return *sibling;
}
//This is Test.cpp
#include <
iostream>
#include <
string>
#include "Object1.h"
using namespace std;
int main(){
Person A(1);
Person B(2);
A.addSibling(&B);
// Change the address of person B through person A's getSibling()
A.getSibling().setAddress("123 Street");
cout <<
B.getAddress() <<
endl;
cout <<
B.ID;
system("Pause");
return 0;
}