1
votes

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 &ltiostream&gt
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 &ltiostream&gt
#include &ltstring&gt
#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 &lt&lt B.getAddress() &lt&ltendl;
    cout &lt&lt B.ID;

    system("Pause");
    return 0;
}
2
Could you provide the exact error you get? Do you know which line throws the error?JoshD
Hi Josh, i get an error at function addSibling() line 32 of Object1.h. Error with "sibling" variable. Error: expression can not be evaluated.But if i compile and run with Dev-C there is no error informed.Steven

2 Answers

3
votes

Using operator * assumes that you deal with some data resided by address stored in this variable. Let's review your code:

*sibling = *p;

You trying to copy by value. This is wrong because sibling points to nowhere. It is even not a NULL, it is unpredictable. The correct line will be:

sibling = p;

So you tell that would store pointer to another instance.

1
votes

One notable problem is that you're returning by value in getSibling(), so you'll get a copy of the sibling rather than that actual sibling. Any changes you make will be to the temporary object.

As others have noted, you're addSibling function should be sibling = p. That's the source of your error.

But be sure to correct your getSibling function otherwise your setAddress won't do what you want.