I wrote this code:
class Address{
private:
std::string street;
int house;
public:
Address(std::string s, int h):
street(s), house(h) {}
void setHouse(int h) {house = h;}
friend std::ostream &operator << (std::ostream& os, Address &a);
};
class Person{
private:
std::string name;
Address A;
public:
Person(std::string n, std::string v, int c) :
name(n), A(v, c) {}
Address& getAddress(){return A;}
friend std::ostream &operator << (std::ostream& os, Person &a);
};
std::ostream &operator << (std::ostream& os, Address &a){
return os << "[" << a.street << ", " << a.house << "]";
}
std::ostream &operator << (std::ostream& os, Person &p){
return os << p.name << " " << p.A;
}
int main(){
Person pietro("Pietro", "Champs Elysees", 16);
std::cout << pietro << std::endl;
Address ma = pietro.getAddress();
ma.setHouse(333);
std::cout << pietro << std::endl;
return EXIT_SUCCESS;
}
I have these questions:
- Why does the line
ma.setHouse(333);does not have any side effect onpietro(ie in the second print the house-number is not changed)? - (I know that it’s not the right way, but) how can i make
ma.setHouse(333);having side effects onpietro? - Why should i write
const Address& getAddress() const {return A;}if the above code does not have side effects?
Q1. Because you are acting on a copy of
pietro‘sAddress:Q2. Take a reference?
Q3. So you can have const correctness. Without the const method and const return value, you can affect the internals of the object. Furthermore, you cannot call the method on const instances or references.