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
2,115,977
2,116,020
Reorganize Classes into Static Libraries
I am about to attempt reorganizing the way my group builds a set of large applications that share about 90% of their source files. Right now, these applications are built without any libraries whatsoever involved except for externally linked ones that are not under our control. The applications use the same common so...
It's very hard to give general guidelines in this area - how you structure libraries depends very much on how you use them. Perhaps if I describe my own code libraries this may help: One general purpose library containing code that I expect all applications will have at least a 50/50 chance of needing to use. This inc...
2,116,126
2,116,186
How can I make the preprocessor insert linebreaks into the macro expansion result?
With C/C++ macros it's quite easy to generated long constructs automatically. For example, if I want a huge set of methods to not ever throw exceptions (a must for COM-exposed methods) I can do something like this: #define BEGIN_COM_METHOD\ try{ #define END_COM_METHOD\ return S_OK;\ } catch( exception& ) {...
You can't do it. The replacement text is until the end of the line where it is #defined, so it will not have newlines in it. If your problems with compilation are infrequent, you could run the preprocessed file through indent or something like that before compiling when that happens to help you get more readable code.
2,116,128
2,116,174
Easier way to do callbacks for vectors (or maybe something else in the STL)? C++
I'm making a simple crime sim game. Throughout it I keep doing the same thing over and over: // vector<Drug*> drugSack; for (unsigned int i = 0; i < this->drugSack.size(); i++) this->sell(drugSack[i]); Just one example. I hate having all these for loops all over the place omg QQ, anyway to do something li...
Time to start knowing the stl algorithms: #include <algorithm> ... std::for_each( drugSack.begin(), drugSack.end(), std::bind1st( std::mem_fun_ptr( &ThisClass::Sell ), this ) ); The idea is to create an object, called a "functor", that can do a certain action for each of the elements in the range drugSack.begin()...
2,116,132
2,116,171
How to port C++ code to C++/CLI in Visual Studio?
I have an application written in native C++ which I'd like to get running on the .NET virtual machine. I was thinking of recompiling the C++ code as C++/CLI, using the Visual Studio 2008 compiler. Regrettably, I don't find any documentation on how to do this, so hence my questions: Does this actually make sense? Am I ...
A lot of native C++ code will actually just compile and run on C++/CLI. This is really a kind of hybrid compiler that can call native Win32 functions and use standard C libraries like OpenGL. You can even call COM interfaces directly (all the stuff you can do with a native C++ compiler). The .Net library is also avail...
2,116,221
2,116,263
Loop efficiency - C++
Beginners question, on loop efficiency. I've started programming in C++ (my first language) and have been using 'Principles and Practice Using C++' by Bjarne Stroustrup. I've been making my way through the earlier chapters and have just been introduced to the concept of loops. The first exercise regarding loops asks o...
You should aim for clarity first and you try to micro-optimize instead. You could better rewrite that as a for loop: const int offsetToA = 65; const int numberOfCharacters = 26; for( int i = 0; i < numberOfCharacters; ++i ) { const int characterValue = i + offsetToA; cout << static_cast<char>( characterValue )...
2,116,235
2,116,252
TEMP Environment variable expansion for C++ (Windows)
I need to get a %TEMP% environmental variable value string in Windows platform. If I try to use any methods(C / C++) (getenv(), …) to get this environmental variable, it returns with “~” in that string. For Example: C:\DOCUME~1\pkp\LOCALS~1\Temp. But I need to get full string for some reasons, as below: C:\Documents ...
Call GetLongPathName() on the short name.
2,116,434
2,116,649
Sorting std::list using std::set
I'm adding two different elements to both std::list and std::set and I want the std::list to be sorted with the same order as of std::set. one way I tried is when the element is added to std::set, find that element then get the index of that element using std::distance(begin, found) and then insert the element to that ...
You should use the std::map, with the data you put in the set as key, and the data you put in the list as value. This way your list elements will be ordered.
2,116,490
2,116,563
boost::intrusive_ptr constructor ambiguity using a class' 'this' pointer
The offending code: template<typename T> class SharedObject { public: typedef boost::intrusive_ptr<T> Pointer; typedef boost::intrusive_ptr<T const> ConstPointer; inline Pointer GetPointer() { return Pointer(this); //Ambiguous call here } inline ConstPointer GetPointer() const { return ConstPointer(t...
When you say: typedef boost::intrusive_ptr<T> Pointer; you are declaring a type which is an intrusive pointer to an int (because T is an int at that point), when the template is instantiated in your code. Your SharedObject class is not an int, so you can't instantiate such an intrusive pointer using this. Edit: OK, I ...
2,116,782
2,116,793
C++ Inheritance, calling a derived function from the base class
How can I call a derived function from a base class? I mean, being able to replace one function from the base to the derived class. Ex. class a { public: void f1(); void f2(); }; void a::f1() { this->f2(); } /* here goes the a::f2() definition, etc */ class b : public a { public: void f2(); }; /* here g...
Declare f2() virtual in the base class. class a { public: void f1(); virtual void f2(); }; Then whenever a derived class overrides f2() the version from the most derived class will be called depending on the type of the actual object the pointer points to, not the type of the pointer.
2,116,828
2,116,871
How to log an c++ exception
Do you know how can I log the exception ? right now the message in the catch statement is printed, but i cannot understood why ins´t Manage.Gere() called sussefully . try{ Manager.Gere(&par,&Acc, coman, comando, RunComando, log, &parti, comandosS, RunComandosSuper,true); } catch (...) { log("ERROR ENTER GERE**...
First thing you need there is find which exceptions Manage.Gere can throw. Then catch them specifically like catch(FirstExceptionGereThrows &exc) and when you catch all possible exceptions, you'll know what is failing in Manage.Gere. catch(FirstException &exc){ log << "Failed because FirstException\n"; }catch(Second...
2,116,959
2,117,123
how to write a function Click() for dynamic created button?
Trying to write a simple VCL program for educating purposes (dynamicly created forms, controls etc). Have such a sample code: void __fastcall TForm1::Button1Click(TObject *Sender) { TForm* formQuiz = new TForm(this); formQuiz->BorderIcons = TBorderIcons() << biSystemMenu >> biMinimize >> biMaximize; formQui...
You could do two things, you could either create an action and associate it with the button, or you could make a function like so: void __fastcall TForm1::DynButtonClick(TObject *Sender) { // Find out which button was pressed: TButton *btn = dynamic_cast<TButton *>(Sender); if (btn) { // Do act...
2,117,042
2,117,246
Capturing real time images from a network camera
What is the best way to capture streamed MJPEG from a network IP camera? I'd like to get frames and process them, using c++ (or python extended with c++). Is OpenCV my best option?
Appart from OpenCV, you can use mplayer with -vo yuv4mpeg redirected to a pipe to get a stream of uncompressed yuv images. You can create the mplayer process and pipe from C++. Another way is to use a RTSP library (your IP camera probably uses it as protocol)
2,117,173
2,117,187
How to enable the mouse in C++ program under DOS using DJGPP?
I've been using DJGPP for the first time recently and can't seem to enable mouse support. What's the best way? Thanks for any help.
Gosh, this takes me back! You need the software interrupt 33H - see http://www.sentex.net/~ajy/mouseint.html, and a tutorial of sorts at http://www.writeka.com/emage/mouse_events.html.
2,117,312
18,447,136
How can i convert a string into a ZZ number?
I'm using the NTL library to implement ElGamal encryption/decryption algorithm. I've got it to the point that it's working but the algorithm wants the message to be converted to integers so it can be encrypted. So if i input a number like 1234 everything works ok but how would i go to be able to convert a C++ string (s...
Here is an easy way to do it: std::string str("1234567890"); NTL::ZZ number(NTL::INIT_VAL, str.c_str()); Now notice that: std::cout << str << std::endl; // prints 1234567890 std::cout << number << std::endl; // prints 1234567890
2,117,452
2,117,489
Visual Studio linking error LNK2005 and LNK2020
I'm using visual studio 2003 and I'm getting the following linking error in my project: Linking... LINK : warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/INCREMENTAL:NO' specification msvcrtd.lib(MSVCR71D.dll) : error LNK2005: _fprintf already defined in LIBCMTD.lib(fprintf.obj) C:\Documents and Settings\mz07\Des...
You are linking a .lib whose code was compiled with an incompatible compiler setting. The problem one is Project + Properties, C/C++, Code Generation, Runtime library. /MD is not compatible with /MT. You'll either have to rebuild the .libs to match your .exe project setting or the other way around.
2,117,488
2,119,127
Extract audio from video as wav
I know there is a question similar to mine: Extract wav file from video file I am new to C++ and understand about COM library + directX is needed for video and audio. I been looking for tutorial and samples code but little success. My question is how do I code the application to take video file (any type) and saved th...
I'll second the motion to just use a build of ffmpeg to perform the audio extraction. It can be done in one easy command as opposed to most likely hundreds of lines of code (If your going to check for all of the possible problems that could happen when dealing with different video formats and codecs). ffmpeg -i video....
2,117,536
2,119,919
Creating a library of template functions
I've been developing a library of mostly template functions and managed to keep things organized (to some extent) in the following manner: // MyLib.h class MyLib { template<class T> static void Func1() { } template<class T> static void Func2() { } }; And obviously calls would be made like this: MyLib:...
You should prefer the namespace over your class with static methods: namespace offer you the possibility to be shared among several files, one per logical group of methods namespace may be omitted: either because ADL kicks in or with using myNamespace::MyFunc; (note: it's bad practice to write using myNamespace;, and ...
2,117,597
2,295,570
Reading response data from TCppWebBrowser in Borland C++Builder
How to I access the data returned on a web page using the TCppWebBrowser component in Borland C++Builder 6.0? I have succeeded in posting data using the sample at: http://edn.embarcadero.com/article/27519
One of my colleagues has found an answer for me at: cboard.cprogramming.com/cplusplus-programming/… This works very well.
2,118,047
2,118,096
Returning reference to a pointer- C++
Consider the following class. class mapping_items { public: mapping_items(){} void add(const mapping_item* item) { items_.push_back( item ); } size_t count() const{ return items_.size(); } const mapping_item& find(const std::string& pattern){ const mapping_item* item ...
There is a problem - what happens if your find() function fails? If this is expected never to happen, you are OK returning a reference (and raise an exception if it happens despite the fact it shouldn't). If on the other hand it may happen (e.g. looking up a name in an address book), you should consider returning a po...
2,118,090
2,118,172
What are the "things to know" when diving into multi-threaded programming in C++
I'm currently working on a wireless networking application in C++ and it's coming to a point where I'm going to want to multi-thread pieces of software under one process, rather than have them all in separate processes. Theoretically, I understand multi-threading, but I've yet to dive in practically. What should eve...
I would focus on design the thing as much as partitioned as possible so you have the minimal amount of shared things across threads. If you make sure you don't have statics and other resources shared among threads (other than those that you would be sharing if you designed this with processes instead of threads) you wo...
2,118,238
2,118,278
storing a type's type for processing variable argument lists
Is it possible to do something along the lines of: type t = int;//this would be a function which identifies what type the next argument is if( t == int ) printf( "%d", va_arg( theva_list, t ) ); in a relatively trivial way? The only object I know which can hold a type is type_info and I can't work out how to use i...
Generally speaking, no. Types can only really be stored, manipulated, etc., at compile time. If you want something at run time, you have to convert (usually via rather hairy metaprogramming) the type to a value of some sort (e.g., an enumeration). Perhaps it would be better if you gave a somewhat higher level descripti...
2,118,245
2,118,394
Is there any emulator programming tutorial or guide?
Possible duplicate of How do Emulators Work and How are they Written? I want to program an emulator ( may be NES or C64, I haven't decided yet ), I know there are lots of them so many may ask why would someone want to make one from scratch, but I want to include some specific characteristics in it, and also for the sak...
Both the NES and C64 are based on the 8 bit 65xx processor. Writing an instruction set emulator for that chip is pretty trivial since the instruction set is small. The larger issue is to emulate the other support hardware, video controller, etc. It's been a long time since I programmed a C64, and I never programmed an ...
2,118,422
2,118,718
Scope of C libraries in C++ - <X.h> vs <cX>
The C++ Programming Language : Special Edition states on page 431 that... For every header < X.h > defining part of the C standard library in the global namespace and also in namespace std, there is a header < cX > defining the same names in the std namespace only. However, when I use C headers in the < cX > style, I d...
Stephan T. Lavavej, a member of the MSVC team, addresses the reality of this situation (and some of the refinements to the standard) in this comment on one of his blog postings (http://blogs.msdn.com/vcblog/archive/2008/08/28/the-mallocator.aspx#8904359): > also, <cstddef>, <cstdlib>, and std::size_t etc should be use...
2,118,493
2,118,818
Asynchronous write to socket and user values (boost::asio question)
I'm pretty new to boost. I needed a cross platform low level C++ network API, so I chose asio. Now, I've successfully connected and written to a socket, but since I'm using the asynchronous read/write, I need a way to keep track of the requests (to have some kind of IDs, if you will). I've looked at the documentation/...
The async_xxx functions are templated on the type of the completion handler. The handler does not have to be a plain "callback", and it can be anything that exposes the right operator() signature. You should thus be able to do something like this: // Warning: Not tested struct MyReadHandler { MyReadHandler(Whatever...
2,118,541
2,121,434
Check if parameter pack contains a type
I was wondering if C++0x provides any built-in capabilities to check if a parameter pack of a variadic template contains a specific type. Today, boost:::mpl::contains can be used to accomplish this if you are using boost::mpl::vector as a substitute for variadic templates proper. However, it has serious compilation-tim...
No, you have to use (partial) specialization with variadic templates to do compile-time computations like this: #include <type_traits> template < typename Tp, typename... List > struct contains : std::true_type {}; template < typename Tp, typename Head, typename... Rest > struct contains<Tp, Head, Rest...> : std::con...
2,118,695
2,118,998
Intel Performance Primitive (IPP) runtime error
I have source code that was not written by me, and I cannot contact the author. It is written in C++ and requires libjpeg, boost, and the Intel Performance Primitives. Compilation was a chore, but after days of problem solving, it compiles. Now, I get the following runtime error: error while loading shared libraries: l...
Looks like the app is compiled against an older version of IPP. Since 6.1.2 is called libippi.so.6.1, it may be as simple installing IPP 5.1.x (though linux library versioning isn't as simple as this.) If you create a login for the intel non-commercial IPP download area, you can dig around and see if they offer older b...
2,118,782
2,119,001
Selecting an explicit specialization of a class based on a derived type
Hi I'm having problems selecting the correct version of a templated class which has an explicit specialization. I'm wanting to select a specialization using a derived class of the class used to specialize. The scenario is: #include <stdio.h> class A {}; class B: public A {}; template<typename T> class Foo { public...
---EDIT : NEW ANSWER Let's make the original approach more maintainable. All the important choices can be found in the definition of Foo. It is supposed to be easy to maintain. #include <boost/mpl/if.hpp> #include <boost/type_traits/is_base_of.hpp> #include <iostream> class A {}; class B: public A {}; class C{}; cl...
2,118,920
2,118,995
How do I copy the binary code of an executable into a new file without using a system copy command?
This is the code I have, but the file is a little smaller and doesn't execute: int WriteFileContentsToNewFile(string inFilename, string outFilename) { ifstream infile(inFilename.c_str(), ios::binary); ofstream outfile(outFilename.c_str(), ios::binary); string line; // Initial read infile >> line; ...
One way is to use the stream inserter for a streambuf: int WriteFileContentsToNewFile(string inFilename, string outFilename) { ifstream infile(inFilename.c_str(), ios::binary); ofstream outfile(outFilename.c_str(), ios::binary); outfile << infile.rdbuf(); }
2,118,992
2,119,163
How do I use gcc builtin __sync_bool_compare_and_swap in g++ on MacOSX?
I have some code that uses: __sync_bool_compare_and_swap it compiles fine on Linux. But when I try to compile it on MacOSX in g++, I get: error: ‘__sync_bool_compare_and_swap’ was not declared in this scope How do I fix this? (This is Mac OSX 10.5.8, so it's intel .. .and should have this instruction). Thanks!
If you can't find it, you can use OSCompareAndSwap() on Mac. But it would be nice to have cross-platform code, wouldn't it.
2,119,015
2,119,821
ActiveMQ publisher and subscriber in multiple languages (C++ Java)
I want to use ActiveMQ as a message broker communicating between a C++ component and a Java component in two process. Eg. C++ component is the publisher and the Java component is the subscriber(there maybe multiple subscribers). I look at ActiveMQ website and it mentions the tool OpenWire and ActiveMQ-CPP. However, all...
OpenWire is a protocol and hence can theoretically be implemented anywhere, but that doesn't mean full implementations exist for every language. The fine print of the C++ client says: "As of version 2.0, ActiveMQ-CPP supports the OpenWire v2 protocol, with a few exceptions. ObjectMessage - We cannot reconstruct the ob...
2,119,080
2,119,203
Extract multiple words to one string variable
std::stringstream convertor("Tom Scott 25"); std::string name; int age; convertor >> name >> age; if(convertor.fail()) { // it fails of course } I'd like to extract two or more words to one string variable. So far I've read, it seems that it is not possible. If so, how else to do it? I'd like name to get all ...
Most of the solutions posted so far don't really meet the specification -- that all the data up to the age be treated as the name. For example, they would fail with a name like "Richard Van De Rothstyne". As the OP noted, with scanf you could do something like: scanf("%[^0-9] %d", name, &age);, and it would read this j...
2,119,149
2,119,185
moving code from unix to windows xp
i have code written in c++. its a console app that takes an input and displays output. Now i can just give my a.out to someone without giving them the code and it should work on another unix system. but what if they have windows environment. I would like to learn how to make dll for them so they can run that. also, if ...
You need to recompile your application for Windows, either on a Windows machine or by using a crosscompiler. This requires that all routines which you use need to be available under Windows, too. Either you wrote your application from scratch using portable libraries (read: no unix/posix system calls), or you will get...
2,119,161
2,119,262
What is an App Bundle on Mac?
I have a basic C++ applicatin build using g++ and -framework ... when I run it, I get a : Working in unbundled mode. You should build a .app wrapper for your Mac OS X applications. (which is not std::couted by any of my application). What causes this, and how can I get rid of it? Thanks!
You need to create a folder structure and place the binary in a special location. For an example with explanation see this Qt page Mac OS X handles most applications as "bundles". A bundle is a directory structure that groups related files together. Bundles are used for GUI applications, frameworks, and installer pack...
2,119,177
2,119,235
stl vector assign vs insert
I understand the semantics of the 2 operations , assign- erases before replacing with supplied values. insert - inserts values at specified location(allocates new memory if necessary). Apart from this is there any reason to preffer one over the other? Or to put it another way, is there any reason to use assign instea...
If you wish to invoke the semantics of assign, call assign - if you wish to invoke the semantics of insert, call insert. They aren't interchangeable. As for calling them on an empty vector, the only difference is that you don't need to supply an iterator to insert at when you call assign. There may be a performance dif...
2,119,223
2,119,507
C/C++ Control Structure Limitations?
I have heard of a limitation in VC++ (not sure which version) on the number of nested if statements (somewhere in the ballpark of 300). The code was of the form: if (a) ... else if (b) ... else if (c) ... ... I was surprised to find out there is a limit to this sort of thing, and that the limit is so small. I'm not ...
Visual C++ Compiler Limits The C++ standard recommends limits for various language constructs. The following is a list of constructs where the Visual C++ compiler does not implement the recommended limits. The first number is the recommended limit and the second number is the limit implemented by Visual ...
2,119,392
2,119,518
c++ builder, label.caption, std::string to unicode conversion
Just need to set the lbl.caption (inside a loop) but the problem is bigger than i thought. I've tried even with vector of wstrings but there is no such thing. I've read some pages, tried some functions like WideString(), UnicodeString(), i know i can't and shouldn't turn off Unicode in C++Builder 2010. std::vector <st...
The problem is that you are mixing standard template library string class with the VCL string class. The caption property expects the VCL string which has all the functionality of the STL one. The example that works is really passing (const char*) which is fine because there is a constructor for this in the VCL Unicode...
2,119,477
2,119,547
Statement reordering with locks
Here some C++ code that is accessed from multiple threads in parallel. It has a critical section: lock.Acquire(); current_id = shared_id; // small amounts of other code shared_id = (shared_id + 1) % max_id; lock.Release(); // do something with current_id The class of the lock variable is wrapper around the POSIX mutex...
It is possible to compile with O3! The compiler will never optimize across a function call unless the function is marked as pure using function-attributes. The mutex functions aren't pure, so it's absolutely safe to use them with O3.
2,119,504
2,136,814
Shell extension installation not recognized by Windows 7 64-bit shell
I have a Copy Hook Handler shell extension that I'm trying to install on Windows 7 64-bit. The shell extension DLL is compiled in two separate versions for 32-bit and 64-bit Windows. The DLL implements DLLRegisterServer which adds the necessary registry entries. After adding the registry entries, it calls the following...
As it turns out, the problem was not specific to 64-bit Windows. After consulting with Microsoft, I learned that this behavior affects Copy Hook Handlers in both 32 and 64 bit systems. The SHChangeNotify() with SHCNE_ASSOCCHANGED API apparently does not cause the shell to reload Copy Hook Handlers. According to a Micr...
2,119,708
2,120,132
Dynamic and Static Libraries in C++
In my quest to learn C++, I have come across dynamic and static libraries. I generally get the gist of them: compiled code to include into other programs. However, I would like to know a few things about them: Is writing them any different than a normal C++ program, minus the main() function? How does the compiled pro...
Is writing them any different than a normal C++ program, minus the main() function? No. How does the compiled program get to be a library? It's obviously not an executable, so how do I turn, say 'test.cpp' into 'test.dll'? Pass the -dynamiclib flag when you're compiling. (The name of the result is still by default ...
2,119,731
2,119,762
Limiting try block scope. Does it matter?
Possible Duplicate: Should java try blocks be scoped as tightly as possible? Is there any performance benefit (particularly in C++ or Java) in keeping the size of try block small [aside from it being more informative to the reader as to which statement can throw]. Given the following method where i do not want to th...
At least with the compilers and exception handling mechanisms I've seen, there should be no difference. The depth at which an exception throw is nested can make a difference, but only when the exception is thrown and the general agreement is that in this case performance is something you can generally ignore.
2,120,030
24,665,400
Can I use glibc under windows?
Is it (or would it) be possible to use glibc under windows (as a replacement of msvcrt)? I know this is a stupid question, and answers like cygwin will pop up, but I am really asking: is it possible to link to glibc on windows and use all library functions like with msvcrt?
A possible workaround could exist: if someone combines http://0xef.wordpress.com/2012/11/17/emulate-linux-system-calls-on-windows/ with http://www.musl-libc.org/ and compiles source code with gcc against musl libc instead of glibc. So, I can't understand why nobody writes a such glibc analog for Windows. :-(
2,120,059
2,120,184
Deserializing unknown inherited type [C++]
Lets say I have a class which routes messages to their handlers. This class is getting the messages from another class who gets the messages through socket. So, the socket gets a buffer containing some sort of message. The class that routes the messages is aware of the message types. Every message is inheriting Message...
You could abstract the message deserialization. Have a "MessageHolder" class that just has the buffer to the object initially. It would have a method: IMessageInterface NarrowToInterface(MessageId id); It wasn't clear to me if your router would already know what type of message it was or not. If it does, then it w...
2,120,078
2,120,101
Using Function Templates
I have created a structure of different data types and i want to return each type of data. does this can be done using a function template which takes a different data argument not included in structure or no arguments? I have something like this, struct mystruct{ int _int; char _c; string _str }; In function template...
Yes: template<class T> T f() { return 0; // for the sake of example } int main() { return f<int>(); // specify the template parameter } template<class T> vector<T> another_example(); // use another_example<int>() which returns a vector<int>
2,120,082
2,120,234
Flex -- C++ connection?
How do I connect a Flex Application( Internet Site ) and C++ togehter ? a minimalistic example from what i mean (User Story): Frank goes to www.myflexsite.de there are 2 textboxes and 1 Button( Label = add two numbers) . He inserts 2 in the first textbox and 5 in the ohter. Now he clicks on the add button. The Backend ...
The easiest would be to write a small console application in C++ and then invoke it via Apache or any other web server using CGI. There are performance problems with this but it's a good start, and then you can move forward. From Flex just make HTTP requests and let your program parse them - for instance, you can send ...
2,120,094
2,241,882
how to build dll files in netbeans using ms vc++ compiler?
i tried using cygwin gcc compiler along with netbeans to create dll files it seems there is an issue in the generated dll file. if i use the ms vc++ compiler and do all compiling on command line its runs file, but i dont know how to integrate ms vc++ tools in netbeans ... can anyone help me on that ? thanks jay
NetBeans doesn't provide a way to integrate microsoft compiler in its IDE. This is probably because it doens't have rights to do so. With NetBeans you can integrate only GNU compilers for C/C++. To use Microsoft C/C++ compiler, you have to use MS Visual Studio IDE, or MS Visual Studio provided command line tools.
2,120,146
2,120,576
Why doesn't this << overload compile
I can't figure out why the following code doesn't compile. The syntax is the same as my other operator overloads. Is there a restriction that the << overload must be friended? If so, why? Thanks for any help. This doesn't work - #include "stdafx.h" #include <iostream> #include <fstream> #include <string> class Test {...
Here's the fundamental reason why the stream operators have to be friends. Take this code: struct Gizmo { ostream& operator<<(ostream& os) const { os << 42; } }; int main() { Gizmo g; cout << g; return 0; } Consider the context of the...
2,120,298
2,120,311
Not using iterators into a resized vectors
I read in The C++ Programming Language : Special Edition Don't use iterators into a resized vector Consider this example. vector< int >::iterator it = foo.begin(); while ( it != foo.end() ) { if ( // something ) { foo.push_back( // some num ); } ++it; } Is there a problem with this? After the vector was res...
Yes, there is a problem with it. Any call to push_back has the potential to invalidate all iterators into a vector. foo.end() will always retrieve the valid end iterator (which may be different to the value last returned by foo.end()), but it may have been invalidated. This means that incrementing it or comparing it ma...
2,120,303
2,120,389
what's interface vs. methods, abstraction vs. encapsulation in C++
I am confused about such concepts when I discussed with my friend. My friend's opinions are 1) abstraction is about pure virtual function. 2) interface is not member functions, but interface is pure virtual functions. I found that in C++ primer, interface are those operations the data type support, so member functio...
I think your main problem is that you and your friend are using two different definitions of the word "interface", so you're both right in different ways. You are using "interface" in the everyday sense of "a defined way to inter-operate with something", as in "the interface between my computer and my keyboard is USB" ...
2,120,725
2,120,816
Help understanding boost::bind placeholder arguments
I was reading a StackOverFlow post regarding sorting a vector of pairs by the second element of the pair. The most obvious answer was to create a predicate, but one answer that used boost caught my eye. std::sort(a.begin(), a.end(), boost::bind(&std::pair<int, int>::second, _1) < boost::bind(&std::pair<int, int>::...
This expression: boost::bind(&std::pair<int, int>::second, _1) < boost::bind(&std::pair<int, int>::second, _2) namely, the use of the < operator actually defines a functor between two other functors, both of which defined by bind. The functor expected by sort needs to have an operator() which looks like this: bool ope...
2,121,003
2,121,115
What all Design Patterns can I use?
1. I need to build a "Web Service Server (Simulator)" which generates the xml files and also sends async calls to the client for notification. At this point, I am writing a code to generate dummy XML files which will be used for testing (FileGeneratorClass-- builder)? 2. Also, can I implement this in a way that I do n...
Patterns don't do anything. You are asking if you should use prepositional phrases when you are planning to write a mystery novel. You don't start a design saying what patterns do I need. Patterns emerge from the design process. You say my program will need x and y, that's similar to the such-and-such pattern, I should...
2,121,027
2,121,136
Looking for a metafunction from bool to bool_type
Basically, I am looking for a library solution that does this: #include <boost/type_traits.hpp> template<bool> struct bool_to_bool_type; template<> struct bool_to_bool_type<false> { typedef boost::false_type type; }; template<> struct bool_to_bool_type<true> { typedef boost::true_type type; }; Is there such...
Oh wait, true_type is just a typedef for std::integral_constant<bool, true>? Then there's an obvious solution: boost::integral_constant<bool, input_value>
2,121,172
2,121,359
Possible reasons for tellg() failing?
ifstream::tellg() is returning -13 for a certain file. Basically, I wrote a utility that analyzes some source code; I open all files alphabetically, I start with "Apple.cpp" and it works perfectly.. But when it gets to "Conversion.cpp", always on the same file, after reading one line successfully tellg() returns -13. T...
It's difficult to guess without knowing exactly what's in Conversion.cpp. However, using < with stream positions is not defined by the standard. You might want to consider an explicit cast to the correct integer type before formatting it; I don't know what formatting FATAL and format() expect to perform or how the % op...
2,121,258
2,121,274
i violated D.R.Y. help me please?
I'm making a blackjack sim and I want to deal the cards how it would be in a casino, i.e. all players get dealt a card, dealer gets one face down, players get another card, dealer gets one face up BUT LOOK I VIOLATED DRY :( How to redo?? void BlackJack::newHand() { resetHands(); for (unsigned int i = 0; i < p...
Move the repeated code into another function: void BlackJack::addDealerCard(bool visible) { Card* c = deck->nextCard(); c->setVisible(visible); dealer->addCard(c); } void BlackJack::addCards() { for (unsigned int i = 0; i < players.size(); i++) players[i]->addCard(deck->nextCard()); } void B...
2,121,525
2,121,616
const pointers in overload resolution
GCC treats these two function declarations as equivalent: void F(int* a) { } void F(int* const a) { } test.cpp: In function 'void F(int*)': test.cpp:235: error: redefinition of 'void F(int*)' test.cpp:234: error: 'void F(int*)' previously defined here This makes some sense because a caller will always ignore the con...
Standard says in 8.3.5/3 that for the purposes of determining the function type any cv-qualifiers that directly qualify the parameter type are deleted. I.e. it literally says that a function declared as void foo(int *const a); has function type void (int *). A pedantic person might argue that this is not conclusive e...
2,121,607
2,121,641
Any RAII template in boost or C++0x
Is there any template available in boost for RAII. There are classes like scoped_ptr, shared_ptr which basically work on pointer. Can those classes be used for any other resources other than pointers. Is there any template which works with a general resources. Take for example some resource which is acquired in the beg...
shared_ptr provides the possibility to specify a custom deleter. When the pointer needs to be destroyed, the deleter will be invoked and can do whatever cleanup actions are necessary. This way more complicated resources than simple pointers can be managed with this smart pointer class.
2,121,617
2,121,638
Can Someone Explain Threads to Me?
I have been considering adding threaded procedures to my application to speed up execution, but the problem is that I honestly have no idea how to use threads, or what is considered "thread safe". For example, how does a game engine utilize threads in its rendering processes, or in what contexts would threads only be c...
This is a very broad topic. But here are the things I would want to know if I knew nothing about threads: They are units of execution within a single process that happen "in parallel" - what this means is that the current unit of execution in the processor switches rapidly. This can be achieved via different means. ...
2,121,633
2,121,645
Why does the interface for auto_ptr specify two copy-constructor-like constructors
I was going through the auto_ptr documentation on this link auto_ptr There is something which i could not fully understand why is it done. In the interface section there are two declarations for its copy constructor 1) auto_ptr(auto_ptr<X>&) throw (); 2) template <class Y> auto_ptr(auto_ptr<Y>&) throw(); ...
It's there in case you can implicitly convert the pointers: struct base {}; struct derived : base {}; std::auto_ptr<derived> d(new derived); std::auto_ptr<base> b(d); // converts Also, you didn't ask but you'll notice the copy-constructor is non-const. This is because the auto_ptr will take ownership of the pointer....
2,121,651
2,121,658
Visual Studio 2008 C++ dependencies
i'm developing a C++ simulation (OpenGL) on top of VS2008 enviroment. My current operating system is Windows Vista. The trouble is that when trying to execute the application on a Windows XP machine, my application crashes because incompatibilities beteween DLL's (namely, msvcrt.dll function entry points ) ... Has any...
I seriously doubt that's the real reason it crashes. You probably just didn't deploy the CRT libraries to the target machine. Or deployed the debug build. If this is a single EXE with no DLL dependencies then solve your problem by linking the static version of the CRT. Right-click the project in Solution Explorer, ...
2,121,844
2,121,877
what is auto_ptr_ref, what it achieves and how it achieves it
auto_ptr_ref documentation here says this This is an instrumental class to allow certain conversions that allow auto_ptr objects to be passed to and returned from functions. Can somebody explain how auto_ptr_ref helps in achieving this. I just want to understand the auto_ptr class and its internals
It is rather confusing. Basically, auto_ptr_ref exists because the auto_ptr copy constructor isn't really a copy constructor in the standard sense of the word. Copy constructors typically have a signature that looks like this: X(const X &b); The auto_ptr copy constructor has a signature that looks like this: X(X &b) ...
2,121,889
2,121,898
Why does using boost increase file size so much?
I've noticed that when I use a boost feature the app size tends to increase by about .1 - .3 MB. This may not seem like much, but compared to using other external libraries it is (for me at least). Why is this?
Boost uses templates everywhere. These templates can be instantiated multiple times with the same parameters. A sufficiently smart linker will throw out all but one copy. However, not all linkers are sufficiently smart. Also, templates are instantiated implicitly sometimes and it's hard to even know how many times ...
2,122,018
2,122,019
Does this program show the four card suits (♠♣♥♦) on all standard-ish systems?
The following shows ♠♣♥♦ on windows xp, will it for all systems?? #include <stdio.h> int main(int argc, char *argv[]) { for (int i = 3; i <= 6; ++i) printf("%c", (char)i); getchar(); return 0; }
Nope. Character encoding is a very platform dependent, in my experience. Consider, in ASCII those characters don't even exist. And I have no clue where they are in Unicode. And where ever they are, you would then be depending on how your platform outputs Unicode.
2,122,025
2,122,031
What is the relationship of .lib and .obj to each other and my project in c++?
How do .lib and .obj files relate to each other? What is their purpose? Is a .lib just a collection of .obj files? If so are the .obj's then stored inside the .lib making the .obj's unnecessary?
Typically, the .obj files refer to object files. This is a source file in its compiled form. For example, a main.cpp and foo.cpp would produce main.obj and foo.obj. It is then the linkers job to link them together, so that main.obj can reach functions defined in foo.obj and vice-versa. The linker will output your binar...
2,122,194
2,122,925
How I print UTF-8 characters C++?
How I print these UTF-8 characters in C++?
Well, you know it is possible because your browser could render them. On Windows you can use the charmap.exe applet to discover their Unicode code points: ♠ = 0x2660 ♣ = 0x2663 ♥ = 0x2665 ♦ = 0x2666 The challenge is to get a C/C++ program to display them. That's not going to be possible in any kind of non-platform ...
2,122,278
19,895,227
How to show a MFC dialog without stealing focus on the other window
I have the dialog shown with ShowWindow(hWnd, SW_SHOWNOACTIVATE); But it doesn't work, the new dialog still steals the focus, why is it? here is the some code snippets from my program, QueryWindow is the MFC dialog class linked with the dialog: QueryWindow window; //window.DoModal(); window.Create(QueryWindow::IDD); wi...
There are few ways to skip dialog from getting focused: Make you OnInitDialog() to return zero value. Example: BOOL QueryWindow::OnInitDialog() { CDialog::OnInitDialog(); return FALSE; // return 0 to tell MFC not to activate dialog window } This is the best and most correct solution. Add WS_EX_NOACTIVATE sty...
2,122,282
2,122,404
Are function-local typedefs visible inside C++0x lambdas?
I've run into a strange problem. The following simplified code reproduces the problem in MSVC 2010: template <typename T> struct dummy { static T foo(void) { return T(); } }; int main(void) { typedef dummy<bool> dummy_type; auto x = []{ bool b = dummy_type::foo(); }; // auto x = []{ bool b = dummy<bool...
From n3000, 5.1.2/6, The lambda-expression’s compound-statement yields the function-body (8.4) of the function call operator, but for purposes of name lookup (3.4), … the compound-statement is considered in the context of the lambda-expression. Not surprisingly, the local type should be visible.
2,122,319
2,122,347
C++ type traits to check if class has operator/member
Possible Duplicate: Is it possible to write a C++ template to check for a function's existence? Is it possible to use boost type traits or some other mechanism to check if a particular template parameter has an operator/function, e.g. std::vector as a template parameter has operator[], while std::pair does not.
You can't solve this via type traits because you'd have to define if for every possible name. Here are the common solutions listed, which have one problem though: many STL implementations put common code in base classes and this method doesn't check for inherited names. If you need to check for inherited members too, s...
2,122,397
2,122,434
error LNK2019: unresolved external symbol
Ok, so I'm having a problem trying figure out the problem in my code. I have a lot of code so I'm only going to post the relevant parts that are messing up when I compile. I have the following function inside of a class and it will compile and everything will run fine until I call the function "CalculateProbabilityResu...
The compiler thinks that getTimeFrameFile is a SQLServer method: unresolved external symbol "public: int __thiscall SQLServer::getTimeFrameFile(int,int)" but you have it defined as a free function: int getTimeFrameFile(int timeInHours, int timeFrameSize) { Change that from a free function to a class method will sol...
2,122,425
2,122,428
How do I install g++ on MacOS X?
I want to compile C++ code on MacOS X, using the g++ compiler. How do I install it?
That's the compiler that comes with Apple's XCode tools package. They've hacked on it a little, but basically it's just g++. You can download XCode for free (well, mostly, you do have to sign up to become an ADC member, but that's free too) here: http://developer.apple.com/technology/xcode.html Edit 2013-01-25: This a...
2,122,506
2,122,531
How to create a hidden window in C++
How to create a hidden window ? The purpose of this window is to receive some messages.
When you create the window, omit the WS_VISIBLE flag and don't call ShowWindow.
2,122,567
2,122,575
Access a value from a struct via a pointer? (C++)
Here is my struct: struct Checker { short row; short col; unsigned short number; short color; }; Now, I have to also make another struct to represent a checkers board: struct Board { Checker checkers[2][13]; // Zeroth entry of 13 is not used. Checker *grid[8][8]; // each entry holds Null or an address ...
cout << grid[0][0]->number; If the grid is a 2-dimensional array of pointers to Checker structs, then grid[0][0] is a pointer to the Checker at that location (0, 0). The -> syntax dereferences the pointer and then accesses the number field. If I am misunderstanding your question or my response fails, please let me kno...
2,122,573
2,122,763
SIMD or not SIMD - cross platform
I need some idea how to write a C++ cross platform implementation of a few parallelizable problems in a way so I can take advantage of SIMD (SSE, SPU, etc) if available. As well as I want to be able at run time to switch between SIMD and not SIMD. How would you suggest me to approach this problem? (Of course I don't wa...
If someone is interested this is the dirty code I come with to test a new idea that I came with while reading about the library that Paul posted. Thanks Paul! // This is just a conceptual test // I haven't profile the code and I haven't verified if the result is correct #include <xmmintrin.h> // This class is doing a...
2,122,739
2,122,756
Lifetime of a thrown object caught by reference
The C++ Standard, paragraph 15.1.4 sais: The memory for the temporary copy of the exception being thrown is allocated in an unspecified way, except as noted in 3.7.3.1. The temporary persists as long as there is a handler being executed for that exception. I'm wondering why this code crashes (I know that it's not bes...
Specifically, the destructor of the thrown magicException object gets called before the catch block. Yes, as your quote from the standard says, a copy is taken by the compiler, and the original (probably) discarded. Your problem is the lack of a copy constructor in your original code. However, a C++ compiler is ...
2,122,863
2,122,876
Generating a unique id of std::string
I want to generate any limited std::string size unique id (i.e of size 6) in 32 bit application. what would be the best and quick way to do this?
Look up hashing of strings, e.g. the Jenkins hash function. But you will never get unique hashes, because strings can be much longer than your size 6, and the Pigoenhole lemma shows trivially that hashes must collide as a a consequence.
2,122,986
2,123,011
Why does endl get used as a synonym for "\n" even though it incurs significant performance penalties?
This program: #include <iostream> #include <cstdlib> #include <string> int main(int argc, const char *argv[]) { using ::std::cerr; using ::std::cout; using ::std::endl; if (argc < 2 || argc > 3) { cerr << "Usage: " << argv[0] << " [<count>] <message>\n"; return 1; } unsigned long count =...
I'm not certain. Inserting std::endl into the output stream is defined as being equivalent to inserting .widen('\n') and then calling flush() and yet many programmers persist in using std::endl even when there is no cause to flush, for example they go on to immediately output something else. My assumption is that it co...
2,123,146
2,129,209
Application does not start in debugger
The application I'm working does not start in the debugger of Visual Studio 2005. Here's what I do: I rebuild the application and hit F5 to start it The title of the VS2005-window says "projectname (Running) ..." The debugger buttons appear but are greyed out The application appears in the Windows task manager, but it...
Ok, I've solved my problem, but I have no idea how. One thing i tried was deleting all build files and exe and dll files, and then recompile everything. But that didn't help. I then tried one thing at random: the plugins were in the same solution. So I removed them and tried to run again. And this time it worked! So I ...
2,123,163
2,123,180
What does this stack trace possibly mean?
I'm having segfault problem in my application written using C++ and compiled using GCC 4.3.2. It is running under Debian 5 x64. The process crashed on the following line of code: #0 0x00000000007c720f in Action::LoadInfoFromDB (this=0x7fae10d38d90) at ../../../src/server/Action.cpp:1233 1233 m_tmap[tId]...
m_tmap[tId]->slist[sId] = pItem; If that's the crash position, you're most likely indexing into non-existent data. If m_tmap is a std::map it's ok - but did you verify slist[sId] is a valid subscript? Or - you called a member function on a NULL (or otherwise invalid)-Pointer and crash the first time you're accessing a...
2,123,265
2,123,964
In wxwidgets, how do I make one thread wait for another to complete before proceeding?
I have a system where my singleton class spawns a thread to do a calculation. If the user requests another calculation while another calculation is still running, I want it to tear down the existing thread and start a new one. But, it should wait for the first thread to exit completely before proceeding. I have all the...
To wait for a thread you need to create it joinable and simply use wxThread::Wait(). However I agree with the remark above: this is not something you'd normally do at all and definitely not from the main GUI thread as you should never block in it because this freezes the UI. Consider using a message queue to simply tel...
2,123,480
2,123,506
Are object files platform independent?
Is it possible to compile program on one platform and link with other ? What does object file contain ? Can we delink an executable to produce object file ?
No. In general object file formats might be the same, e.g. ELF, but the contents of the object files will vary from system to system. An object file contains stuff like: Object code that implements the desired functionality A symbol table that can be used to resolve references Relocation information to allow the linker...
2,123,699
2,123,751
Where does my C++ compiler look to resolve my #includes?
this is a really basic question. I've been learning C++ and thus far I have only used the standard library. I have been including things like <iostream> and with no problems. Now I want to use Apache Xerces, so I've installed it on my machine (a Debian system) and am following a tutorial which says I need to includ...
Use the --verbose option: [...] #include "..." search starts here: #include <...> search starts here: /usr/lib/gcc/i686-pc-linux-gnu/4.4.2/../../../../include/c++/4.4.2 /usr/lib/gcc/i686-pc-linux-gnu/4.4.2/../../../../include/c++/4.4.2/i686-pc-linux-gnu /usr/lib/gcc/i686-pc-linux-gnu/4.4.2/../../../../include/c++/4....
2,123,823
2,123,851
Dump class/struct member variables in g++
Is there a flag in g++ or tools to dump the member variables of a struct/class? To illustrate, consider source code like this struct A { virtual void m() {}; }; struct B : public A { int b; virtual void n() = 0; }; struct C : public B { int c1, c2; void o(); }; struct D : public C { virtual void n() {}; A d; }; I want...
Use the right tool for the right job. g++ isn't much of a hierarchy viewing tool. You can always use a external tool like doxygen, that can dump graphviz diagrams. For power-solutions there is gcc-xml, that can dump your whole program into an xml file that you can parse at will.
2,123,877
2,123,889
The problem with header files
I have 3 header files in the project: Form1.h - this is header with implementation there, TaskModel.h with TaskModel.cpp, TaskController.h with TaskController.cpp. There are content of files: //----- TaskController.h #pragma once #include "TaskModel.h" .......... //---- Form1.h #pragma once #include "TaskModel.h"...
You can forward declare classes not header files. The problem with cyclic dependencies is usually a mark of bad design. Do you want TaskModel.h to include Form1.h? Why is that? Can it be avoided? Couldn't you just include Form1.h into TaskModel.cpp? For forward declaration do: // in TaskModel.h class Form1; // or oth...
2,123,907
2,123,941
concurrent reference counter class and scoped retain: is this ok?
This is a question regarding coding design, so please forgive the long code listings: I could not resume these ideas and the potential pitfalls without showing the actual code. I am writing a ConcurrentReferenceCounted class and would appreciate some feedback on my implementation. Sub-classes from this class will recei...
Your ConcurrentReferenceCounted seems to use a full mutex, which is not necessary and not very fast. Reference counting can be implemented atomically using architecture-dependent interlocked instructions. Under Windows, the InterlockedXXXfamily of functions simply wraps these instructions.
2,124,097
2,125,299
C++ container/array/tuple consistent access interface
Is there, perhaps in boost, consistent element access semantics which works across containers? something along the lines of: element_of(std_pair).get<1>(); element_of(boost_tuple).get<0>(); element_of(pod_array).get<2>(); in principle i can write myself, but I would rather not reinvent the wheel.thanks
I'm not aware of such a thing. You could most probably just implement a free get function for the types you're interested in. Boost.Tuple already has it. std::pair has it in C++0x. And the rest shouldn't be too complicated. E.g #include <iostream> #include <utility> #include <vector> #include <boost/tuple/tuple.hpp> n...
2,124,161
2,124,174
Manipulating scrollbars in third-party application
I need to create an application which do the following: At the beginning we have notepad window open with a lot of text in it. Our application must scroll through this file and take notepad window screenshot after each scroll action. I've tried to achieve this using SBM_GETRANGE, SBM_GETRANGE, SBM_SETPOS but it does no...
Don't try to manipulate the scrollbar directly - instead SetFocus() to the text window, then send Page Down messages. If there are applications where you must manipulate the scrollbar, you should get its window handle and send the messages there.
2,124,339
2,124,385
C++ preprocessor __VA_ARGS__ number of arguments
Simple question for which I could not find answer on the net. In variadic argument macros, how to find the number of arguments? I am okay with boost preprocessor, if it has the solution. If it makes a difference, I am trying to convert variable number of macro arguments to boost preprocessor sequence, list, or array f...
This is actually compiler dependent, and not supported by any standard. Here however you have a macro implementation that does the count: #define PP_NARG(...) \ PP_NARG_(__VA_ARGS__,PP_RSEQ_N()) #define PP_NARG_(...) \ PP_ARG_N(__VA_ARGS__) #define PP_ARG_N( \ _1, _2, _3, _4, _5, _6, _7, _8,...
2,124,483
2,124,505
Controlling cursor and keyboard with C++/Visual C++
This time I have a question about C++. I'm using Dev-C++ for programming, but I also have Visual C++ Express installed so both are good. I'm creating a program like automated tasks, is it.. macro? But as I'm a noob in C++, because I started it a week ago, I need help. Please keep the answers simple :-D This is a part o...
If you're writing to the console, you'd rather use something like conio.h or curses.
2,124,514
2,124,521
How to ensure a member is 4-byte aligned?
In order to use OSAtomicDecrement (mac-specific atomic operation), I need to provide a 4-byte aligned SInt32. Does this kind of cooking work ? Is there another way to deal with alignment issues ? struct SomeClass { SomeClass() { member_ = &storage_ + ((4 - (&storage_ % 4)) % 4); *member_ = 0; } SInt32 *...
If you're on a Mac, that means GCC. GCC can auto align variables for you: __attribute__((__aligned__(4))) int32_t member_; Please note that this is not portable across compilers, as this is GCC specific.
2,124,633
2,124,677
Atomic increment on mac OS X
I have googled for atomic increment and decrement operators on Mac OS X and found "OSAtomic.h", but it seems you can only use this in kernel space. Jeremy Friesner pointed me at a cross-platform atomic counter in which they use assembly or mutex on OS X (as far as I understood the interleaving of ifdefs). Isn't there s...
What makes you think OSAtomic is kernel space only? The following compiles and works fine. #include <libkern/OSAtomic.h> #include <stdio.h> int main(int argc, char** argv) { int32_t foo = 1; OSAtomicDecrement32(&foo); printf("%d\n", foo); return 0; }
2,124,749
2,125,150
Compiling libmagic statically (c/c++ file type detection)
Thanks to the guys that helped me with my previous question (linked just for reference). I can place the files fileTypeTest.cpp, libmagic.a, and magic in a directory, and I can compile with g++ -lmagic fileTypeTest.cpp fileTypeTest. Later, I'll be testing to see if it runs in Windows compiled with MinGW. I'm planning o...
This is tricky, I suppose you could do it this way... by the way, I have downloaded the libmagic source and looking at it... There's a function in there called magic_read_entries within the minifile.c (this is the pure vanilla source that I downloaded from sourceforge where it is reading from the external file. You cou...
2,124,836
2,124,846
redefine a non-virtual function in C++
When I read Effective C++, it says, never redefine a non-virtual function in C++. However, when I tested it, the code below compiles correctly. So what's the point? It's a mistake or just a bad practice? class A { public: void f() { cout<<"a.f()"<<endl;}; }; class B: public A { public: void f() {...
Redefining a non-virtual function is fine so long as you aren't depending on virtual dispatch behavior. The author of the book is afraid that you will pass your B* to a function that takes an A* and then be upset when the the result is a call to the base method, not the derived method.
2,124,921
2,124,954
static binding of default parameter
In Effective C++, the book just mentioned one sentence why default parameters are static bound: If default parameter values were dynamically bound, compilers would have to come up with a way to determine the appropriate default values for parameters of virtual functions at runtime, which would be slower and more compli...
Whenever a class has virtual functions, the compiler generates a so-called v-table to calculate the proper addresses that are needed at runtime to support dynamic binding and polymorphic behavior. Lots of class optimizers work toward removing virtual functions for this reason exactly. Less overhead, and smaller code. I...
2,124,963
2,124,983
Global variables in C++
I am supposed to write a program that should read from input numbers in the main() part, and then make some calculations in other bool functions. I don't want to insert the whole arrays of the numbers and all the other parameters in the functions everytime i call them. My question is this: Can i make somehow in c++ to...
Making variables global for this reason is bad habit. Either just pass the arrays to the functions, or make the whole thing into an object and make the arrays and functions members of the class. This is what OOP is about.
2,124,986
2,125,040
cant exchange widget in QSplitter (Qt)
I have a QSplitter with two widgets. One of them is static, the other one is supposed to change on the press of a button. But the problem is the widget does not change? I have a pointer for the widget that is changing - this->content The widget to switch to is in the pointer named widget. Here's a code snippet where I ...
Problem solved. Got help from some people in #qt on freenode. Thanks. I forgot to call setVisible(true) on this->content after switching to the new widget.
2,125,003
2,125,651
Design choice for sound effects
I'm trying to decide how I want to implement sound effects in my program. I've debating between 2 options. 1) Create an abstract interface SoundEffect and have every sound effect derive from that. Each sound effect is its own class. Upon construction, it opens the sound file and plays, and upon destruction it closes th...
If i understand that right you are hard-coding the sound effects for all possible sounds? That sounds wrong, you create different subclasses for differing behaviour, not for differing data. If you have certain sound effect types that need preprocessing of the data, subclasses make sense - if the project is bigger, you ...
2,125,021
2,125,317
Can I make this C++ code faster without making it much more complex?
here's a problem I've solved from a programming problem website(codechef.com in case anyone doesn't want to see this solution before trying themselves). This solved the problem in about 5.43 seconds with the test data, others have solved this same problem with the same test data in 0.14 seconds but with much more comp...
I tested the following on 28311552 lines of input. It's 10 times faster than your code. What it does is read a large block at once, then finishes up to the next newline. The goal here is to reduce I/O costs, since scanf() is reading a character at a time. Even with stdio, the buffer is likely too small. Once the block ...
2,125,189
2,125,265
Generic Alpha Beta Search with C++
I'm trying to design a function template which searches for the best move for any game - of course the user of this function template has to implement some game specific functions. What i'm trying to do is to generalize the alpha beta search algorithm with a function template. The declaration of this function template ...
You could define an abstract interface say game_traits and have specialized game_traits implementation for each game: template<typename Game> class game_traits { ... }; class Chess { ... }; template<> class game_traits<Chess> { static bool endGame(Chess game); ... }; template <typename Game, typename traits ...
2,125,209
2,125,336
Linker errors even though I prevent them with #ifndef
I am getting linker errors that suggest I am not using #ifndef and #define. 1>TGALoader.obj : error LNK2005: "struct TGA tga" (?tga@@3UTGA@@A) already defined in main.obj 1>TGALoader.obj : error LNK2005: "struct TGAHeader tgaheader" (?tgaheader@@3UTGAHeader@@A) already defined in main.obj 1>TGALoader.obj :...
You're not doing anything wrong. The problem is with the Tga.h file you got from NeHe. This header file defines four objects which means that if you include the file in different translation units the symbols for these will appear multiple times and that is what the linker is complaining about. The solution is to move ...
2,125,330
2,125,420
get heap corruption when changing member variables order
i have a quite strange problem. my class has -among others- following memers: GLboolean has_alpha; GLuint width; GLuint height; GLuint length; GLuint millisPerFrame; GLfloat uv[2]; GLuint texsize[2]; GLint compsize; // location2 long preload_interval_next; long preload_interval; if i put the has_alpha at (locati...
The problem here is almost certainly not in the members you have listed, but another one, possibly an int, pointer or bool that is not properly initialised in the constructor. Please post a larger example that fails, and make sure you initialise all members using the constructor initialisation list.
2,125,476
2,125,507
Invalid ESP when using multiple inheritance in C++ (VS2005)
I've been making a game which uses the Box2D physics engine, and I've come across some weirdness with the stack pointer (ESP) and multiple inheritance. I've managed to reproduce it in a minimal amount of code, and it seems that the order in which I declare the classes to be used in multiple inheritance seems to dictate...
The problem is that you cast the pointer to void* first. The compiler doesn't know then how to perform static cast for the pointer. It needs to change the pointer value during the cast if you use multiple inheritance to use second superclass virtual table. Just cast the pointer back to CScoreZone* before using static_c...
2,125,485
2,125,496
c++: Dynamically choose which subclass to create
I am new to c++ and i have a question. Lets say we have a base class Base and two derived classes, Derived1 and Derived2. f.e. Derived1 has a constructor taking a integer and Derived2 a constructor taking a boolean. Is it possible to determine at run time (or at compile time) which of those two subclasses to create and...
You probably want Factory Design Pattern.