Understanding of the objects creation in c++ - c++

If i have a class name app and a class name manager. I want to create inside manager class an app class, I've seen two options but I didn't understand the difference.
choice 1:
//.....
class app; //writing this line outside the declaration of the func
class manager{
//..
private:
app *a;
//...
}
or choice 2:
class manager{
//..
private:
app *a;
//..
}

I think you're talking about forward declaration. If so, then read this:
C++ INCLUDE Rule : Use forward declaration when possible
Read also this FAQ:
[39.12] What special considerations are needed when forward declarations are used with member objects?

The class app; outside your class manager { ... } is a forward declaration. It tells the compiler, "app is a class. I'm not going to tell you what it looks like, but trust me, it is."
Think of your compiler as only knowing about this particular file (which I am assuming is a .h file) when it compiles. You have said that your member class includes a pointer to an "app". "What the heck is an app?" the compiler wants to know. Without the forward declaration (or perhaps an #include app.h or something similar), it doesn't know, and will fail to compile. By saying at the top, class app;, it knows that app is a class. That's all it needs to know to allocate the space for a pointer to it in your member class.

Look, your "choice 2" isn't valid C++. Who knows what was on your mind... Maybe you wanted to write something like this:
class manager {
//..
private:
class app *a;
//..
}
In this case we define pointer to app class, which is unknown here. This can be used instead of #include "app.h", because all pointers are of the same size and you can define a pointer without defining that app class. Your first example does the same thing, but allows you to omit class word in all subsequent definitions of pointers to it.

The first example includes a forward declaration of the class app so that you can declare pointers to it in later code. The second example doesn't mention app at all before you attempt to use it, so the compiler will not accept it. The compiler needs to know what the name app refers to before you can use it to declare additional things.
Since you're only declaring a pointer, you don't yet need to have a full declaration of app. But in order for your program to fully compile and link, you'll need to define app eventually. Possibly within the same file, or possibly in some other file. But somewhere before you attempt to create an instance of that class or use any of its member variables and functions.

Related

Clarification on classes and scopes in this scenario

I'm currently working with the JUCE Framework to create an audio VST plugin to get to grips and learn, but just want to clarify some basic stuff relating to classes.
in my header file, i have a class EQPLUGProcessor and inside that class i call static juce::AudioProcessorValueTreeState::ParameterLayout createParameterLayout();
When i call the function createParameterLayout() in my .cpp i have to write juce::AudioProcessorValueTreeState::ParameterLayout EQPLUGAudioProcessor::createParameterLayout(){}
My question is, why do i have to include the juce::AudioProcessorValueTreeState::ParameterLayout before the actual scope that the function is in ( EQPLUGAudioProcessor)? Surely i should be telling the compiler to look in the EQPLUGAudioProcessor and thats it?
I get that EQPLUGAudioProcessor is the class which its all inside, but still cant seem to understand when, where and why i'd need to clarify the classes that the function comes from again in the .cpp?
Let me know if this requires clarification.
An enclosing namespace or a class does not have to be specified only inside the same namespace or a class:
class store {
class give_me {
// ...
};
static give_me something_cool();
};
Here, the declaration of something_cool() only needs to reference give_me, rather than store::give_me. This is because this declaration appears inside the declaration of its class.
Now that this class is declared, and it's time to define it's class method, everything must be spelled out:
store::give_me store::something_cool()
{
// ...
}
If the class method returned a void instead you'l still have to write something like:
void store::something_cool()
{
// ...
}
You already understand that you can't just write void something_cool() and define this class method. This would only define some unrelated function with this name.
You have to write store::something_cool because this definition no longer appears within the store scope.
Well, the same thing applies not just to class methods but also to inner classes (and also other kinds of symbols that are declared in some enclosing scope). Since give_me is not a class that's declared in global scope, it is an inner class, when in global scope you must reference it as store::give_me.
That's just how C++ works. There are also various complicated rules that define where a scope begins, and ends, with respect to C++'s syntax, that's tangentially related to this. In some cases it is possible to take advantage of these scoping rules and avoding explicit scope references by using an auto declaration with a trailing return type; but how to do that will have to be a different question for some other time.

typedef structs declared inside class or outside?

I'm creating a class called ImageLoader that will be used to load various image formats. For various image formats there are certain structs used. For example with bmp files you have a BITMAPFILEHEADER struct and two others.
What I want to know is, when I'm putting my class definition in the header file, do I make the struct typedefs part of the class definition, or should they be separate, outside the class definition?
I'm not sure because if I was just declaring a struct variable, that would obviously happen in the class, but because I'm defining a type, I'm not sure if it's considered good design to define a type inside a class.
My general rule is that if it will only be used in conjunction with that class, then declare it inside (it implies ownership); otherwise declare it separately.
You get better encapsulation if you leave out everything from the header that you possibly can. Even if some methods of your class need parameters or return types of the struct, you might get away with a forward declaration.
The only time you need to put it in the header is when it's part of the public interface.
As to whether it goes in the class or not, consider whether it's useful on its own or if it is totally subservient to the class. If it can stand alone it should probably go in its own header.
I would not say that declaring a type in a class is an indicator of bad design. Assuming that your mention of "design" means something along the lines of "readability", I would be a stickler for consistency and insist that the same relationships be expressed in the same way.
Otherwise, you are not going to be struck down by a divine wrath for nesting types (Considering SGI is not a smoldering crater). This is pretty context-centric, so there are no hard and fast rules outside of what you define based on your requirements.
If client accessibility is not an issue, I declare most everything in an appropriate scope in headers and just document what my code means. Again, this is if I do not have strict usage/readability guidelines to enforce. I'd go with Mark's suggestion if I did.
Two cents: You could try enumerating image types and using one public struct for config data so that you could justify pulling everything else behind closed doors.
BITMAPFILEHEADER is a structure defined in the Win32 Platform SDK. I'm not sure I've understood your request about it and your class...
In general, if you are defining structures that are not exposed to the client of your class, I'd define them in the private part of your class, or in a sub-namespace Details in your header file, e.g.:
namespace YourCoolLibrary
{
namespace Details
{
struct SomeInternalStructure
{
...
};
} // namespace Details
class YourCoolClass
{
...
private:
Details::SomeInternalStructure m_something;
};
} // namespace YourCoolLibrary
There are even many more choices. If you put it in the class you have to choose if it's public, protected, or private making the class definition visible for every user of the class, only derived classes or no other classes.
If you do not need the details of the class definition I'd put only forward declarations into ImageLoader to keep it simpler. The full definition of the inner class then goes into the implementation file.
My rule of thumb is to make names as local as possible, so if I use it accidentally at the wrong place the compiler will complain.
If the typedef logically belongs into the class you are creating, put it inside; if it would make sense on a global level, leave it outside.

forward declare static function c++

I want to forward declare a static member function of a class in another file. What I WANT to do looks like this:
BigMassiveHeader.h:
class foo
{
static void init_foos();
}
Main.cpp:
class foo;
void foo::init_foos();
int main(char** argv, int argc)
{
foo::init_foos()
}
This fails out with "error C2027: use of undefined type 'foo'"
Is there a way to accomplish what I want to do with out making init_foos a free function, or including BigMassiveHeader.h? (BigMassiveHeader.h is noticeably effecting compile time, and is included everywhere.)
You cannot forward declare members of a class, regardless of whether they are static or not.
You can't forward declare members of your class but you could make a namespace and a function inside of that namespace and forward declare that.
namespace nsfoo
{
void init_foos();
}
Your class if needed could friend this function.
If you have a BigMassiveHeader, you should consider splitting it up into several SmallCompactHeaders. If you want to express that many classes and functions belong together semantically, you can put them in the same namespace. You can always provide a convenience-header that includes all your small headers.
You can't partially declare classes in C++, so either you'll have to put the class's declaration in its own, smaller header, or...
Include BigMassiveHeader.h in your file and use precompiled headers.
The Visual C++ way: http://msdn.microsoft.com/en-us/library/2yzw0wyd%28v=VS.71%29.aspx, or the GCC way: http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html.
I know it's not the point of the question, but if BigMassiveHeader.h is not likely to change much over time, you should take a look at precompiled headers
As a first refactoring, I'd use a free function which calls the static function. It's not like your main method is getting called lots of times, so you won't notice an extra call, and that makes the least change to the existing code.
Of course, you don't actually say what you are trying to do, only what you want to do. If what you are trying to do is get init_foos called once on application start, use static object initialisation for that, rather than calling it in main. If what you are trying to do is get init_foos called after all static objects are created, then it's more complicated.
By static object initialisation, I mean something like having this in a .cpp file which has access to the definition of init_foos. Make it a friend and init_foos private to prevent multiple calls:
struct call_init_foos {
call_init_foos () { foo::init_foos(); }
} call_init_foos_on_startup;
to forward declaration of a single method of a class, you must declare the method as part of the class (as it really is).
for example, in your case, add to main.cpp:
class foo
{
public:
static void init_foos();
}
its not the prettiest, but it will save you having to include the whole header..
No, you need to include the header for that. Sorry.
Use a free function if you must, or split the class.

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.
%

Forward declare pointers-to-structs in C++

I am using a 3rd party library that has a declaration like this:
typedef struct {} __INTERNAL_DATA, *HandleType;
And I'd like to create a class that takes a HandleType in the constructor:
class Foo
{
Foo(HandleType h);
}
without including the header that defines HandleType. Normally, I'd just forward-declare such a type, but I can't figure out the syntax for this. I really want to say something like:
struct *HandleType;
But that says "Expected identifier before *" in GCC. The only solution I can see is to write my class like this:
struct __INTERNAL_DATA;
class Foo
{
Foo(__INTERNAL_DATA *h);
}
But this relies on internal details of the library. That is to say, it uses the name __INTERNAL_DATA, which is an implementation detail.
It seems like it should be possible to forward-declare HandleType (part of the public API) without using __INTERNAL_DATA (part of the implementation of the library.) Anyone know how?
EDIT: Added more detail about what I'm looking for.
Update:
I am using it in the implementation .cpp of Foo, but I want to avoid including it in my header .h for Foo. Maybe I'm just being too pedantic? :)
Yes you are :) Go ahead with forward declaration.
If HandleType is part of the interface there must be a header declaring that. Use that header.
Your problem is still a vague one. You are trying to protect against something you cannot.
You can add the following line to your client library:
typedef struct INTERNAL_DATA *HandleType;
but, if the name/structure changes you may be in for some casting nastiness.
Try templates:
template <class T>
class Foo
{
Foo(T h);
};
Forward declaration is fine. If you are going to use pointers or references you only need a class (__INTERNAL_DATA) declaration in scope. However, if you are going to use a member function or an object you will need to include the header.
If the type is in a 3rd party library then the big benefit of forward declaration (isolating rebuilds due to changes in headers) is effectively lost.
If you're worried about compilation times (it's a sizeable header) then perhaps you can place it in a precompiled header or just include the relevant header from a library.
E.g. many library headers look like
// library.h
#include "Library/Something.h"
#include "Library/SomethingElse.h"
typedef struct {} __INTERNAL_DATA, *HandleType;
If it is defined like that (all on one line), then __INTERNAL DATA is as much a part of the public interface as HandleType.
However, I don't think __INTERNAL_DATA actually exists. More than likely, HandleType is really (internally) an int. This odd definition is just a way of defining it so that it's the same size as an int, but distinct, so that the compiler give you an error if you try passing an int where you're supposed to pass an HandleType. The library vendor could just as easily have defined it as "int" or "void*", but this way we get some type checking.
Hence __INTERNAL_DATA is just a convention and is not going to change.
UPDATE: The above was a bit of a mental burp... OK, __INTERNAL_DATA definitely does not exist. We know this for a fact, because we can see it's definition as an empty struct. I'm going to guess that the 3rd-party library uses "C" external linkage (no name managling), in which case, just copy the typedef -- it will be fine.
Inside the library itself, HandleType will have a completely different definition; maybe int, maybe "struct MyStruct {.......} *".
If you really, really, really don't want to expose _INTERNAL_DATA to the caller then your only real choice is to use typedef void* HandleType; Then inside your library you can do anything you want including changing the entire implementation of *HandleType.
Just create a helper function to access you real data.
inline _INTERNAL_DATA* Impl(HandleType h) {
return static_cast<_INTERNAL_DATA*>(h);
}
I'm not quite sure what you're going for, but the following will work without including the actual header file:
// foo.h
class Foo
{
public:
template<typename T>Foo(T* h) { /* body of constructor */ }
};
Mind you, you will still have to have access the public members of __INTERNAL_DATA within the body of the constructor.
edit: as pointed out by James Curran, the __INTERNAL_DATA structure has no members, so it can be used, as above, with no problems.