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

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

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.

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(); }

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.

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?

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.

Related

Preventing library internal stuff from beeing visible in .h

First things first: I know thats it's quite probable that my question is based on a general missunderstanding, but I hope I can make my point clear to you.
I know that when putting code into diffrent files in C++ we have do create a .h (for Definitions) and a .cpp (for implementations).
When writing a class-library for example I have to put a definitioj of both, private and public members in the header. But what to do if - for some reason - I want to hide the private things from the user?
Thanks!
You use the Pimpl idiom. Pimpl stands for "pointer to implementation". Basically, you don't store the implementation details in the class. Instead you store an opaque pointer to implementation as such:
class MyClass
{
public:
//public functions here
private:
class Impl; //no definition, opaque
Impl* pimpl;
};
And then you go on to define your MyClass::Impl class in the .cpp file only, because only the function definitions need it.
The PIMPL idiom has the additional benefit that as long as the interface of the class does not change, any changes made to the implementation do not require the recompilation of class clients.
You can't. This is one of the drawbacks of C++: things marked private are still part of the class declaration and so will be present in the header.
If you really want to hide the functionality, then using the pImpl Idiom can help. Personally though I prefer to live with the drawback as using the idiom can cause other problems such as your class no longer being trivially copyable.
See Why should the "PIMPL" idiom be used?

What are benefits of using PrivateClass containing data of the Class?

class MyClassPrivate
{
//My members.
};
//and then
class MyClass {
private:
MyClassPrivate* const d;
};
What is the reason of using this 'pattern'? How it's correctly called?
This is called "Pointer to implementation" or "pimpl". See http://en.wikibooks.org/wiki/C++_Programming/Idioms#Pointer_To_Implementation_.28pImpl.29
When you use this pattern you would forward declare the implementation class, and declare the body elsewhere, i.e.:
// header
class MyClassPrivate;
class MyClass {
public:
MyClass();
~MyClass();
private:
MyClassPrivate* const d;
};
// cpp
class MyClassPrivate {
};
MyClass::MyClass() : d(new MyClassPrivate) {}
MyClass::~MyClass() { delete d; }
The advantage of doing this is that the implementation of MyClass is not exposed to other users of MyClass. If the implementation changes, the other users of MyClass does not need to be recompiled. Any header files that has to be included for members also need not be exposed, which improves compilation time.
The most usage is Pimlp idiom.
Why should the “PIMPL” idiom be used?
Pimpl idiom
The Pimpl
The Pimpl idiom describes a way for making your header files
impervious to change. You often hear advices like "Avoid change your
public interface!" So you can modify your private interface, but how
can you avoid recompilation when your header file defines the private
methods. This is what the Pimpl does – Reduce compilation damages when
your private interface changes[3].
From Here:
Benefits:
Changing private member variables of a class does not require recompiling classes that depend on it, thus make times are faster, and the FragileBinaryInterfaceProblem is reduced.
The header file does not need to #include classes that are used 'by value' in private member variables, thus compile times are faster.
This is sorta like the way SmallTalk automatically handles classes... more pure encapsulation.
Drawbacks:
More work for the implementer.
Doesn't work for 'protected' members where access by subclasses is required.
Somewhat harder to read code, since some information is no longer in the header file.
Run-time performance is slightly compromised due to the pointer indirection, especially if function calls are virtual (branch prediction for indirect branches is generally poor).
How to do it:
Put all the private member variables into a struct.
Put the struct definition in the .cpp file.
In the header file, put only the ForwardDeclaration of the struct.
In the class definition, declare a (smart) pointer to the struct as the only private member variable.
The constructors for the class need to create the struct.
The destructor of the class needs to destroy the struct (possibly implicitly due to use of a smart pointer).
The assignment operator and CopyConstructor need to copy the struct appropriately or else be disabled.
You can use this for the PIMPL idiom, when you want to separate interface from iplementation.
Many design patterns use a "pointer" to a private attribute as well, such as the Strategy Pattern. This patterns allows you to select a different algorithm at run-time.
Also, if you make the manipulation of your data adhere to the same interface, you can encapsulate the data in a Private Class, make this class a part of a hierarchy and switch between different data implementations during run time (or compile time for that matter :)).
A good example of this is a geometrical class that holds data on polygons. Each Polygon provides access to the points, you can also delete the Polygon edge and do various other topological operations. If you provide an abstract base class for the Polygon class with the methods such as deletePoint, addPoint, swapEdge, you can test different Polygon implementations.
You may define a polygon as a list of Point types directly, and store the points in different contaienrs (list or vector). The Polygon class may be defined via indirect addressing, where the polygon is actually a list of IDs to the list of points (I am talking about lists in the general sense). This way, you can test different algorithms of the PolygonGeometry class and see how they work with differtn Polygon implementations.
There is a design principle behind this: Prefer Composition to Inheritance. Whenever you are using Composition and you are relying on the type to be deterimined at run-time, you will have a private attribute pointer.

