Constructors

closed account (jvqpDjzh)
//Hello! I was studying a bit of overloading with our tutorials and I've just fronted a thing that I don't remember anymore well...

//Here is the part where my doubts came:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// overloading operators example
#include <iostream>
using namespace std;

class CVector {
  public:
    int x,y;

    CVector () {};//Why can we put here ';'? 
//but the constructor, which is a function, should have no the final ';', right ?
//what am I forgetting?

    CVector (int a,int b) : x(a), y(b) {}
    CVector operator + (const CVector&);
};


if you want to see all the code: http://www.cplusplus.com/doc/tutorial/templates/
Last edited on
No, because that's not just the definition of the ctor, that's also the implementation as well.

edit:
it's the equivalent of having the definition in the header:
 
CVector(); // <--- yes, you do need the semi-colon now. 


and the implementation in the .cpp file:

1
2
CVector::CVector()
{}      // <-- no semi-colon here, just like any other function impl. 



also remember that ";" is just an empty statement, so is valid to put it almost anywhere. eg, this compiles just fine:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
	;
	;
	;
	;
	;
	;

	return 0;
}

;
;
;


in other words, i think it's just a typo in your tutorial.
Last edited on
closed account (jvqpDjzh)
Ok, thank you! I have never heard that the ';' was an empty statement and that we could put it almost everywhere.
closed account (jvqpDjzh)
But what do you really mean by "empty statement"? We can use it almost everywhere but, for example, in certain cases it's mandatory to use it (classes, structs, arrays, enums,...)
More correctly, ; is a statement terminator. How it's used depends on the type of statement.

A ; is used to terminate declarative statements (structs, classes, enums) as you mentioned.

In the case of executable statements, by itself it creates a null statement. A null statement can have meaning in certain situations such as:
1
2
3
 
    if (true)
        ;  // terminates the true side of the if 



Last edited on
closed account (jvqpDjzh)
ok, thank you!
Topic archived. No new replies allowed.