1

in a book i am reading to learn basic c++, there is this example:

#include <iostream>
using namespace std;

class Point {
private:             // Data members (private)
int x, y;
public:              // Member functions
void set(int new_x, int new_y);
int get_x();
int get_y();
};

void Point::set(int new_x, int new_y) {
x = new_x;
y = new_y;
}

int Point::get_x() {
return x;
}
int Point::get_y() {
return y;
}

My question is, is it not possible in c++ to include the definition of the member functions inside the class itself? The above seems quite messy. The book says to define a class member function you should use 'return_type class_name::function(){arguments}. But in C# you can just do it within the same class and it is less code. I haven't been able to find much about properties in c++. Thanks for help.

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
Daniel Gratz
  • 799
  • 1
  • 10
  • 15

7 Answers7

7

Although it is possible, it's not really recommended. Actually, the way it's done in your book isn't how it should be done either (and hopefully, later on in the book that will change!). The way you'll see it done 99% of the time (yes, I pulled that number out of my ass) is a class definition in a header file (.h extension) and the definitions in a source file (.cpp extension). The header file will be imported so to speak, into the source file via #include.

MGZero
  • 5,812
  • 5
  • 29
  • 46
  • So best practice is for each class, one header and one source file? That'll turn into alot of files. – Daniel Gratz Sep 29 '11 at 14:56
  • 2
    One source/header for each logical grouping of coupled classes. – Mark B Sep 29 '11 at 15:00
  • Another common style is to place small content functions in the header like the book shows. Placing code inside the class, IMO, clutters up the class declaration. – Thomas Matthews Sep 29 '11 at 15:03
  • Not recommended? By whom? For a simple accessor, inlining it will probably reduce code size and improve efficiency. I have read the recommendation of inlining accessors in the class before in a couple of books... I would have to find precise references. – David Rodríguez - dribeas Sep 29 '11 at 15:14
  • @Daniel Gratz, Just wait till you get to the part about templates. Then you'll try to put them in separate source/header files and then you end up screaming because templates defy most C++ conventions. :D – Zeenobit Sep 29 '11 at 15:21
  • @David Rodriguez I agree, and thats why I said 99% of the time. The left over 1% refers to inline functions and templates. – MGZero Sep 29 '11 at 15:25
3

You can define the members within the class as such.

class Point {
private:             // Data members (private)

    int x, y;

public:              // Member functions

    void set(int new_x, int new_y) {
        x = new_x;
        y = new_y;
    }

    int get_x() { return x; }
    int get_y() { return y; }
};

However, this isn't a popular style of coding in C++. Most C++ conventions suggest that you separate the implementations (definitions) from the interface (the declarations) in different files (definitions would go into Point.cpp, and declarations would go into Point.h), unless the definitions are very short (like accessors).

Zeenobit
  • 4,954
  • 3
  • 34
  • 46
1

You can define functions in the class definition in C++. This will cause them to be inline implicitly but that shouldn't matter because compilers have flexibility in terms of actually inlining. Usually this isn't done because it will increase compile time due to larger amounts of code being processed and the canonical C++ way it to put the method definitions in a separate source file.

Mark B
  • 95,107
  • 10
  • 109
  • 188
1
class Point
{
    private:             // Data members (private)
        int x, y;
    public:              // Member functions
        void set(int new_x, int new_y)
            { x = new_x; y = new_y; }
        int get_x()
            { return x; }
        int get_y()
            { return y; }
};
sehe
  • 374,641
  • 47
  • 450
  • 633
0

of course you can write

#include <iostream>
using namespace std;

class Point {
private:             // Data members (private)
int x, y;
public:              // Member functions
void set(int new_x, int new_y)
{
x = new_x;
y = new_y;
}
int get_x()
{
return x;
}
int get_y()
{
return y;
}
};

But whole point is to separate declaration and implementation.

GreenScape
  • 7,191
  • 2
  • 34
  • 64
0

Yes we can Define a function inside a class.it has following advantage. 1)the function which you define inside a class is treated as an "inline" function . (inline keyword before any function suggest compiler to place body of the definition of the function to where ever that function is been called from at compile time) 2)due to which inline function execute Faster.then normal function. (remember its totally up to the compiler to make that function inline or not.you cannot force compiler to make it inline)

aj8080
  • 95
  • 1
  • 8
0

Most answers point out that it is possible but not recommended, I do not agree with the latter. For simple one-liner accessors it just makes sense to provide them inside the class definition in most cases:

class point {
   int x,y;
public:
   // ... 
   int posX() const { return x; }
   int posY() const { return y; }
};

As of the setters, it will depend on whether you want to verify any invariant or not. In the former case, you might want to move it to a single translation unit, but even there if the checks are small I would just inline them inside the class definition.

The recommendations for separating declaration and definition of the member methods include things like:

  • smaller compile time: false, the compiler can parse the accessor trivially, it will not add much more to the parsing

  • smaller code size: false, if the function is not inlined, then the compiler must generate code for the function call, including calculation of the this pointer and actually perform the call. The inlined accessor will just require the reading of the member which will take less code.

  • higher compile time coupling: any change in the implementation of the function will require recompilation of all translation units that include the header... True, if you change the function, which for such a simple accessor will not happen.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
  • I've been getting a bit confused, a class 'declaration' is like class Name (); and the definition is fleshing it out and writing the code that makes it do something. In your post you refer to definition but i think you meant declaration. – Daniel Gratz Sep 29 '11 at 15:37
  • @DanielGratz: Actually, `class name;` is a declaration, and `class name {};` a definition. `class name { void f(); };` is the definition of class `name` that contains a declaration of the member function `name::f` which is not in turn defined· The definition of the class is where the members are *declared*, and that is inside the curly braces, even if the members are *defined* outside of the class *definition*. And I did mean *definition*. A bit confusing I guess. – David Rodríguez - dribeas Sep 29 '11 at 15:58
  • I had it backwards then. So the header normally has a class definition with function declarations inside, and the function definitions are outsourced to the source file. I can't think of any scenario in which you'd have a class declaration in the header, as almost all classes would contain data members that would be declared, or functions to be declared. Ach, confusing. And here, http://www.intap.net/~drw/cpp/cpp07_01.htm someone calls it a declaration and not a definition. – Daniel Gratz Sep 29 '11 at 18:18
  • @DanielGratz: There are many cases where you would like to just have a class declaration (without definition) in one header, search for *forward declaration* of a class and you will find many examples (the main use case is breaking compile time dependencies and reducing compilation times). As of your link, well the standard says §9.1/1 *A class-specifier is commonly referred to as a class definition.*, and *class-specifier* is defined in the grammar as *class-specifier: class-head { member-specificationopt }*, which is the best quote I can get. – David Rodríguez - dribeas Sep 29 '11 at 18:37