C++: Why must private functions be declared?

Why do classes in C++ have to declare their private functions? Has it actual technical reasons (what is its role at compile time) or is it simply for consistency's sake?
I asked why private functions had to be declared at all, as they don't add anything (neither object size nor vtable entry) for other translation units to know
If you think about it, this is similar to declaring some functions static in a file. It's not visible from the outside, but it is important for the compiler itself. The compiler wants to know the signature of the function before it can use it. That's why you declare functions in the first place. Remember that C++ compilers are one pass, which means everything has to be declared before it is used.1
From the programmer's point of view, declaring private functions is still not completely useless. Imagine 2 classes, one of which is the friend of the other. The friendzoned class2 would need to know how the privates of that class look like, (This discussion is getting weird) otherwise they can't use it.
As to why exactly C++ was designed in this way, I would first say there is the historical reason: the fact that you can't slice a struct in C, was adopted by C++ so you can't slice a class (and adopted by other languages branched from C++, too). I'd also guess that it's about simplicity: Imagine how difficult it would be to devise a method of compilation in which you can split the class among different header files, let your source files know about it, and prevent others from adding stuff to your class.
A final note is that, private functions can affect vtable size. That is, if they are virtual.
1 Actually not entirely. If you have inline functions in the class, they can refer to functions later defined in the same class. But probably the idea started from single pass and this exception later added to it.
2 It's inlined member functions in particular.
You have to declare all members in the definition of the class itself so that the compiler knows which functions are allowed to be members. Otherwise, a second programmer could (accidentally?) come along and add members, make mistakes, and violate your object's guarantees, causing undefined behavior and/or random crashes.
There's a combination of concerns, but:
C++ doesn't let you re-open a class to declare new members in it after its initial definition.
C++ doesn't let you have different definitions of a class in different translation units that combine to form a program.
Therefore:
Any private member functions that the .cpp file wants declared in the class need to be defined in the .h file, which every user of the class sees too.
From the POV of practical binary compatibility: as David says in a comment, private virtual functions affect the size and layout of the vtable of this class and any classes that use it as a base. So the compiler needs to know about them even when compiling code that can't call them.
Could C++ have been invented differently, to allow the .cpp file to reopen the class and add certain kinds of additional member functions, with the implementation required to arrange that this doesn't break binary compatibility? Could the one definition rule be relaxed, to allow definitions that differ in certain ways? For example, static member functions and non-virtual non-static member functions.
Probably yes to both. I don't think there's any technical obstacle, although the current ODR is very strict about what makes a definition "different" (and hence is very generous to implementations in allowing binary incompatibilities between very similar-looking definitions). I think the text to introduce this kind of exception to the rule would be complex.
Ultimately it might come down to, "the designers wanted it that way", or it might be that someone tried it and encountered an obstacle that I haven't thought of.
The access level does not affect visibility. Private functions are visible to external code and may be selected by overload resolution (which would then result in an access violoation error):
class A {
void F(int i) {}
public:
void F(unsigned i) {}
};
int main() {
A a;
a.F(1); // error, void A::F(int) is private
}
Imagine the confusion when this works:
class A {
public:
void F(unsigned i) {}
};
int main() {
A a;
a.F(1);
}
// add private F overload to A
void A::F(int i) {}
But changing it to the first code causes overload resolution to select a different function. And what about the following example?
class A {
public:
void F(unsigned i) {}
};
// add private F overload to A
void A::F(int i) {}
int main() {
A a;
a.F(1);
}
Or here's another example of this going wrong:
// A.h
class A {
public:
void g() { f(1); }
void f(unsigned);
};
// A_private_interface.h
class A;
void A::f(int);
// A.cpp
#include "A_private_interface.h"
#include "A.h"
void A::f(int) {}
void A::f(unsigned) {}
// main.cpp
#include "A.h"
int main() {
A().g();
}
One reason is that in C++ friends can access your privates. For friends to access them, friends have to know about them.
Private members of a class are still members of the class, so they must be declared, as the implementation of other public members might depend on that private method. Declaring them will allow the compiler to understand a call to that function as a member function call.
If you have a method that only is used int the .cpp file and does not depend on direct access to other private members of the class, consider moving it to an anonymous namespace. Then, it does not need to be declared in the header file.
There are a couple of reason on why private functions must be declared.
First Compile Time Error Checks
the point of access modifiers is to catch certain classes (no pun intended) of programming errors at compile time. Private functions are functions that, if someone called them from outside the class, that would be a bug, and you want to know about it as early as possible.
Second Casting and Inheritance
Taken from the C++ standard:
3 [ Note: A member of a private base class might be inaccessible as an inherited member name, but accessible directly. Because of the rules on pointer conversions (4.10) and explicit casts (5.4), a conversion from a pointer to a derived class to a pointer to an inaccessible base class might be ill-formed if an implicit conversion is used, but well-formed if an explicit cast is used.
3rd Friends
Friends show each other there privates. A private method can be call by another class that is a friend.
4th General Sanity and Good Design
Ever worked on a project with another 100 developers. Having a standard and a general set of rule helps maintain maintainable. declaring something private has a specific meaning to everyone else in the group.
Also this flows into good OO design principles. What to expose and what not

A few questions about C++ classes

I have two basic questions. The first one is about function in other classes. If I have a header file with a class in it and I want to use that function in another class I have created, do I always have to construct a class object to run a function in that class like:
someclass class; <----object construction
class.somefunction();
Is there a way just to call the function with the object construction?
And the second question is it okay to put multiple small classes in one header file?
Functions should only be member functions if they act on an object of the class. Functions that don't act on an object should just be plain global functions (or class static):
// Global function
void foo() { /* do something */ }
// Static function
class Foo
{
public:
static void foo() { /* do something */ }
};
For your second question, yes it's ok. Generally people stick to one class per file, but in my opinion there's nothing wrong with having a few small classes in a single file.
If your function is declared static then you don't need an object instance to call it.
class Foo
{
public:
static void Bar() {}
};
// ...later
Foo::Bar();
To answer your second question, yes it's sometimes ok. I've done that before with small utility structs that are related to each other. Usually I'm just being lazy and don't want to bother making separate files.
Is there a way just to call the function with the object construction?
Only if the function is declared static. (ok, that's a lie, its possible without constucting a object if you subvert the type system, but it's not a good idea)
And the second question is it okay to put multiple small classes in one header file?
Sure, it's done all of the time.
1 static as already mentioned
2 do what feels natural. Keep related classes together. One of the problems with JAva is its fanatical enforcement of one class per file
However - unforgivable sin is spreading the implementation of class a throughout the implementations of classes b c and d
Ie all of a class implementation should be in one .cpp file.
delcare the function as static.
Are you talking about inner classes? If thats the case, then its totally legit.

Can I transform an object and access the private data members in C++?

I want to access a private data member in a class. There is no member function in the class to access the private data member. It is private.
I want to take the class and some how crack it open. One method was to copy the declaration of the class, make the private member public and call the new class class something_else. Then I do a reinterpret cast and copy the original object. This works. But I want something more elegant ... or perhaps generic ... or just another way.
What options are there? Can I use void*? Can I memcpy the class into another empty class? What are ways to do this??
%
I am assuming that
You've already been through "breaking encapsulation is bad" stage,
Exhausted other possible solutions,
Can't change class' header.
There are a few ways to subvert access to a class's private members, as demonstrated in GotW #76.
Duplicate a class definition and add a friend declaration.
Use evil macros: #define private public before including class' header.
Write a class definition with identical binary layout and use reinterpret_cast to switch from original class to a fake one.
Specialize a template member function if there is one (the only portable solution).
With the idea you suggest in your question, you don't need to copy the original object. If you write your own "all public" variation of the real class declaration, then cast a pointer to that new type, you can directly access the object through it.
The reason why none of this is a good idea is simple. You must be manipulating objects of a class of which you don't control the source (otherwise you'd be able to modify the source to give you the access you need). But if you don't control the source, then what if the maintainers change the layout of their class? Your duplicated version will no longer match up, and there will be no way for the compiler to detect this mismatch. The result will probably be memory corruption at runtime.
Since it's incorrectly understood, I have to clarify. All the following solutions do not require you to recompile the object. To use a class in your code, if it's compiled into an object file, you should include header file with the declaration of that class.
#include <class.h>
ObjectFoo instance;
It is possible (but dangerous unless you're careful) to change the header (a) or copy the header to another place and include that header (b), without recompiling the class itself.
#include <class_fixed.h>
ObjectFoo instance;
Your code, where you included the new header will just think that within the object file (which you haven't recompiled!) he will find implementation of the class declared as in class_fixed.h. While there persists the class declared as in class.h. If you change offsets of members (add new members for example) in your new header, you're dead and the code will not work properly. But just changing the access works fine. Compiled code doesn't know about access, this matters only at the compilation strange.
This is not always harmful. In everyday life you encounter such a change when you install new version of a library into your system and do not recompile all programs that depend on it. But it should be handled with care
There are several solutions.
memcpy()Don't! Do not memcpy as object copying sometimes undergoes specific policy imposed by the class designer. For example, auto_ptrs can't be just memcopied: if you memcopy the auto_ptr and then destructor is ran for both, you'll attempt to free the same memory two times and the program will crash.
Change private: to public: in header or with macroIf your license permits it, you may solve your problem by editing the header file that comes with the implementation of the class. Whether the source code of the implementation (i.e. cpp-file of the class) is under your control doesn't matter: changing private to public for data members (in header) suffices and works just fine even if you're given a binary-only library that contains class definition. (For member functions changing access sometimes changes its internal name, but for MSVS and GCC it's ok.)
Adding a new getter functionWhile changing private to public is nearly always ok (unless you rely on specific compile-time checks that should break the compilation if class has certain member accessible), adding new getter function should be performed carefully. The getter function should be inline (and therefore defined in the header file of the class).
reinterpret_castThe cast works just fine if you're NOT casting a pointer to dynamic base class (dynamic means "with virtual functions or bases") whose actual instance at the moment of casting can be derived from the class at the particular piece of code.
protected:And just in case you forgot. C++ can declare members protected:, i.e. accessible only to the classes derived from the given. This may fulfill your needs.
You can, but you shouldn't. The objects are just memory. You can certainly cast the pointer into an equivalent class that has the same members but where everything is public. But why do you want to do this? Do you have somebody else's code that you need to work with? Get them to add proper accessor methods. Do you really need to treat them as public members? Change the class.
I'm not really sure what you are trying to do, but it's probably a mistake.
I agree with the "edit the source" comment, but I think you should add a method, not just comment out the 'private'.
You must have the declaration of the class, so you presumably have the header but possibly not the .cpp/whatever file. Add an inline member function to the class in a copy of the header, and include this header instead of the original. You should still be able to link to the object file for the inaccessible source code.
Of course this counts as an evil hack, bypassing the protections built into the language rather than working with them. That's why I suggest the minimally evil hack - don't make everything private, and if you can get away with a getter (but no setter) do that. Of course the real minimal evil is not to do it, if there's any way at all to avoid it.
Remember, if this is someone elses class you're working with, the next version might be implemented differently and might not have that member at all.
Thank you ... I did want to show the code for my original fix. The reason as someone aluded to is that I cannot change the original code ... so I have to do a jail break.
#include<iostream>
using namespace std;
// Class Objectfoo
// Pretend Objectfoo lives somewhere else ... I cannot open him up
class ObjectFoo
{
private:
int datax;
public:
ObjectFoo() { datax = 100; }
void get() { cout << datax << endl;}
};
// Class ObjectBar
class ObjectBar
{
public:
int datax;
};
ObjectFoo FOOEY;
ObjectBar* touch_foo(int x, ObjectFoo* foo , ObjectBar* bar)
{
bar = reinterpret_cast<ObjectBar*>(foo);
bar->datax = x;
return bar;
}
int main()
{
ObjectBar* bar;
cout << "Displaying private member in ObjectFoo i.e. ObjectFoo.datax" << endl;
FOOEY.get();
cout << "Changing private member " << endl;
bar = touch_foo(5, &FOOEY, bar);
cout << "bar->datax = " << bar->datax << endl;
cout << "Displaying private member in ObjectFoo i.e. ObjectFoo.datax" << endl;
FOOEY.get();
return 0;
}
This works ... but I think I want something more generic ... or more flexible.
%