Reputation: 173
I have a class e.g.:
class Vehicle {
public:
Vehicle(int handle);
// Methods that use the handle e.g.:
Color getColor() {
return VEHICLE::GET_COLOR(handle);
}
protected:
int handle;
};
I don't know if that example makes sense to you, but I built several wrapper classes around those handles to get a more OOP style of coding.
So my question now is, how much overhead is there when I pass a Vehicle
object over just passing the vehicle handle to other methods?
Upvotes: 3
Views: 2486
Reputation: 18411
An optimizing compiler would ensure that there is no overhead for such simple call forwards. The core class (used by wrapper) should ideally be in same module (DLL/SO), otherwise linker/optimizer may be of little help.
However, for such thin wrappers around core class, even in shared-library scenario, the compiler would simply call the core method, eliminating the wrapper class method from call site.
Upvotes: 0
Reputation: 2914
If you split your class in a header and source file and use it in other compilation units there will be a sligth overhead due to the call to the constructor.
To solve this, the definition of your constructor has to be placed within your header file, so that the compiler can inline it.
You can do this with either changing your class declaration:
class Vehicle {
public:
Vehicle(int handle)
: handle(handle)
{
}
...
or by putting the definition inside your headerfile and decorating it with the inline
keyword.
class Vehicle {
public:
Vehicle(int handle);
...
}
inline Vehicle::Vehicle(int handle)
: handle(handle)
{
}
Notice that there is no gurantee that your function will be inlined, but probably every major compiler out there will be able to do it.
Also notice, that additional work in your constructor, e.g handle - 1
, will also very likely result in a overhead.
If your class is polymorphic or bigger, there might be additional overhead.
Upvotes: 3