question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,849,961
1,849,967
Disallow any member function to change its data members in C++ Class
So how i can do this? So that no member function can change the value of its data members once object has been initialized in C++.
Make all the member functions const. That's the only mechanism for the job, and it works just fine. If you also make them private you're completely covered. If for some reason you feel compelled to mark them protected, then things are more complicated. You will need to make the individual fields const, and that will in...
1,849,991
1,850,002
Best practices: Where should function comments go in C/C++ code?
So... I understand this might be subjective, but I'd like some opinions on what the best practice for this is. Say I have the following header and .cpp file: header: // foo.h class foo { public: int bar(int in); }; cpp: // foo.cpp int foo::bar(int in) { // some algorithm here which modifies in and returns th...
I put comments describing what the function does in the header and comments describing how it does it in the cpp file.
1,850,192
1,850,552
Correct way to write console applications on GNU/Linux with C++
I really like the console and got recently hooked on programming console applications using nCurses mainly in conjunction with the C programming language. Unfortunately i think the ncurses API is totally borked and very hard to use, and the C++ bindings are undocumented. So my question is, what is THE API to use for C...
maybe you'd like s-lang better?
1,850,227
1,850,285
Cross language development problem
I'm working on a project that involves a database (My SQL), website (PHP) and a custom high performance server application (C++). The C++ application (and its accompanying client application) make up the main bulk of the project, with the database storing long term data for it. The website is primarily for displaying v...
You might try not allowing PHP to access the database at all. Make the C++ app do all the database work, and make it serve data to the PHP site. You could run part of the C++ app as a server for the PHP to fetch reports etc from it.
1,850,636
1,850,664
Conditional compilation
How do I add conditional compilation to my makefile: say if I have a #ifdef SAVE_DATA in a cpp (.cc) file.
Usually something like CXXFLAGS+=-DSAVE_DATA
1,850,809
1,850,825
Static struct linker error
I'm trying to create a static struct in C++: static struct Brushes { static HBRUSH white ; static HBRUSH yellow ; } ; But its not working, I'm getting: Error 4 error LNK2001: unresolved external symbol "public: static struct HBRUSH__ * Brushes::white" Why? The idea is to be able to use Brushes::white, Brushes::...
You have to define the static members somewhere, usually in the .cxx file, e.g.: HBRUSH Brushes::white; The reason is that the header file doesn't make the definition, it only declares it.
1,851,034
1,851,068
USB How do you create a bootable custom USB application?
Many LCD televisions nowadays have USB ports so you can plug in your camera and it becomes a camera gallery on the TV. I want to write a gallery program which, when plugged in to the TV, will start to cycle through the images on the USB device. How would I do this? Is it possible to write some sort of OS/application ...
That would depend entirely on the television's firmware whether it would even be supported. If it were, the specification of how to do it would need to be observed.
1,851,053
1,851,923
Calling static pointer to a list from a shared library in c++
I have a static class member class bar {...} class foo { public: static QHash<qint64,bar>* barRepHash; } Now I call a function which accesses this member within a shared library, I get a memory error whereas when I access the function through the main program, it works fine. I've tested this under a numb...
IIRC the exe and shared library will get their own copies of static member variables like that, and that as such you will need to initialise it separately in each case. Since its a pointer, one way may be to initialise it in your main program as normal and then pass the pointer to the dll when you load it so that the d...
1,851,078
1,851,118
Random bytes with fread
#post The names of my variables are not imporant! This code will be deleted when it works! #post Alright, so I'm using fread in stdio.h to read a text file. The problem is that I keep reading random bytes that don't exist in the text file from my knowledge. I'm assuming they are part of files scheme, but I just wanna m...
A couple of weird things here: int i = 0; for(i=0;i<alen;++i) { fread(&cha[i],sizeof(CHR),bsize,inFile); printf("[%i]%s",i,cha[i]); } You don't null terminate the buffer before printing it (as RageZ pointed out). You increment i on each loop repetition, but every time you read 84 chars (bsize) into &cha[i]. I t...
1,851,167
1,851,220
Algorithm for finding path to point
I'm not sure if I worded this properly, but basically I have an object at point X,Y and I want an algorithm that can get this point to X',Y' but like show its route so I can animate it. I'm building a tile game and when the game starts I want the tiles to magically place themselves into a nice 2d array. So I will gener...
It sounds like you just want a linear transformation. Like Xt = (((X'-X)/T)*t)+X, Yt = (((Y'-Y)/T)*t)+Y Or in English the coordinate for a tile at time t is t/total_frames length along it's path. A* is overkill if you aren't trying to avoid obstacles.
1,851,267
1,851,334
MinGW/GCC Delay Loaded DLL equivalent?
I'm trying to port some old MSVC C++ code to MinGW/GCC. One problem is that the project relies heavily on the /DELAYLOAD option for functions that aren't always used, and where the proper dll is located at runtime. Is there such a similar option on MinGW/GCC? This code is targeting the windows platform.
On elf targets (for Unix-like systems), you can specify the -z lazy option (which is the default anyway) with ld (the linker that MinGW also uses). As far as I know, the i386 PE target (for Windows) does not have an explicit lazy linking option. I can find no documentation of it being available.
1,851,279
1,852,123
What is the recommended way of passing keyboad events to QProcess transparently?
I have a GUI application, which creates a QProcess inside, catches its output and shows it on a form. I need to somehow catch key events from the form to pass them to QProcess (to make it fell as close as possible to real terminal window). So, I suppose, I should process keyReleaseEvent() and somehow transform either e...
The problem is more than just deciding what to write to the process. You can't emulate a terminal just by reading/writing stdout/stdin of a process, it's more complicated than that. Think about the program less, or any pager, for example. How does it know how many lines to print at a time? It needs information about...
1,851,315
3,398,066
Boost's Interpreter.hpp example with class member functions
Boost comes with an example file in boost_1_41_0\libs\function_types\example called interpreter.hpp and interpreter_example.hpp I am trying to create a situation where I have a bunch of functions of different arguments, return types, etc all register and be recorded to a single location. Then have the ability to pu...
I've been working on this issue and i've somewhat succeeded to make the boost interpreter accept the member function such as: // Registers a function with the interpreter, // will not compile if it's a member function. template<typename Function> typename boost::enable_if< ft::is_nonmember_callable_builtin<Function> >...
1,851,355
1,851,381
Converting STL String, and STL Vector into void*?
Ive got some C++ code, that we use to serialize arbitrary data and store it into a specialized image format as metadata. Anyways, it takes it as a void*. Can i just do a simple memcpy? Or is there a better way to do this?
For std::string you can use c_str() to obtain the char* pointing to the internal string. For std::vector the standard dictates that the elements are contiguous in memory and so you can access the pointer to the beginning of the data as &v[0]. You should of course be careful with these since you are basically handing th...
1,851,468
1,851,482
Usage of 'short' in C++
Why is it that for any numeric input we prefer an int rather than short, even if the input is of very few integers. The size of short is 2 bytes on my x86 and 4 bytes for int, shouldn't it be better and faster to allocate than an int? Or I am wrong in saying that short is not used?
CPUs are usually fastest when dealing with their "native" integer size. So even though a short may be smaller than an int, the int is probably closer to the native size of a register in your CPU, and therefore is likely to be the most efficient of the two. In a typical 32-bit CPU architecture, to load a 32-bit value re...
1,851,525
1,851,599
C++ can native type char hold End of File character?
The title is pretty self explanatory. char c = std::cin.peek(); // sets c equal to character in stream I just realized that perhaps native type char can't hold the EOF. thanks, nmr
Short answer: No. Use int instead of char. Slightly longer answer: No. If you can get either a character or the value EOF from a function, such as C's getchar and C++'s peek, clearly a normal char variable won't be enough to hold both all valid characters and the value EOF. Even longer answer: It depends, but it will n...
1,851,863
1,851,877
reasons for choosing com
i was wondering why one would choose Com as his software development "technology" my first though is machine/programming _language independence what's yours ?
COM is the de facto standard for automation and IPC on windows (though .Net has begun to shift the focus), thus there are areas you simply don't have (or had) a choice: Shell extensions ActiveX builds on COM Internet Explorer extensions extending MS Office applications Scriptability for JScript, VBScript, ... with one...
1,852,243
1,852,280
qt soap client + ASP.net Web service
I'm writing Qt client for ASP.NET web service with FORMS based authentication. The service consists of 3 methods: Login(user,pass) Helloworld() - this method returns info about authenticated user. Logout() Every thing working fine on the dot.net client with CookieContainer. The problem begins with HelloWorld() metho...
Are you running IIS or the ASP.NET Development server? I was able to recreate a similar problem where everything worked fine using ASP.NET Development server but under IIS the session was null. One thing to look for is when you invoke the session-enabled-service you should see the ASP.NET_SessionId being set in the r...
1,852,302
1,852,310
A proposal to add statemachine support to C++-like language
Lately as part of my day job I've been learning IBM Rhapsody and using it to generate code in C++ from the UML. Yesterday it struck me that it might be cool to think about adding state machine support to my C++ compiler, so I jotted a few notes here: http://ellcc.org/wiki/index.php/State_machines_and_Active_Classes My ...
With a few exceptions, C++ has traditionally been extended using class libraries, not new keywords. State machines can easily be implemented using such libraries, so I don't think your proposal has much of a chance. One problem I see in your proposal is the use of 'goto' to go to another state. What happens if I want t...
1,852,556
1,852,576
Casting a pointer to a sub-class (C++)
I'm developing a game and I need to find a way of getting the value of a certain 'map block' in the game (in char format). I have a class DisplayableObject which takes care of all sprites, and a sub-class ThreeDCubePlayer which takes care of the player object. For ease of rendering/updating everything, all DisplayableO...
Use one of the type safe casts, e.g. dynamic_cast instead of the C-style cast. If m_ppDisplayableObjects is a DisplayableObject**, then it would look something like this: ThreeDCubePlayer* cubePlayer = dynamic_cast<ThreeDCubePlayer*>(m_ppDisplayableObjects[0]); if (cubePlayer != NULL) { char mapEntry = GetMapEntry...
1,852,624
3,356,692
Play RTP video stream using Qt?
I want to create a Qt widget that can play incoming RTP streams where the video is encoded as H264 and contains no audio. My basic plan for implementation is this: Create a Phonon MediaSource object (Stream type). Connect it with a QIODevice subclass that provides the data Obtain the video data using either: The JRT...
I was able to get it to work using the libVLC solution. I can't garantuee that this is the best solution though as I simply stopped looking after that. Here's a link to the libVLC sample.
1,852,652
1,852,702
How can I #include a file whose name is built up from a macro?
On a cross-platform project, I want to #include a header file whose name contains the name of the platform. I have a #define macro for the platform. So for example, for #define PLATFORM win32 I want #include "engine\win32\devices_win32.h" while for #define PLATFORM linux I want #include "engine\linux\devices_linux.h...
#define PLATFORM Linux #define xstr(x) #x #define str(x) xstr(x) #define sub(x) x #define FILE str(sub(engine/PLATFORM/devices_)PLATFORM.h) #include FILE I'm not sure I'd use it, though. ;-) I had to use Linux rather than linux because linux is defined as 1 in my compiler.
1,852,655
1,852,700
How to create an SDL pop up menu?
I've seached around how to create a pop up menu in a SDL window application using c++ ? I haven't found any clues ! I would like to have something that looks like this : http://www.youtube.com/watch?v=Mc_CE9OiHvA I've tried to use glutMenu, but it doesn't work ... Thanks
SDL is a low-level graphics library. I don't remember seeing anything like menus, buttons, or other GUI controls in it last time I used it. It's possible that one of the many add-on libraries has menuing functions. Generally, you're expected to build such things yourself from primitives SDL provides. One add-on libr...
1,852,744
1,852,779
Where do data files go so the Microsoft Visual C++ 2008 debugger can find them?
I am writing code that opens an istream object on a file specified by the user. I want to be able to run the program in the debugger and just type the filename (eg data.txt) at the prompt, not the whole path. I haven't worked out how to do this inside the IDE so I have been saving my .txt file to the debug folder and r...
you can set the working path of the executable (project properties->Debugging->Working Directory), which leads the debugger to start the executable with that path as working directory. This has the advantage that if you set the same path for all your configurations (Debug/Release/...), you only need 1 data.txt on your ...
1,852,752
1,852,765
Appending an int to a wchar_t*? ..unresolved, lack of concrete example
I am building a string of int values, stored in a wchar_t*. If I have an integer, how can I append it onto the end of a wchar_t*? Windows only solutions are fine for this and I'd rather not include boost :)
Use a wide version of stringstream and the '<<' operator. The correct operator to perform the conversion for you should be defined. If I am missing some subtlety here you could depend on boost and use this. I'm still a fan of secure versions of sprintf and so is Herb Sutter :D.
1,852,801
1,852,820
How do I modify the internal buffer of std::cin
I am writing a software that grabs a password using std::cin However unlikely, i am trying to avoid the possibility that the password get paged to the disk from memory so I want to modify the buffer of std::cin to overwrite the password as soon as I'm done with it. right now i have this: std::cin.clear(); std::stringst...
You can use gptr() and egptr() to get the beginning and end of the buffer. Edit: As Charles Bailey pointed out, these are protected. My assumption is that if you want a stream buffer that you can clear its contents at a specified time, that you'd be implementing one of your own that derives from one of the standard str...
1,852,856
1,852,868
Linker error 'unresolved external symbol' : working with templates
I have a template based class [Allotter.h & Allotter.cpp]: template <typename allotType> class Allotter { public: Allotter(); quint32 getAllotment(allotType*); bool removeAllotment(quint32, int auto_destruct = 0); private: QVector<QPair<quint32, allotType*>> indexReg; int init_topIndex; }; and it's usage is show...
You cannot split templates into .h and .cpp files - you need to put the complete code for the template in the .h file.
1,852,934
1,852,986
Finding the command line options a process was launched with
I'm trying to find out how to do this, I'm currently using CreateToolHelp32SnapShot to get a list of the running processes and I've got the FilePaths of the executables which are currently running, but I need to be able to find out what command line options were used to start the process. I know its possible since you ...
check if NtQueryInformationProcess and ReadProcessMemory win API calls will do what you need. There is no simple example for that so check the source code here: Get Process Info with NtQueryInformationProcess another way for getting this data is throgh WMI, smth like this: SELECT CommandLine FROM Win32_Process WHERE Pr...
1,853,062
1,854,104
c++: Operator overloading and error handling
I am currently starting to look into operator overloading in c++ for a simple 2D vertex class where the position should be available with the [] operator. That generally works, but I dont really know how to deal with errors for instance if the operator is out of bounds (in the case of a 2D vertex class which only has x...
Error handling is a tricky beast in the best of times. It pretty much boils down to how big a deal the error is, and what if anything is expected to happen with it when it occurs. There are four basic paths you can follow: Throw an exception The sledgehammer of error handling. A great tool, definitely want to use i...
1,853,082
1,853,680
search a Binary search tree
I am trying to find a name within a key. I think it is retrieving it fine. however, its coming up as not found. maybe my code is wrong somewhere? if (database.retrieve(name, aData)) // both contain the match in main() static void retrieveItem(char *name, data& aData) { cout << ">>> retrieve " << name << endl << endl;...
You should be using the BST to navigate through the tree - not looping over each item in your array, like others have said. Try something like: bool retrieve(key, aData) retrieve(key, aData, parent) if (key == aData) return true else return false bool retrieve(key, aData, parent) if (key == items[paren...
1,853,121
1,853,158
Should a function's comment include descriptions of work done by functions it calls?
Let's say I have a function called DisplayWhiskers() which puts some slashes and backslashes on the screen to represent an animal's whiskers like this: /// \\\. I might write a comment for this function along the lines of // Represents an animal's whiskers by displaying three // slashes followed by a space and three ...
Your functions should ideally do one thing only, whatever a "thing" may be and at what level of granularity. Similarly, they should be described at the appropriate level of granularity. If you're printing out an ASCII kitten, you can leave that as the description for DisplayKitten(). You don't have to describe every ...
1,853,148
1,853,238
Disable Exceptions in BOOST?
I want to use boost::asio but I don't want boost to throw exceptions, because in my environment exceptions must not be raised. I've encountered BOOST_NO_EXCEPTIONS but the documentation says that callers of throw_exception can assume that this function never returns. But how can a user supplied function not return? Wh...
Either you terminate the process or you goto a something like a global error handler using longjmp which you've previously defined with setjmp.
1,853,358
1,857,314
Use a regular iterator to iterate backwards, or struggle with reverse_iterator?
I recently learned about the right way to work with reverse iterators in C++ (specifically when you need to erase one). (See this question and this one.) This is how you're supposed to do it: typedef std::vector<int> IV; for (IV::reverse_iterator rit = iv.rbegin(), rend = iv.rend(); rit != rend; ++rit) { // Use...
The reason for reverse iterators is that the standard algorithms do not know how to iterate over a collection backwards. For example: #include <string> #include <algorithm> std::wstring foo(L"This is a test, with two letter a's involved."); std::find(foo.begin(), foo.end(), L'a'); // Returns an iterator pointing ...
1,853,584
1,853,795
Using AlphaBlend() and FillRect()
So, I'm using AlphaBlend() to copy a rectangle from one HBITMAP to another. It works, but there is a problem. Whenever I use the FillRect() function, the alpha values in the HBITMAP get slammed out to 0. Everytime. So I have to GetDIBits(), reset the alpha back to 255, and then SetDIBits(), after every call to the Wi...
With the exception of AlphaBlend... BitBlt is the only other GDI function that will preserve the alpha channel in any way. Your options basically therefore are: Switch to using DIBSections. This will not solve the basic problem of GDI apis overwiting the alpha channel, but as a DIBSection you can avoid the costly DDB ...
1,853,619
1,853,638
Strange characters appear when using strcat function in C++
I am a newbie to C++ and learning from the MSDN C++ Beginner's Guide. While trying the strcat function it works but I get three strange characters at the beginning. Here is my code #include <iostream> #include <cstdio> #include <cstring> using namespace std; int main() { char first_name[40],last_name[40],full_nam...
The array that you are creating is full of random data. C++ will allocate the space for the data but does not initialize the array with known data. The strcat will attach the data to the end of the string (the first '\0') as the array of characters has not been initialized (and is full of random data) this will not be ...
1,853,658
1,853,666
binary '=': no operator found which takes a right-hand operand of type "Button *"
I've got a Menu class which is a singleton. It is now going to have three Button objects on it, m_Load, m_Save, m_New. I am calling their constructors in an Init() method like so: void Menu::Init() { Menu::m_Load = new Button(L"../Data/png/load.png"); Menu::m_Save = new Button(L"../Data/png/save.png"); Me...
You're trying to assign a pointer to a Button to a Button. Declare your button members as pointers. Button *m_Load;
1,853,788
1,855,127
Design choice with a container class that several classes use
I have a class that wraps around a list called ExplosionGroup (previously called AllExplosions for reasons I'll explain) which is a list of 'Explosion's (another class). My original design choice, and what ran for awhile, was to have an ExplosionGroup in the 'Level' class that runs all the levels. Any classes (like shi...
I have no answers, just some questions that would help others (and maybe also yourself) to find a good answer. What are the exact steps that have to be performed in order to show an explosion? What are my invariants here? (e.g. are all explosions the same, are the object-specific, dependant on time or position on the ...
1,853,906
1,854,158
How to implement class composition in C++?
If I understand correctly we have at least two different ways of implementing composition. (The case of implementation with smart pointers is excluded for simplicity. I almost don't use STL and have no desire to learn it.) Let's have a look at Wikipedia example: class Car { private: Carburetor* itsCarb; public:...
In that case we have an object itself as private member. (By the way, calling this entity as object am I write from the terminology point of view?) Yes you can say "an object" or "an instance" of the class. You can also talk about including the data member "by value" instead of "by pointer" (because "by pointer" and ...
1,854,006
1,872,341
C++ : When do I need a shared memory allocator for std::vector?
First_Layer I have a win32 dll written in VC++6 service pack 6. Let's call this dll as FirstLayer. I do not have access to FirstLayer's source code but I need to call it from managed code. The problem is that FirstLayer makes heavy use of std::vector and std::string as function arguments and there is no way of marshali...
I have found a solution for the problem. Basically, the StdVectorWrapper class which I wrote do not implement deep copy. So all I need to do is to add the following to the StdVectorWrapper class to implement deep copy. Copy Constructor Assignment Operator Deconstructor Edit: Alternative Solution An even better solut...
1,854,113
1,854,138
ostringstream problem with int in c++
I would expect the following code to output hello5. Instead, it only outputs hello. It seems to be a problem with trying to output an int to the ostringstream. When I output the same directly to cout I receive the expected input. Using XCode 3.2 on Snow Leopard. Thanks! #include <iostream> #include <string> #include <s...
Changing the Active Configuration in XCode from 'Debug' to 'Release' works as a workaround.
1,854,115
1,854,163
boost.asio tcp sockets, Will asynchronous operations be ordered?
If am am calling boost::asio::async_write/async_read directly after each other, will the data be ordered? Or do I need to wait on the callback before I am calling write/read again? Thanks in advance!
The data is not guaranteed to be ordered and if you are using those functions you should wait for the callback before writing again. (Discussion in terms of async_write, also applies to async_read) Because async_write is implemented in terms of multiple calls to the underlying stream's async_write_some function, those ...
1,854,164
1,957,704
How to use boost::function_types::parameter_types with ClassTypeTransform
I have been toying with an example hpp provided in the boost library and I am trying to figure out how to use this parameter_types function correctly. From the boost doc, parameter_types needs a ClassTypeTransform in order to parse class member function signatures. I want to parse member function signatures, but I ca...
ClassTransform is simply used to modify the first argument type in case parameter_types<> is applied to a member function pointer type. The default is add_reference<_>, so for instance: parameter_types<void(X::*)(int)>::type -> SomeSequence<void, X&, int> parameter_types<void(X::*)(int), mpl::identity<_> >::type -> Som...
1,854,241
1,854,250
How to set a default parameter for a vector <string> for use in a default constructor within a class?
For example, a class named Table, with its constructor being: Table(string name="", vector <string> mods); How would I initialize the vector to be empty? Edit: Forgot to mention this was C++.
Table(string name="", vector <string> mods); if you want vector to be empty inside constructor then mods.clear(); or mods.swap(vector<string>()); In case you want as a default parameter: Table(string name="", vector<string> mods = vector<string>()); Like any other default parameter.
1,854,251
1,855,146
Why doesn't this compile?
When I try to declare iss using the first form, g++ gives me "error: no match for 'operator>>' in 'iss >> s'". But don't the two different declarations do the same thing? #include <iostream> #include <sstream> #include <string> int main() { const char *buf = "hello world"; std::string ss(buf); //std::istr...
This is known as the "most vexing parse" of C++: what looks like an instance declaration to you actually looks like a function declaration to the compiler. std::string name(); //function declaration std::string name; //object declaration with default constructor std::stringstream ss(std::string(buf)); //function dec...
1,854,290
1,854,305
Combine native DLL and assembly into a single DLL
I am currently programming in C++ and C#. Using native C++ for the numerical computing part. Originally I intended to use C++/CLI to make a wrapper to the native C++ classes, but I found it would result in a 2 to 4 times slowdown. So I decided to compile my native C++ to a DLL and call in .NET/C# via P/Invoke. I will ...
You can mix languages in the same assembly in .NET but not naturally. I would avoid this unless absolutely necessary. See: http://www.hanselman.com/blog/MixingLanguagesInASingleAssemblyInVisualStudioSeamlesslyWithILMergeAndMSBuild.aspx I keep assemblies from different languages separate.
1,854,304
1,854,343
C++ : How to include boost library header in VC++6?
I used this guide to rebuild the boost library in VC++6 under windows XP. But is having problems trying to include the header files. By default, the boost library makes use of point 1 as follows to declare the header files. But if I used point 1, I get "fatal error C1083: Cannot open include file...". I tried using poi...
Did you add the boost include path to your project? If you try to compile your program from Visual Studio you can add extra include paths in the global options (menus: Tools -> Options -> Directories -> Show directories for: Include files). If you will also make use of the compiled boost libraries (e.g. for boost::fil...
1,854,323
1,868,240
Recommendation for C++ wrapper for cross platform in-process dynamic library bindings (i.e. a lightweight, high performance COM or CORBA)
We're developing an application that will have a plug-in "architecture" to allow consumers of the app to provide their own proprietary algorithms. (We will basically have a set of parsers and allow third parties to provide their own as well) The domain space requires very high performance, so out-of-process bindings a...
I think this might also work: http://pocoproject.org/docs/Poco.SharedLibrary.html
1,854,335
1,854,337
How to create a Java class, similar to a C++ template class?
How do I write an equivalent of this in Java? // C++ Code template< class T > class SomeClass { private: T data; public: SomeClass() { } void set(T data_) { data = data_; } };
class SomeClass<T> { private T data; public SomeClass() { } public void set(T data_) { data = data_; } } You probably also want to make the class itself public, but that's pretty much the literal translation into Java. There are other differences between C++ templates and Java generics, but none of tho...
1,854,439
1,854,460
Method not being called in switch statement
Edit: Works perfectly in debugger now, but block doesn't rotate at all when run normally.. I'm having a problem that I've run through the debugger a ton and have narrowed it down to this. I've got a block on screen that comes down in the middle and rotates. The image of the block obviously changes depends on the rotati...
Your code seems unnecessarily long and repetitive. It should be refactored: image = NULL; switch ( m_CurrentRotation ) { case BossRotation_ZeroDegrees: { image = BossFiveImage::p_ZeroDegrees; break; } case BossRotation_NinetyDegrees: { image = BossFiveImage::p_NinetyDegrees; break; } case BossRotatio...
1,854,444
1,854,664
Compiling SDL on OS X with makefile
I'm trying to compile the tetris program I wrote with C++ and SDL on OS X. First I tried doing this: `g++ -o tetris main.cpp `sdl-config --cflags --libs` -framework Cocoa` and got this: Undefined symbols: "Game::startGame()", referenced from: _main in ccQMhbGx.o "Game::Game()", referenced from: _main i...
I think your compile issue is related to the SDL main function. The compile failure is because you're missing references to "Game.o" or whatever the object file resulted out of compiling Game.cpp is called. Try: g++ -o tetris main.cpp Game.o Pieces.o Whateverelse.o `sdl-config --cflags --libs` -framework Cocoa
1,854,499
1,854,509
Is string::compare reliable to determine alphabetical order?
Simply put, if the input is always in the same case (here, lower case), and if the characters are always ASCII, can one use string::compare to determine reliably the alphabetical order of two strings? Thus, with stringA.compare(stringB) if the result is 0, they are the same, if it is negative, stringA comes before stri...
According to the docs at cplusplus.com, The member function returns 0 if all the characters in the compared contents compare equal, a negative value if the first character that does not match compares to less in the object than in the comparing string, and a positive value in the opposite case. So it wi...
1,854,575
1,854,591
glBitmap() without GL_COLOR_INDEX
Is it somehow possible to get glBitmap() to draw a GL_RGBA bitmap? glBitmap() is a lot quicker than glDrawPixels(), but perhaps that has to do with that the format is GL_COLOR_INDEX instead of GL_RGBA? I'm running my glDrawPixels() in a display list; is there perhaps some smart way to speed it up?
From the documentation: "A bitmap is a binary image" - Here a "binary image" simply means an image in which every pixel has exactly two possible colors which map to "transparent" and "the current raster color". You can't paint anything else using this function. Some other things you can try to achieve the same effect, ...
1,854,711
1,855,269
How to check if a Graph is a Planar Graph or not?
I'm learning about the Planar Graph and coloring in c++. But i don't know install the algorithm to do this work. Someone please help me? Here i have some information for you! This is my code! And it still has a function does not finish. If someone know what is a "Planar Graph", please fix the Planar_Graph function belo...
Regarding planarity... The well known e <= 3v - 6 criteria by Euller mentioned here says that if a graph is planar, then that condition must hold. However, not all graphs in which that condition holds are necessarily planar. That is why you actually need a planarity test algorithm. A thing to notice is that planarity t...
1,855,459
1,855,465
maximum value of int
Is there any code to find the maximum value of integer (accordingly to the compiler) in C/C++ like Integer.MaxValue function in java?
In C++: #include <limits> then use int imin = std::numeric_limits<int>::min(); // minimum value int imax = std::numeric_limits<int>::max(); std::numeric_limits is a template type which can be instantiated with other types: float fmin = std::numeric_limits<float>::min(); // minimum positive value float fmax = std::num...
1,855,472
1,855,503
antlr : C++ target with visual studio 2008
the Antlr site is not clear on the subject of compiling a grammar for C++, it says that the tool will generate C code compatible with C++, what dose it mean? will I be able to compile this code with VS 2008 ?
VS 2008 has both C and C++ compiler (and C++ compiler can compile C code, this is what they meant), I don't think you'll have any problems. They say: "C target as of release 3.1 is C++ compatible, compile .c files as C++. C+ classes will be provided as a separate library later in 2008." Meaning it's C++ compatible.
1,855,482
1,855,538
How to properly initialize class value member?
lets say we have this: class Foo { public: Foo(const Bar& b) : m_bar(b) {} private: Bar m_bar; }; Now regarding efficiency C++ FAQ LITE says this: Consider the following constructor that initializes member object "x" using an initialization list: Fred::Fred() : x(whatever) { }. The most common benef...
I'll break it down into performance and semantic differences, as you requested: Should the constructor better have the parameter as value instead of reference? Unless it is a primitive type or small struct, it should have the parameter passed by const reference. Passing by reference gives you a performance difference...
1,855,628
1,855,644
Network protocol object serialization in C++
I'm writing some C++ code that will have to send data over TCP/IP. I want this code to be portable on Linux/Windows/Osx. Now, as it is the first time I write portable network code, I basically need some simple functions to add to certain objects like: class myclass{ ...member... public: string serialize(){ std...
Why do it all manually if there are great libraries like Boost.Serialization that you can build on? From their goals: Data Portability - Streams of bytes created on one platform should be readable on any other. Also of interest for you might be points 4 and 5: Deep pointer save and restore. That is, save and restor...
1,855,704
1,855,756
C++ binary file I/O to/from containers (other than char *) using STL algorithms
I'm attempting a simple test of binary file I/O using the STL copy algorithm to copy data to/from containers and a binary file. See below: 1 #include <iostream> 2 #include <iterator> 3 #include <fstream> 4 #include <vector> 5 #include <algorithm> 6 7 using namespace std; 8 9 typedef std::ostream_iterator<doub...
For the question 1) You need to specify a separator (for example a space). The non-decimal part was stuck to the decimal part of the previous number. Casting and using NULL is generally wrong in C++. Should have been a hint ;) copy (vd.begin(), vd.end(), oi_t(output, " ")); For the question 2) #include <iomanip> outp...
1,855,725
1,855,750
Assigning a "const char*" to std::string is allowed, but assigning to std::wstring doesn't compile. Why?
I assumed that std::wstring and std::string both provide more or less the same interface. So I tried to enable unicode capabilities for our application # ifdef APP_USE_UNICODE typedef std::wstring AppStringType; # else typedef std::string AppStringType; # endif However that gives me a lot of compile errors wh...
The relevant part of the string API is this constructor: basic_string(const charT*); For std::string, charT is char. For std::wstring it's wchar_t. So the reason it doesn't compile is that wstring doesn't have a char* constructor. Why doesn't wstring have a char* constructor? There is no one unique way to convert a st...
1,855,773
1,855,981
Avoid slicing of exception types (C++)
I am designing an exception hierarchy in C++ for my library. The "hierarchy" is 4 classes derived from std::runtime_error. I would like to avoid the slicing problem for the exception classes so made the copy constructors protected. But apparently gcc requires to call the copy constructor when throwing instances of them...
I would steer clear of designing an exception hierarchy distinct to your library. Use the std::exception hierarchy as much as possible and always derive your exceptions from something within that hierarchy. You might want to read the exceptions portion of Marshall Cline's C++ FAQ - read FAQ 17.6, 17.9, 17.10, and 17....
1,855,859
1,855,989
Curving from one point to another
I have tiles that are in random spots, and they wind up at x',y' (to make a nice 2d array) by doing : Xt = (((X′-X)/T)*t)+X , Yt = (((Y′-Y)/T)*t)+Y This works well, but it is linear. I'm looking for something curvier. A little bit like a parabola works. Basically instead of getting to X' in a straight line, I'm loo...
You're looking for Bezier Curves, or some other similar parametric curve. These are programatically quite easy to code and have the advantage of being intuitively straightforward to manipulate. The best treatise I know of is in the classic book Mathematical Elements of Computer Graphics, but any textbook on computer ...
1,855,885
1,855,897
How do I get \0 off my string from C++ when read in C#
I'm kind of stuck here. I'm developing a custom Pipleline component for Commerce Server 2009, but that has little to do with my problem. In the setup of the pipe, I give the user a windows form to enter some values for configuration. One of those values is a URL for a SharePoint site. Commerce Server uses C++ compon...
Would this help: string sFixedUrl = "hello\0\0".Trim('\0');
1,855,948
1,855,966
instantiated from here error
my compiler is torturing me with this instantiation error which I completely don't understand. i have template class listItem: template <class T> class tListItem{ public: tListItem(T t){tData=t; next=0;} tListItem *next; T data(){return tData;} private: T tData; }; if i try to i...
As it stands, your code needs a default constructor for the type T. Change your template constructor to: tListItem(T t) : tData(t), next(0) {} The difference being that your version default constructs an instance of type T and then assigns to it. My version uses an initialisation list to copy construct the instance,...
1,855,951
1,856,401
Sharing object by reference or pointer
Say I have an object of type A having Initialize() method. The method receives object B, which are kept as the object data member. B object is shared between several objects, thus A should contain the originally received B object and not its copy. class A { public: bool Initialize(B?? b); ...
I'd stay with pointer. Reference here just sends wrong message. You don't use references to object in situations when you plan to take pointer to object and keep or share it, etc. Main reason for references in C++ is allowing things like operator overloading and copy constructors to work for user defined types. Without...
1,856,013
1,856,034
What is the C++ equivalent of C# Collection<T> and how do you use it?
I have the need to store a list/collection/array of dynamically created objects of a certain base type in C++ (and I'm new to C++). In C# I'd use a generic collection, what do I use in C++? I know I can use an array: SomeBase* _anArrayOfBase = new SomeBase[max]; But I don't get anything 'for free' with this - in othe...
There is std::vector which is a wrapper around an array, but it can expand and will do automatically. However, it is a very expensive operation, so if you are going to do a lot of insertion or removal operations, don't use a vector. (You can use the reserve function, to reserve a certain amount of space) std::list is a...
1,856,307
1,856,479
To iterate or to use a counter, that is the question
Whenever someone starts using the STL and they have a vector, you usually see: vector<int> vec ; //... code ... for( vector<int>::iterator iter = vec.begin() ; iter != vec.end() ; ++iter ) { // do stuff } I just find that whole vector<int>::iterator syntax sickitating. I know you can typedef vector<in...
When you use index to perform essentially sequential access to a container (std::vector or anything else) you are imposing the random-access requirement onto the underlying data structure, when in fact you don't need this kind of access in your algorithm. Random-access requirement is pretty strong requirement, compared...
1,856,309
1,856,543
C++ Overloading the >> operator
I need to overload the stream extraction operator. I need to do this by allowing a user to input a string of characters at a prompt, say "iamastring", and then the operator would extract each character from the string and test whether or not it is whitespace and if it is not whitespace store it in a character array wh...
It's quite funny - your name is like mine, but reversed :) How about: char buffer[buffSize+1]; // no need for dynamic allocation here unsigned i = 0; while(std::cin && !std::isspace(std::cin.peek()) && i < buffSize) buffer[i++] = std::cin.get(); buffer[i] = '\0'; // null termination can be important. // i now contain...
1,856,468
1,856,541
How to output IEEE-754 format integer as a float
I have a unsigned long integer value which represents a float using IEEE-754 format. What is the quickest way of printing it out as a float in C++? I know one way, but am wondering if there is a convenient utility in C++ that would be better. Example of the way that I know is: union { unsigned long ul; float f;...
The union method you suggested is the usual route that most people would take. However, it's technically undefined behavior in C/C++ to read a different member from a union than the one that was most recently written. Despite this, though, it's well-supported among pretty much all compilers. Casting pointers, as Jon ...
1,856,529
1,856,871
How to use DLL library file in a C++ project?
I have a C++ project and a DLL library made using C#. Is it possible to add it to the C++ project and use its methods? I am using Visual Studio 2008
http://support.microsoft.com/kb/828736
1,856,567
1,856,574
Passing an iterator to another function
I was wondering what would be the best way to accomplish something like this... // Iterating through a list if ( foo ) { RemoveBar( it ); } void RemoveBar( std::list< Type >::iterator it ) { it = listName.erase( it ); ...// Other stuff related to cleaning up the removed iterator } I don't think pass by value w...
Iterators are normally passed by value. I'd make RemoveBar() return the new iterator.
1,856,597
1,856,619
What _can_ I use as std::map keys?
Extends. I have: struct Coord { int row, col ; bool operator<( const Coord& other ) const { return row < other.row && col < other.col ; } } ; I'm trying to create a map<Coord, Node*>, where you can look up a Node* by Coord. The problem is, it has bugs. Lookups into the map<Coord, Node*> by Coord are ret...
Yes you could very well have a problem with strict-weak ordering. Odds are its not working like you'd expect. Consider: bool operator<( const Coord& other ) const { return row < other.row && col < other.col ; } obj1 (this) row: 2 col: 3 obj2 row: 3 col: 2 obj1 < obj2? => false ok well then: obj2 < obj1? => f...
1,856,600
2,174,595
Qt, text on a black and white screen
I'm using Qt (embedded) to make a GUI on a black and white screen. The problem is Qt renders text with shades of grey so it is unreadable on the black and white screen. Does anyone have any idea how to make the text just use 1 bit per pixel, or purely black and white? Thanks, Mark
Incase anyone sees this trying to do the same thing - Turning off AA and setting the supported bit depths to only 1 will not work, virtually all fonts just have grey in them, and if so you can't use them. Best solution is to just create your own purely black and white fonts as a bdf with a 96 resolution (fontforge is g...
1,856,640
1,856,968
The procedure entry point _ftol2 could not be located in the dynamic link library msvcrt.dll
I've recently been tinkering with a little gameproject using VC++ 2008. I'm using SDL, OpenGL, Boost and Box2D as included libraries. It works fine on my windows 7 machine, aswell as a friend's w7 machine. How ever it wont work on my second friend's XP sp3 machine, with the vc++ 2008 SP1 redist pack installed. When he ...
I shouldn't have included the opengl32.dll from my system with my game. The opengl32.dll on XP is an older version and is properly linked with the MSVCRT.dll on XP aswell. When I included the windows 7 opengl32.dll it simply didn't match with the xp dlls. Removing the opengl32.dll and glu32.dll from my game folder solv...
1,856,646
1,856,689
Is it allowed to inherit from a class in the std namespace (namely std::wstring)?
The class std::wstring is missing some operations for "normal" c strings (and literals). I would like to add these missing operations in my own custom class: #include <string> class CustomWString : public std::wstring { public: CustomWString(const char*); const char* c_str(void); }; ...
The compiler definitely lets you, as there is no way to seal a class with a public constructor in C++. STL containers are not designed for inheritance, so it's generally a bad idea. C++ has to many strange corners to ignore that. Your derived class might break with another STL implementation, or just with an update of ...
1,856,680
1,856,764
Origin of term "reference" as in "pass-by-reference"
Java/C# language lawyers like to say that their language passes references by value. This would mean that a "reference" is an object-pointer which is copied when calling a function. Meanwhile, in C++ (and also in a more dynamic form in Perl and PHP) a reference is an alias to some other name (or run-time value in the d...
There is an early usage of the term "call by reference" in the paper "Semantic Models of Parameter Passing" by Richard E Fairley, March 1973. In the early days, the terminology was inconsistent. For example, the Fortran 66 specification uses the phrases "association by name" and "association by value". We would now c...
1,856,727
1,856,747
Can more than one boost::signal be connected to 1 slot?
i know i can connect multiple slots to the same signal. but Can I do it the other way round? having 3 signals connected to the same slot? anyone ever tried this? thanks a lot!
There is nothing preventing you from connecting more than one signal to a slot. Do it if you need to, it'll work fine.
1,856,892
2,182,290
Problem in accessing members of class in C# DLL from C++ project
I have added a C# DLL into a C++ project as mentioned at MS support, however I was not able to access its variables and methods inside the class. It also says that it's a struct and not a class, I don't know if it is important but I thought I should mention it is as well. Whenever I write . or -> or :: after the object...
Starting with Visual Studio 2005, you can use C++/CLI, Microsoft's ECMA-approved C++ dialect that allows using managed and unmanaged code together. In VS2005, there are the "Managed Extensions for C++", with which you can achieve roughly the same, but you have to use horribly-looking syntaxes for writing managed code i...
1,856,947
1,856,964
Displaying multiple icons in a single cell of a QTableView
I am writing a small gui app with QT4.5 in QtCreator. The main screen on the app contains a QTreeView with two columns, the first is text the second is a group of icons. These icons represent the last few states of the item displayed in the row. I am not sure what the best way to do this is. I have currently implemen...
I would create a custom delegate, based on a hbox, into which you can place all the pictures. Have a look at delegates in the Qt Documentation about model view programming.
1,857,292
1,857,310
How do you get the location, in x-y coordinate pixels, of a mouse click?
In C++ (WIN32), how can I get the (X,y) coordinate of a mouse click on the screen?
Assuming the plain Win32 API, use this in your handler for WM_LBUTTONDOWN: xPos = GET_X_LPARAM(lParam); yPos = GET_Y_LPARAM(lParam);
1,857,458
1,858,763
CDirScan function NextL raises KERN-EXEC 0
CDirScan function NextL raises "Main Panic KERN-EXEC 0" if it is not called right away SetScanDataL() (i.e. if it is called later within the same active object after another event) f1() - called within active object iDirScan = CDirScan::NewLC(aFs); iDirScan->SetScanDataL(aPath, KEntryAttDir|KEntryAttMatchExclusiv...
I wrote some test code in an attempt to reproduce this but couldn't. Generally, KERN-EXEC 0 panics are most often caused by stale R object handles. For example, make sure that the RFs handle you pass to CDirScan is not closed too early.
1,857,484
1,858,466
C++0x, Compiler hooks and hard coded languages features
I'm a little curious about some of the new features of C++0x. In particular range-based for loops and initializer lists. Both features require a user-defined class in order to function correctly. I came accross this post, and while the top-answer was helpful. I don't know if it's entirely correct (I'm probably just com...
I'm not wrong in thinking that these new features do infact rely extremely heavily on compiler code They do rely extremely on the compiler. Whether you need to include a header or not, the fact is that in both cases, the syntax would be a parsing error with today compilers. The for (:) does not quite fit into todays ...
1,857,668
1,866,668
C++ Visual Studio character encoding issues
Not being able to wrap my head around this one is a real source of shame... I'm working with a French version of Visual Studio (2008), in a French Windows (XP). French accents put in strings sent to the output window get corrupted. Ditto input from the output window. Typical character encoding issue, I enter ANSI, get ...
Before I go any further, I should mention that what you are doing is not c/c++ compliant. The specification states in 2.2 what character sets are valid in source code. It ain't much in there, and all the characters used are in ascii. So... Everything below is about a specific implementation (as it happens, VC2008 on a ...
1,857,673
1,857,681
How can I implement scripting in my game?
I'm trying to write a game and implement scripting so that later on in development I won't have to recompile everything when I want to change numbers. My problem is that I don't know how scripts should interface with the game. The scripting language I'm using is angelscript. Right now, I have a state: the intro state, ...
There's no correct answer to such a large question really. You do it the same way you would do engine/game logic separation in C++. Define an API that the script can call that allows it whatever it is you want it to do. Register functions in that API with the script, and use the API in angelscript. What that API sh...
1,857,721
1,857,766
how to synchronize a varied number of threads?
Could someone please help me with synchronizing varied number of threads? The problem is when the number of threads can vary from one to 9 and when for instance two clients are connected to server, the communication should be synchronized in this form : client1, client2, client1, client2 ... until the communication is ...
I actually don't understand well how the threads should be synchronized. If there is some block of code that needs to be done in a serialized manner then the pthread_mutex_lock should be good enough. If the order of operation should be preserved (1,2,3,1,2,3) I suggest using pthread_mutex_lock along with some variable ...
1,857,850
1,857,947
Deleting And Reconstructing Singleton in C++
I have an application which runs on a controlling hardware connected with different sensors. On loading the application, it checks the individual sensors one by one to see whether there is proper communication with the sensor according to predefined protocol or not. Now, I have implemented the code for checking the ind...
fflush clears the output buffer. If you want to clear the input buffer, you're going to need to read the data or seek to the end. I'm not convinced the "Singleton" pattern is appropriate. There are other ways of ensuring at most one instance for each piece of hardware. What if you later want multiple threads, each work...
1,858,141
1,858,544
Is UnregisterHotKey() important for clean up?
Simple question I think, after I have registered a few system-wide hotkeys with RegisterHotKey() do I need to eventually call UnregisterHotKey() to clean them up, or can I simply exit my application without worrying about it? MSDN doesn't seem to say, that or I misunderstand it, anyways: I realize I should just go ahea...
If the MSDN doesn't explicitly tell you to unregister, then it's probably safe to just quit. The MSDN is usually pretty good at pointing things like this out. However, I also use RegisterHotKey and I always make sure to call UnRegisterHotKey when my application quits as you never know if not doing do will cause you p...
1,858,297
1,858,325
What is the best LALR parser generator for C++ that can generate meaningful error messages
I am looking for the best solution for a LALR parser generator for C++ that will allow me to generate really good error messages. I really hate the syntax errors that MySQL generates and I want to take the parser in it and replace it with a "lint" checker that will tell me more than just ERROR 1064 (42000): You have ...
Why do you require LALR? One of the benefits of LL(k) parsers is that they can often make it easier to generate clear error messages. Most grammars that can be parsed by an LALR parser can be easily refactored to be parsable by an LL(k) parser. ANTLR is a popular LL(k) parser generator that can generate C++ (as well as...
1,858,364
1,858,375
how to bias a random number generator
i am using the random number generator provided with stl c++. how do we bias it so that it produces smaller random numbers with a greater probability than larger random numbers.
Well, in this case you probably would like a certain probability distribution. You can generate any distribution from a uniform random number generator, the question is only how it should look like. Rejection sampling is a common way of generating distributions that are hard to describe otherwise, but in your case some...
1,858,419
1,858,862
Reopening a closed Piped read file descriptor?
I have used pipes to facilitate interprocess communication. They work just fine. But in my scenario I want to close and reopen the read end of the file descriptor fd[0]. Does anyone know how to do that?
You cannot reopen an unnamed pipe. If you really need to do this reopening magic, consider using named pipes, that can be opened and reopened as many times as you wish. But before doing it, consider whether it makes any sense at all.
1,858,500
1,858,535
Small question concerning redefining member functions
I'm trying to redefine two member functions from their parent's definition.I don't know if I have it right or not, but something in my code has errors attached and I can't find out what. some of the header: class Account { public: Account(double); void creditBalance(double); void debitBalance(double); doub...
If the intention is that for instances of CheckingAccount accounts the versions which use a fee is called, then you want to use virtual methods. A virtual method is a method decalared (at least in the base class) as "virtual", and has the same name and signiture in any derived classes. When a virtual method is called, ...
1,858,571
1,858,765
C++ Duplicate Symbol error when defining static class variable in XCode
I have a static class member incremented in the constructor. As per the rules, it is declared in the class and defined outside. This should be totally legal. Any ideas why I'm getting a duplicate symbol error? class Player { private: static int numPlayers; public: Player() { numPlayers++; } }; int Pl...
The problem is that you are not separating your DECLARATION from your DEFINITION. Consider: class Player { private: static int numPlayers; public: Player() { numPlayers++; } }; The code above merely declares the existence of "numPlayers" in the class "Player". It does not, however, reserve any space...
1,858,639
1,858,876
Shall I place try...catch block in destructor, if I know my function won't throw exception
I know destructor shouldn't not throw exception. http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.13 I have the following code : ~a() { cleanup(); } // I do not expect exception being thrown in this function. // If exception really happen, I know that it is something not recoverable. void a::cleaup() { ...
Since delete won't throw, neither will cleanup and as such there is no need to put the call in try-catch. Since your static analysis tool is probably having a hard time figuring that out, perhaps you could help it out (it's only a guess though) by declaring cleanup as no-throw. void cleanup() throw();
1,858,727
1,861,703
Connecting and Fetching a record form sequel server 2005
I have a windows application in visual C++. I am not using MFC, in this application I have connect to SQL server 2005 and fetch records form a database file. Can any one guide me how this can done. Thanks in advance.
I would say, you could use some wrapper framework around the odbc calls. Currently I was working on a project where SQL server communication was involved so I found this wrapper framework: TinyODBC which is a minimalistic ODBC wrapper library. It's pretty trivial how can one use it, but I have to admit I had to patch i...
1,858,778
1,877,384
How can I simplify my C++ code to reverse characters?
Hello I have this program which reverses letters I enter. I'm using iostream. Can I do it another way and replace iostream and cin.getline with cin >> X? My code: //Header Files #include<iostream> #include<string> using namespace std; //Recursive Function definition which is taking a reference //type of input st...
below function gets line from standard input, reverses it and writes to stdout #include <algorithm> #include <string> #include <iostream> int main() { std::string line; std::getline( std::cin, line ); std::reverse( line.begin(), line.end() ); std::cout << line << std::endl; }
1,858,963
1,859,026
Vectors, "virtual", Segmentation Fault on function call
I'm getting a Segmentation Fault when trying to call a function that is within a object that is part of a vector of "Shape" Pointers My problem is in this function:: Point findIntersection(Point p, Point vecDir, int *status) { Point noPt; for (int i = 0; i < shapes.size(); i++) { ...
The problem is here: Sphere s(Point(0.0,0.0,-50.0), 40.0); shapes.push_back(&s); at this point, you've created the Sphere s locally on the stack, and you've pushed its address into your vector. When you leave scope, local objects are freed, and so the address you've stored in your vector now points to memory you no lo...
1,858,970
1,858,984
How to catch this error? [C++]
I'm trying to catch dividing by zero attempt: int _tmain(int argc, _TCHAR* argv[]) { int a = 5; try { int b = a / 0; } catch(const exception& e) { cerr << e.what(); } catch(...) { cerr << "Unknown error."; } cin.get(); return 0; } and basically it doesn't work. Any advice why? Thank you. P.S. Any chance t...
Divide by zero does not raise any exceptions in Standard C++, instead it gives you undefined behaviour. Typically, if you want to raise an exception you need to do it yourself: int divide( int a, int b ) { if ( b == 0 ) { throw DivideByZero; // or whatever } return a / b; }
1,858,978
1,859,021
Segmentation fault when instantiating object from particular library
I have an C++ application (heavily shortened down, shown below); #include <iostream> #include "MyClass.h" void foobar() { MyClass a; } int main(int argc, char** argv) { std::cout << "Hello world!\n"; return 0; } Where "MyClass" is defined in a statically linked library (.a). However, this application Segfaults ...
There may be some static initialization inside the the MyClass library that goes wrong, if you don't have the source code it will be hard to find and fix.
1,859,117
1,859,189
Difference between double dispatch and visitor pattern in Java and C++
Is there any difference between double dispatch and visitor pattern? I'm working with Java and C++ and wondering if there is any split between the two.
The visitor pattern is a means of adding a new operation to existing classes. Double dispatch is a means of dispatching function calls with respect to two (or, when generalised, more) polymorphic types, rather than a single polymorphic type, which is what languages like C++ and Java support directly.
1,859,176
1,859,217
Component Object Model via C++(maybe VS)
I was searching through google about Microsoft Component Object Model. Found only few normal articles and only 1 step by step example, which doesn't work. Is there any links/references/books/tutorials you know how to build simple COM component via VS C++? Any answer or help would be appreciated!
COM is generally considered antiquated technology these days. That's not to say nobody is still using it - there are plenty of legacy systems that are still invested in it - but it's rare to find someone approaching it as a newbie nowadays. I'm not sure if things have moved on much but my recommendations would be Don B...
1,859,415
1,940,361
Export every frame as image from a Movie-File (QuickTime-API)
I want to open an existing Movie-File and export every frame of this file to an image like JPEG or TIFF. I got so far until now: int main(int argc, char* argv[]) { char filename[255]; // Filename to ping. OSErr e; // Error return. FSSpec filespec; // QT file specification short filemovie...
As a beginning, this article on Movie exporters should pretty much get you started: http://www.mactech.com/articles/mactech/Vol.16/16.05/May00QTToolkit/index.html Even though MacTech is a Mac resource, all described API functions should be available in the QuickTime for Windows SDK as well. I will slap some sample code...