Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting all methods in class definition

When I use the pimpl idiom, is it a good idea to put all the methods definitions inside the class definition? For example:

// in A.h

class A {
   class impl;
   boost::scoped_ptr<impl> pimpl;
public:
   A();
   int foo();
}

// in A.cpp

class A::impl {
   // method defined in class
   int foo() {
       return 42;
   }

   // as opposed to only declaring the method, and defining elsewhere:
   float bar();
};

A::A() : pimpl(new impl) { }
int A::foo() {
   return pimpl->foo();
}

As far as I know, the only problems with putting a method definition inside a class definition is that (1) the implementation is visible in files that include the class definition, and (2) the compiler may make the method inline.

These are not problems in this case since the class is defined in a private file, and inlining has no effect since the methods are called in only one place.

The advantage of putting the definition inside the class is that you don't have to repeat the method signature.

So, is this OK? Are there any other issues to be aware of?

like image 261
Amnon Avatar asked Dec 23 '10 09:12

Amnon


People also ask

How do you define a method outside a class in C++?

Defining the method outside the class To do this, we specify the name of the class, followed by the operator :: (scope resolution), then followed by the name of the method. In the code example below, we will create a class myclass and define a method mymethod outside the class.

What is methods in class?

A method is a procedure associated with a class and defines the behavior of the objects that are created from the class.

What is a class function in c++?

Class: A class in C++ is the building block that leads to Object-Oriented programming. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A C++ class is like a blueprint for an object.

What are methods in C++?

Methods are functions that belongs to the class. There are two ways to define functions that belongs to a class: Inside class definition. Outside class definition.


1 Answers

I think you answered your own question : both solutions are equivalent.

However, I wouldn't be so sure that 'inlining has no effect since the methods are called in only one place' : an additional call could exists when the functions are not inlined. But chances are that the compiler is smart enough to optimize them away from the one-line forwarding calls in the outer class.

In the end, I believe it's just a matter of taste.

like image 83
icecrime Avatar answered Sep 21 '22 07:09

icecrime