2

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;
}
2
  • Could you provide the exact error you get? Do you know which line throws the error?
    – JoshD
    Oct 3, 2010 at 18:49
  • 1
    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
    Oct 3, 2010 at 19:01

2 Answers 2

3

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.