Not understanding classes

Is this

1
2
3
4
5
6
7
8
9
10
11
12
13
class Widget {
	int value;
public:
	Widget();
	Widget(int v);
	int get();
	void bump();
};

int Widget::get() const {
	return value;
}
...

the same as
1
2
3
4
5
6
7
8
9
10
11
12
class Widget {
	int value;
public:
	Widget();
	Widget(int v);
	//int get();
	void bump();

    int get() const {
	return value;
};
...


If it is why cant i use const here int Widget::get() const { and here int get() const {
Code works without const but what if i have to use this Widget as const argument to another function and there i have to use this get() method =/

cout << "Thanks in advance for help :)" <<endl;
No it is not the same. cv qualifiers for *this are part of function signature, so they should be present in declaration too.
This is the equivalent to second snippet:
1
2
3
4
5
6
7
8
9
10
11
12
class Widget {
	int value;
public:
	Widget();
	Widget(int v);
	int get() const;
	void bump();
};

int Widget::get() const {
	return value;
}
Thank you man, i have much to learn :)
@MiiNiPaa what does it mean when you declare a function and have a constant before the semicolon?
Hi,

It's been a few hours since MiiNiPaa has replied, so I hope you don't mind if I answer instead.

Marking a function const guarantees that none of the values of the member variables will be changed. If one does try to change one, then it will be a compile error.

This is handy for accessor functions (aka get functions), as one example.

It is a very good idea to mark your function parameters const as well (unless you do want to change them, as you might for a reference), and have functions return a const value or a const reference as well.

These things are called const correctness which is a very good thing that not many other languages have. Use const as much as you can.

Beware that with function overloading when you have 2 functions that look exactly the same except for one which has the const, realise they are actually 2 different functions.
Topic archived. No new replies allowed.