krb
krb

Reputation: 16345

Can I create functions without defining them in the header file?

Can I create a function inside a class without defining it in the header file of that class?

Upvotes: 1

Views: 446

Answers (5)

wilhelmtell
wilhelmtell

Reputation: 58685

Why don't you try and see?


[˙ʇ,uɐɔ noʎ 'oᴎ]

Update: Just to reflect on the comments below, with the emphasis of the C++ language on smart compiling, the compiler needs to know the size of the class (thus requiring declaration of all member data) and the class interface (thus requiring all functions and types declaration).

If you want the flexibility of adding functions to the class without the need to change the class header then consider using the pimpl idiom. This will, however, cost you the extra dereference for each call or use of the function or data you added. There are various common reasons for implementing the pimpl:

  • to reduce compilation time, as this allows you to change the class without changing all the compilation units that depend on it (#include it)
  • to reduce coupling between a class' dependents and some often-changing implementation details of the class.
  • as Noah Roberts mentioned below the pimpl can also solve exception safety issues.

Upvotes: 4

Maciej Hehl
Maciej Hehl

Reputation: 7995

I have no idea what You are trying to do, but I have a strange gut feeling, that Pointer To Implementation (pImpl) idiom might be helpful. If you want to add a public method in a cpp file and that method is not declared in the class definition in a header, You can't do that and it doesn't make sense.

Upvotes: 0

Drew Hall
Drew Hall

Reputation: 29055

Short answer: No, you can't.

However, if you're trying to inject a private function into the class that will only be used in that class's implementation, you can create a function in an anonymous namespace within that class's .cpp file that takes an object of that type by reference or pointer.

Note that you won't be able to muck with the passed objects internal state directly (since there's no way for the class to declare friendship with that anonymous function), but if the function just aggregates operations from the public interface of the class it should work just fine.

Upvotes: 2

Edward Strange
Edward Strange

Reputation: 40887

No. However, you can mimic such:


struct X
{
  void f();

  X();
  ~X();

private:
  struct impl;
  impl * pimpl;
};

// X.cpp
struct X::impl
{
  void f()
  {
    private_function();
    ...
  }
  void private_function() { ...access private variables... }

};

//todo: constructor/destructor...

void X::f() { pimpl->f(); }

Upvotes: 3

pmr
pmr

Reputation: 59841

No, you can't. It wouldn't make much sense anyway. How should users of your class that include the header file know about those functions and use them?

Upvotes: 0

Related Questions