functions declaration

hi, i wanna ask something. i got this code from Microsoft Visual C++ Windows Applications by Example by Stefan Björnander

1
2
3
4
5
6
7
8
9
10
11
12
13
class BankAccount
{
public:
BankAccount(int iNumber, double dSaldo = 0);
BankAccount(const BankAccount& bankAccount);
void Deposit(double dAmount) {m_dSaldo += dAmount;}
void Withdraw(double dAmount) {m_dSaldo -= dAmount;}
int GetNumber() const {return m_iNUMBER;}
double GetSaldo() const {return m_dSaldo; }
private:
const int m_iNUMBER;
double m_dSaldo;
};


my question is: is it the same when you write this?

int GetNumber() const {return m_iNUMBER;}

with

const int GetNumber() {return m_iNUMBER;}
Yes. Which is why it doesn't make sense to return const copies from functions.
1
2
3
4
5
6
const T f1();
T f2();

T a;
a=f1();
a=f2();
int GetNumber() const means that the function doesn't modify the object
const int GetNumber() means that the function returns a const int
Ah. I missed the other const.
 
const int GetNumber() means that the function returns a const int


Sometimes I question the purpose of returning a const int. Since the function already make a copy of int as return value for the function caller, setting it to be const is too restrictive in my opinion.
@bazzy: are you saying that

int GetNumber() const

which is doesn't modify the object was intended to just return the value of the member, or in the other words, it purpose is just for the "consciousness" of the programmer while writing the code (avoiding the unwanted behavior of the program)?
Yes, it will make the compiler give errors if you modify the object inside a const function
doesn't modify the object was intended to just return the value of the member, or in the other words, it purpose is just for the "consciousness" of the programmer while writing the code (avoiding the unwanted behavior of the program)?
What declaring a member function as const does is effectively make this of type const T * (i.e. a pointer to a const T). This implies that:
1. You can call the function using either a T or a const T. Non-const member functions can't be called using a const T (because the function might try to modify the object).
1
2
3
4
5
6
7
8
9
10
11
struct A{
    void f() const;
    void g();
};
//...
A a;
const A b;
a.f(); //OK
a.g(); //OK
b.f(); //OK
b.g(); //Compiler error. Can't cast implicitly from const A * to A *. 

2. The compiler won't allow you to modify class members or call non-const member functions.
1
2
3
void A::f() const{
    this->g(); //Compiler error. Can't cast implicitly from const A * to A *.
}
Topic archived. No new replies allowed.