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,339,077
2,339,088
Is it possible I have forward declaration of a class, without making them reference or pointer in header file
// I prefer to perform forward declaration on myclass, as I do not // wish to ship "myclass.h" to client // However, the following code doesn't allow me to do so, as class defination // is needed in header file. // // a.h #include "myclass.h" class a { public: a(); myclass me; }; I try to do it another way ar...
No. The reason being, that the compiler needs to know the size of your object (i.e. myclass) in order to know the size of the object (i.e. class "a" in your example). If you have only forward declared myclass, the compiler has no way of knowing the size that must be allocated for the "a" class. A reference or pointe...
2,339,167
2,339,198
How to forward declare the following template class
I try to forward declare concurrent_bounded_queue ; class MyClass { namespace tbb { template<typename T> class cache_aligned_allocator; template<class T, class A = cache_aligned_allocator> class concurrent_bounded_queue; }; // I wish to maintain this syntax. tbb::concurrent_bounded_queu...
Allocator is a template, but second argument of the queue is concrete class. Try this: class MyClass { namespace tbb { template<typename T> class cache_aligned_allocator; template<class T, class A = cache_aligned_allocator<T> > class concurrent_bounded_queue; }; tbb::concurrent...
2,339,226
2,339,244
Typedef compilation error on function overload
Why can't I compile the program 1 when the the program 2 is working fine ? Why is it's behavior different? Program 1: #include <iostream> typedef int s1; typedef int s2; void print(s1 a){ std::cout << "s1\n"; } void print(s2 a){ std::cout << "s2\n"; } int main() { s1 a; s2 b; print(a); ...
Typedefs don't define new types, they merely create aliases for existing types. In your first program s1 and s2 are both aliases for int. In your second program they are aliases for two different structures that just happen to be identical in structure. You could have assigned names to the two structures which would ha...
2,339,381
2,373,761
Converting C++ TCP/IP applications from IPv4 to IPv6. Difficult? Worth the trouble?
Over the years I've developed a small mass of C++ server/client applications for Windows using WinSock (Routers, Web/Mail/FTP Servers, etc... etc...). I’m starting to think more and more of creating an IPv6 version of these applications (While maintaining the original IPv4 version as well, of course). Questions: What ...
getaddrinfo and getnameinfo are your friends.. As much as possible I suggest they be your best friends in your quest to provide IPv4 and IPv6 support in an existing application. If done right by adding IPv6 support you also end up abstracting the system to the point where an unknown future IP protocol can run without c...
2,339,445
2,339,553
Error launching a Java app from a Win32 C++ app using CreateProcess
I'm trying to launch a Java app from a C++ app using the following code: #include <windows.h> #include <memory.h> #include <tchar.h> int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { STARTUPINFOW siStartupInfo; PROCESS_INFORMATION piProcessInfo; ...
Solved it. I used: if (CreateProcess(TEXT("C:\\Program Files\\Java\\jre6\\bin\\java.exe"), TEXT(" -jar test.jar"), NULL, NULL, false, CREATE_DEFAULT_ERROR_MODE, NULL, NULL, &siStartupInfo, &piProcessInfo) == false) { MessageBox(NULL, L"Could not load app", L"Error", 0); } Whereas you've used: if (CreatePro...
2,339,459
2,339,496
Is there any reason a .Net windows programmer needs to learn C or C++ anymore?
Can someone describe what advantages a C or C++ programmer would have over a .Net programming when developing for Windows?
There's a saying that every sufficiently complex C application ultimately ends up reimplementing parts of C++. The same goes with C++ programs and higher languages. Learning C and C++ will indirectly make you a better programmer by helping you gain a deeper understanding of how .Net actually works, and why the designer...
2,339,487
2,339,510
Calculate Angle of 2 points
Given P1 and P2, how can I get the angle from P1 to P2? Thanks
It's just float angle = atan2(p1.y - p2.y, p1.x - p2.x). Of course the return type is in radians, if you need it in degrees just do angle * 180 / PI
2,339,558
2,339,619
Mocking non-virtual methods in C++ without editing production code?
I am a fairly new software developer currently working adding unit tests to an existing C++ project that started years ago. Due to a non-technical reason, I'm not allowed to modify any existing code. The base class of all my modules has a bunch of methods for Setting/Getting data and communicating with other modules. ...
I would write a Perl/Ruby/Python script to read in the original source tree and write out a mocked source tree in a different directory. You don't have to fully parse C++ in order to replace a function definition.
2,339,593
6,578,941
overriding ctype<wchar_t>
I'm writing a lambda calculus interpreter for fun and practice. I got iostreams to properly tokenize identifiers by adding a ctype facet which defines punctuation as whitespace: struct token_ctype : ctype<char> { mask t[ table_size ]; token_ctype() : ctype<char>( t ) { for ( size_t tx = 0; tx < table_size; ++ tx )...
(It's been a year with no substantive answer, and I've learned a lot about iostreams in the meantime…) The custom facet exists exclusively to serve the string extraction operator in >> token. That operator is defined in terms of use_facet< ctype< wchar_t > >( in.getloc() ).is( ios::space, c ) "for the next available in...
2,339,679
2,339,910
What are the differences between .so and .dylib on macOS?
.dylib is the dynamic library extension on macOS, but it's never been clear to me when I can't / shouldn't use a traditional unix .so shared object. Some of the questions I have: At a conceptual level, what are the main differences between .so and .dylib? When can/should I use one over the other? Compilation tricks & ...
The Mach-O object file format used by Mac OS X for executables and libraries distinguishes between shared libraries and dynamically loaded modules. Use otool -hv some_file to see the filetype of some_file. Mach-O shared libraries have the file type MH_DYLIB and carry the extension .dylib. They can be linked against wit...
2,339,702
2,340,294
Setting Resized bitmap file to an MFC Picture Control
Is there an easier way to do it than this, and if this is the only way, are there any potential memory leaks here? CImage img1; int dimx = 100, dimy = 100; img1.Load(filename); //filename = path on local system to the bitmap CDC *screenDC = GetDC(); CDC *pMDC = new CDC; pMDC->Create...
I see no need for the CImage new_image (as SetBitmap takes a HBITMAP which you already have through pb) and pb and pMDC must be deleted (after detaching the HBITMAP), but for the rest it seems correct. CImage img1; int dimx = 100, dimy = 100; img1.Load(filename); //filename = path on local system to the bitmap CDC *sc...
2,339,759
2,339,938
Why Visual C++ 6 complains on private destructor
The following code works fine for Visual C++ 2008. However, when comes to Visual C++ 6, I get the following error. May I know why, and how I can fix the error, but still make the destructor remains in private. class X { public: static X& instance() { static X database; return database; } pr...
The revised sample shows a confirmed compiler bug for VC6 - the common workaround was to simply make the destructor public.
2,339,773
2,369,220
How to do a Extensible Storage Engine (JetBlue) repair in code?
I'm using ESE (JetBlue) in an app, when JetAttachDatabase is called it returns JET_errDatabaseDirtyShutdown. What am I supposed to do in my app? my desire is for any uncommeted transactions to be deleted
Log recovery will be done automatically by the call to JetInit, which will automatically rollback uncomitted transactions. In order for JetInit to work it has to find the logfiles so in this case you have probably either: Deleted the logfiles. Don't do that. Didn't set the logfile path correctly. Always set the same l...
2,340,005
2,340,225
c++ MFC CBitmap , CImage or BITMAP structure , get resolution (DPI)
HEllo , i can not find any way to get horizontal or/and vertical resolution for bitmap. If you know how to get it, please say it me , Thank you!
Is your question that you want to know the size of the image? CBitmap -> GetBitmapDimension CImage -> GetWidth and GetHeight BITMAP -> bmWidth and bmHeight Or that you want to know the size it will have on a display? GetDeviceCaps(hdc, LOGPIXELSX)
2,340,240
2,340,405
force exit from readline() function
I am writing program in c++ which runs GNU readline in separate thread. When main thread is exited I need to finish the thread in which readline() function is called. The readline() function is returned only when standart input came (enter pressed). Is there any way to send input to application or explicitly return fr...
Instead of returning from main thread, call exit(errno). All other threads will be killed nastily! Or, if you wanted to be nicer, and depending on your OS, you could send a signal to the readline thread, which would interrupt the syscall. Or, if you wanted to be cleverer, you could run readline in async mode, using a s...
2,340,281
2,340,309
Check if a string contains a string in C++
I have a variable of type std::string. I want to check if it contains a certain std::string. How would I do that? Is there a function that returns true if the string is found, and false if it isn't?
Use std::string::find as follows: if (s1.find(s2) != std::string::npos) { std::cout << "found!" << '\n'; } Note: "found!" will be printed if s2 is a substring of s1, both s1 and s2 are of type std::string.
2,340,311
2,340,346
posix_memalign for std::vector
Is there a way to posix_memalign a std::vector without creating a local instance of the vector first? The problem I'm encountering is that I need to tell posix_memalign how much space to allocate and I don't know how to say sizeof(std::vector<type>(n)) without actually creating a new vector. Thanks
Well, there are two sizes here. The vector itself is typically no more than a pointer or two to some allocated memory, and unsigned integers keeping track of size and capacity. There is also the allocated memory itself, which is what I think you want. What you want to do is make a custom allocator that the vector will ...
2,340,318
2,340,560
How can I visually design a component in C++ Builder?
I have been away from C++ for a couple of years now doing AS3/Flex work. I have gotten used to being able to create a component and place it in design mode with very little fuss and I am struggling to get my head around the C++ Builder way of doing the same thing. I have written many components for C++ Builder in the p...
You might want to have a look at frames (look for "Frame objects"). They are "subforms" you can design visually and then place on forms.
2,340,487
2,341,506
Is the Non-Virtual Interface (NVI) idiom as useful in C# as in C++?
In C++, I often needed NVI to get consistency in my APIs. I don't see it used as much among others in C#, though. I wonder if that is because C#, as a language, offers features that makes NVI unnecessary? (I still use NVI in C#, though, where needed.)
I think the explanation is simply that in C#, "traditional" Java-style OOP is much more ingrained, and NVI runs counter to that. C# has a real interface type, whereas NVI relies on the "interface" actually being a base class. That's how it's done in C++ anyway, so it fits naturally there. In C#, it can still be done, a...
2,340,506
2,340,523
Updating DataGrid View in Multithreaded Environment
I have set of c++ dlls and a c# exe . My c++ dlls are multi-threaded and they put data into a Database. My c# exe uses Background worker . My c# exe gets these data to a Data table asynchronously. To achieve this I am using named Mutex. My problem is when I assign this Data Table to my grid view It is crashing. I am us...
With begin invoke do you mean myDelegate.BeginInvoke? you could try myForm.Invoke this runs the delegate on the UI Thread...
2,340,691
2,340,820
Techniques for generating a 2D game world
I want to make a 2D game in C++ using the Irrlicht engine. In this game, you will control a tiny ship in a cave of some sort. This cave will be created automatically (the game will have random levels) and will look like this: Suppose I already have the the points of the polygon of the inside of the cave (the white par...
Describing how to get an arbitrary polygonal shape to render using a given 3D engine is quite a lengthy process. Suffice to say that pretty much all 3D rendering is done in terms of triangles, and if you didn't use a tool to generate a model that is already composed of triangles, you'll need to generate triangles from ...
2,340,730
22,927,149
Are there C++ equivalents for the Protocol Buffers delimited I/O functions in Java?
I'm trying to read / write multiple Protocol Buffers messages from files, in both C++ and Java. Google suggests writing length prefixes before the messages, but there's no way to do that by default (that I could see). However, the Java API in version 2.1.0 received a set of "Delimited" I/O functions which apparently do...
I'm a bit late to the party here, but the below implementations include some optimizations missing from the other answers and will not fail after 64MB of input (though it still enforces the 64MB limit on each individual message, just not on the whole stream). (I am the author of the C++ and Java protobuf libraries, but...
2,340,795
2,340,982
Does function-level linking in VC++ have any negative effects?
Visual C++ has function-level linking. Looks like it's a great thing - it can reduce the size of generated executables. Does it have any negative effects? Will I have to pay anything for the advantages of this option or can I just turn it on and enjoy the benefits?
Actually, there could be some small increase of compilation time. I don't think that it can affect negativily anything else.
2,340,919
2,341,014
Const-Correctness on complex return value
struct Foo { char * DataPtr; }; class ISomeInterface { public: Foo GetFoo( ) const; Foo GetFoo( ); }; The Foo::DataPtr is a pointer to an internal buffer of the object behing ISomeInterface. Is there a way to make sure that the Foo::DataPtr returned by the const version of ISomeInterface::GetFoo i...
You need a struct ConstFoo { const char* DataPtr; }; for this. The const in C++ is not transitive. (this is also why you have iterator and const_iterator.)
2,340,930
2,340,942
Stray '\342' in C++ program
I'm getting these errors in my program after pasting in some code: showdata.cpp:66: error: stray ‘\342’ in program showdata.cpp:66: error: stray ‘\200’ in program showdata.cpp:66: error: stray ‘\235’ in program showdata.cpp:66: error: stray ‘\’ in program showdata.cpp:66: error: stray ‘\342’ in program showdata.cpp:66:...
The symbol ” is not ". Those are called 'smart quotes' and are usually found in rich documents or blogs.
2,341,084
2,341,507
How to change an object's attribute in a value into a map
I have a map like this: map<prmNode,vector<prmEdge> > nodo2archi; In a certain situation, I have to change an object's attribute in a value into the vector of prmEdge. This is the code: prmNode par=freePathNode[z]; z++; prmNode arr=freePathNode[z]; map<prmNode,vector<prmEdge> >::iterator it; it=nodo2archi.find(par); ...
it->second.begin()->setState(1) should do it. it->second.begin() is a vector iterator, so you need -> to access the vector element. If you need to access the other elements of the vector, you can of course use the vector's interface rather than iterators, e.g. it->second[2].setState(1).
2,341,113
2,341,160
How to shut off a certain process on windows?
I have some .exe name i want to terminate if its running, how? Edit: I modified mike's example to this, and its perfect: WinExec("taskkill /IM notepad.exe /F", SW_HIDE);
If you know the name of a process to kill, for example notepad.exe, use the following command from a command prompt to end it taskkill /IM notepad.exe This will cause the program to terminate gracefully, asking for confirmation if there are unsaved changes. To forcefully kill the same process, add the /F option to the...
2,341,177
2,341,202
c++ std::ofstream flush() but not close()
I'm on MacOSX. In the logger part of my application, I'm dumping data to a file. suppose I have a globally declared std::ofstream outFile("log"); and in my logging code I have: outFile << "......." ; outFile.flush(); Now, suppose my code crashes after the flush() happens; Is the stuff written to outFile before the flu...
From the C++ runtime's point of view, it should have been written to disk. From an OS perspective it might still linger in a buffer, but that's only going to be an issue if your whole machine crashes.
2,341,354
2,348,295
Qt in visual studio: connecting slots and signals doesn't work
I have installed Qt and Qt for VS plugin. Everything works fine, UI applications compile and run that's ok, but connecting signals and slots doesn't. I have Q_OBJECT in my class and for connecting I am using this code in constructor: connect(ui.mainTableView, SIGNAL(activated(const QModelIndex &)), this, SLOT(s...
RESULT: Oh no it turns out to be a silly question, thanks everybody, all answers pushed me towards the solution, but the last step was to find out that on my platform items are activated only by double-click, not single. Sorry
2,341,866
2,341,921
Why was Cassandra written in Java?
Question about Cassandra Why the hell on earth would anybody write a database ENGINE in Java ? I can understand why you would want to have a Java interface, but the engine... I was under the impression that there's nothing faster than C/C++, and that a database engine shouldn't be any slower than max speed, and cert...
I can see a few reasons: Security: it's easier to write secure software in Java than in C++ (remember the buffer overflows?) Performance: it's not THAT worse. It's definitely worse at startup, but once the code is up and running, it's not a big thing. Actually, you have to remember an important point here: Java code i...
2,341,987
2,362,757
Where is the call to std::map::operator[] in this code?
I have the following typedef's in my code: typedef unsigned long int ulint; typedef std::map<ulint, particle> mapType; typedef std::vector< std::vector<mapType> > mapGridType; particle is a custom class with no default constructor. VS2008 gives me an error in this code: std::set<ulint> gridOM::ids(int filter) { st...
Case closed. It turns out that I did in fact make the coding mistake of writing a call to operator[], but it was hundreds of lines further down in the source file from where the error was reported. Apparently VS just pointed me to the first usage of a variable of mapType instead of the actual point where it tried to in...
2,342,037
2,343,072
To which extent is "boost does it" equivalent to "very portable, use it"?
In this answer to a question asking "is doing Z this way portable" the idea is "boost does it this way, it means it is very portable". Can I just always consult boost sources to find the most portable way of doing something in C++? How can I judge for myself if boost is really such a collection of super-portable code?
There are some cases where Boost libraries exist precisely because they wrap very non-portable code. The most obvious examples are the file system and threading stuff. The telltale sign of this is a large use of Boost.Config macros. Boost code that doesn't depend on Boost.Config (or other non-standard #ifdefs) will be...
2,342,162
2,342,176
std::string formatting like sprintf
I have to format std::string with sprintf and send it into file stream. How can I do this?
You can't do it directly, because you don't have write access to the underlying buffer (until C++11; see Dietrich Epp's comment). You'll have to do it first in a c-string, then copy it into a std::string: char buff[100]; snprintf(buff, sizeof(buff), "%s", "Hello"); std::string buffAsStdStr = buff; But I'm not su...
2,342,511
2,342,596
What if I don't call ReleaseBuffer after GetBuffer?
From CString to char*, ReleaseBuffer() must be used after GetBuffer(). But why? What will happen if I don't use ReleaseBuffer() after GetBuffer()? Can somebody show me an example? Thanks.
I'm not sure that this will cause a memory leak, but you must call ReleaseBuffer to ensure that the private members of CString are updated. For example, ReleaseBuffer will update the length field of the CString by looking for the terminating null character.
2,342,921
2,395,290
C or C++ HTTP daemon in a thread?
I'm starting up a new embedded system design using FreeRTOS. My last one used eCos, which has a built-in HTTP server that's really lightweight, especially since I didn't have a filesystem. The way it worked, in short, was that every page was a CGI-like C function that got called when needed by the HTTP daemon. Speci...
I suggest you have a look at libmicrohttpd, the embedded web server: http://www.gnu.org/software/libmicrohttpd/ It is small and fast, has a simple C API, supports multithreading, is suitable for embedded systems, supports POST, optionally supports SSL/TLS, and is available under either the LGPL or eCos license (depen...
2,343,191
2,343,223
failed constructor and failed destructor in C++
I have one question about failed constructor and failed destructor in C++. I noticed that when the constructor failed, an exception will be thrown. But there is no exception thrown in destructor. My question is 1) If constructor failed, what exception will be thrown? bad_alloc? or anything else related? Under what si...
If a constructor fails, an exception is thrown only if the constructor is implemented so that it throws an exception. (You might need to differentiate between memory allocation and construction. Allocating memory using new might fail throwing a std::bad_alloc exception.) There is no case where a constructor, in gener...
2,343,208
2,343,294
Can you catch an exception by the type of a conversion operator?
I don't know how to phrase the question very well in a short subject line, so let me try a longer explanation. Suppose I have these exception classes: class ExceptionTypeA : public std::runtime_error { // stuff }; class ExceptionTypeB : public std::runtime_error { // stuff operator ExceptionTypeA() const...
You cannot. Standardese at 15.3/3: A handler is a match for an exception object of type E if The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv- qualifiers), or the handler is of type cv T or cv T& and T is an unambiguous public base class of E, or the handler is of type c...
2,343,245
2,343,337
Can you please explain this C++ delete problem?
I have the following code: std::string F() { WideString ws = GetMyWideString(); std::string ret; StringUtils::ConvertWideStringToUTF8(ws, ret); return ret; } WideString is a third-party class, so are StringUtils. They are a blackbox to me. Second parameter is passed by reference. When I step through the debug...
If StringUtils was compiled separately (e.g., with a different compiler version), you may have a conflict in the object layout. If StringUtils is in a DLL, you have to ensure that both it and the main program are compiled to use the standard library in a DLL. Otherwise, each module (executable and DLL) will have its o...
2,343,558
2,343,630
How do I declare an array of objects whose class has no default constructor?
If a class has only one constructor with one parameter, how to declare an array? I know that vector is recommended in this case. For example, if I have a class class Foo{ public: Foo(int i) {} } How to declare an array or a vector which contains 10000 Foo objects?
For an array you would have to provide an initializer for each element of the array at the point where you define the array. For a vector you can provide an instance to copy for each member of the vector. e.g. std::vector<Foo> thousand_foos(1000, Foo(42));
2,343,719
2,344,146
C++ templated functor in lambda expression
This first piece has been solved by Eric's comments below but has led onto a secondary issue that I describe after the horizontal rule. Thanks Eric! I'm trying to pass a functor that is a templated class to the create_thread method of boost thread_group class along with two parameters to the functor. However I can't se...
Sig (or in your case, simply typedef void result_type; is necessary. IIRC, lambda::bind makes const copies of its arguments. There is thus a problem with functors with non-const operator(). This is solved by making Ftor::operator()const or by wrapping (in doFtor()), _ftor with boost::ref There is a similar problem with...
2,343,821
2,350,352
How to include the calling class and line number in the log using Pantheios?
I just started using Pantheios and it feels really like a great library for logging! Maybe even the greatest one for C++! Congratulations to the author! However, I could not find neither in the documentation nor in all the forum posts anything about how to include the calling class and the line number in the log. I'm u...
The answer for this actually is in the FAQ file included in the library download. I have a fixed-back-end DLL that has the following header in it and I am able to include the class, function and line number in the log file. #include <pantheios/pantheios.hpp> #include <pantheios/frontends/fe.N.h> //#include <pantheios/f...
2,343,979
2,343,998
I'm getting error C2664 on some I/O code
void BinaryTree::InitializeFromFile(string Filename){ ifstream inFile; inFile.open(Filename, fstream::binary); if(inFile.fail()){ cout<<"Error in opening file "<<Filename; return; } for(int i=0;i<=255;i++) Freq[i]=0; char c; inFile.get(c); while(!inFile.eof()){ Freq[c] ++; inFile.get(c); } } ...
Use Filename.c_str() instead - open() doesn't take a std::string as a parameter for the filename.
2,344,081
2,344,106
NLP project, python or C++
We are working on Arabic Natural Language Processing project, we have limited our choices to either write the code in Python or C++ (and Boost library). We are thinking of these points: Python Slower than C++ (There is ongoing work to make Python faster) Better UTF8 support Faster in writing tests and trying differen...
Write it in Python, profile it, and if you need to speed parts of it up, write them in C++. Python and C++ are similar enough that the "familiar" advantage with C++ will be irrelevant pretty quick. I say this as someone who has developed primarily in C++ and has recently gotten serious with Python. I like them both, ...
2,344,087
2,344,108
Try does not catch exception in DllImport function
I call C++ function from C# project: [System.Runtime.InteropServices.DllImport("C.dll")] public static extern int FillSlist(out string slist); and then try { FillSlist(out slist); } catch { } C++ dll is protected by third-party tool, so some code is being performed before FillSlist is really executed. Something rea...
Is this running on CLR 4.0? If so ... If an exception does not get caught in an open catch block as demonstrated in your code it's because the CLR considers it a corrupted state exception and is by default not handled by user code. Instead it propagates up and causes the process to terminate. It does this for a reas...
2,344,233
2,344,248
Validate HWND using Win32 API
From the native Win32 API using C++ is there a way to determine whether the window associated with an HWND is still valid?
You could use the Win32 API IsWindow. It is not recommended to use it though for 2 reasons: Windows handles can be re-used once the window is destroyed, so you don't know if you have a handle to an entirely different window or not. The state could change directly after this call and you will think it is valid, but it...
2,344,288
2,344,962
Qt Asynchronous Action During aboutToQuit
I've got some Asynchronous cleanup activity I need to do as my Qt application is shutting down. My current approach is to trap the aboutToQuit signal. I launch my Asynchronous behavior, and then the application shuts down. Is there any way to block Qt from shutting down until my asynchronous behavior is complete? This ...
Why do you launch your cleanup code asynchronously if you have to wait anyway until your code is done? If you don't connect your slot as QueuedConnection to aboutToQuit it should block until your cleanup code is done. But if you really want launch it asynchronously you have to synchronize it by hand: QSemaphore wait4Cl...
2,344,294
2,344,380
Command arguments in compiler configurations
[edit] I meant to say "command arguments in compiler configs" . for the title. I am trying to get into game mods. And I am trying to implement the source sdk. one of the steps is to go into debugging in my compiler configurations and add some data to the command arguments -dev -sw -game "C:\Program Files (x86)\Steam\st...
In a normal (read console) C/C++ application you would have program entry point with the following declaration: int main( int argc, char* argv[] ); Here argc is the number of command line "strings", including the command itself, while argv is the array of these strings. So in your example it'd be argc of 5 (adding the...
2,344,330
2,344,365
Algorithm to add or subtract days from a date?
I'm trying to write a Date class in an attempt to learn C++. I'm trying to find an algorithm to add or subtract days to a date, where Day starts from 1 and Month starts from 1. It's proving to be very complex, and google doesn't turn up much, Does anyone know of an algorithm which does this?
The easiest way is to actually write two functions, one which converts the day to a number of days from a given start date, then another which converts back to a date. Once the date is expressed as a number of days, it's trivial to add or subtract to it. You can find the algorithms here: http://alcor.concordia.ca/~gpka...
2,344,465
2,344,578
How to create interface for C++ application with XAML?
How to create interface for C++ application with XAML? (I SEARCH FOR SOME APP LIKE EXPRESSION BLEND (OR even beter a plug in for it))
Visual Studio Pro 2008 does support C++ .Net and XAML interface designer so it should do what you are looking for. PS : Visual Studio 2010 is going to be released soon. I never tried XAML with this one but it should have a better support.
2,344,670
2,344,689
Tired of building web applications? Trying maybe C++?
I'm getting a little tired of building web applications. Feels like same thing over and over again. Are there any other cool things you can do. I'm maybe getting to start coding in C++. Any suggestions for tips in that area? Should I delve into Qt or MFC? Any suggestions?
If you're just starting out in C++, I recommend starting with some simple console-based applications first. Get used to the syntax and some fundamentals like strong typing, pointers, and understanding the difference between pointers and references. (Depending on your experience as a developer, you may already know all ...
2,344,673
2,344,709
Alternative version of find_if which finds all, not just the first?
Is there an alternative version of std::find_if that returns an iterator over all found elements, instead of just the first one? Example: bool IsOdd (int i) { return ((i % 2) == 1); } std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); std::vector<int>::iterator it = find_if(v.begin...
You can just use a for loop: for (std::vector<int>:iterator it = std::find_if(v.begin(), v.end(), IsOdd); it != v.end(); it = std::find_if(++it, v.end(), IsOdd)) { // ... } Alternatively, you can put your condition and action into a functor (performing the action only if the condition is true) and just u...
2,344,691
2,344,714
How can I convert the following java function into C++?
If I have the following Java code: int[][] readAPuzzle() { Scanner input = new Scanner(System.in); int[][] grid = new int[9][9]; for (int i=0; i<9; i++) for (int j=0; j<9; j++) grid[i][j] = input.nextInt(); return grid; } public static void main(String[] args) { // Read a Sudoku puz...
You need to read in the input text into your array grid and pass it on. grid[i][j] = cin >> grid[i][j]; Doesn't do what you think it does, it tries to assign an object of type istream to grid[ i ][ j ] cin >> grid[i][j]; however suffices. Also, note in C++ the dimensions follow the identifier as in: int grid[9][9];...
2,344,788
2,344,827
iostream, some questions
I've seen people do things like.... istringstream ibuf; if (ibuf >> zork >> iA >> Comma >> iB) now I guess the value depends on what >>iB exposes but exactly what is that and what does it mean? Does true mean all the ietms were extracted? Also, after an expression like ibuf >> zork >> iA >> Comma >> iB; is the...
This works because of two properties of istream objects: istreams return themselves after each extraction (the >> operator) to allow chaining multiple extractions (a >> b >> c) istreams return their status (as though .good() were called) when they're cast/converted to bool, via overloading bool operator !() Basicall...
2,344,887
2,345,126
Select which handles are inherited by child process
When creating a child process in C++ using Windows API, one can allow inheritance of handles from parent to child. In a Microsoft example "Creating a Child Process with Redirected Input and Output", redirecting a child process' std in/out to pipes created by the parent, it is necessary to allow inheritance for the redi...
If the output file handle is inherited by the child process, then that is because the code in the parent process that opened the file explicitly stated that the file handle should be inheritable. It passed a value for the lpSecurityAttributes parameter of CreateFile. The default state is for the handle to not be inheri...
2,344,910
2,345,028
Create derived class instance from a base class instance without knowing the class members
Is this scenario even possible? class Base { int someBaseMemer; }; template<class T> class Derived : public T { int someNonBaseMemer; Derived(T* baseInstance); }; Goal: Base* pBase = new Base(); pBase->someBaseMemer = 123; // Some value set Derived<Base>* pDerived = new Derived<Base>(pBase); The value of pDe...
Why wouldn't you actually finish writing and compiling the code? class Base { public: // add this int someBaseMemer; }; template<class T> class Derived : public T { public: // add this int someNonBaseMemer; Derived(T* baseInstance) : T(*baseInstance) // add this { return; } // add this...
2,344,929
2,345,017
Pointers in C# to Retrieve Reference From DllImport Function
I am referencing a DLL in my C# project as follows: [DllImport("FeeCalculation.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] public static extern void FeeCalculation(string cin, string cout, string flimit, string frate, string fwindow, string fincrement, s...
Edit: now that we have structures to work with, a better solution is possible. Just declare structs in C# that match your C++ structs, and use them in the extern declaration [StructLayout(LayoutKind.Sequential)] public struct feeAnswer { public uint fee; public uint tax1; public uint tax2; public u...
2,345,034
2,345,077
Terminate all (grand)children when terminating a child process
I will jump right in, to be brief and descriptive: C++, Windows API I am creating child processes using CreateProcess to run external (command-line) applications. I have built in a time-out, and if the child process has not returned normal execution by that time, I wish to force termination on that child process. Idea...
You can use Job objects to kill all the processes as a unit. You create a job object via the CreateJobObject API, and assign a process to it with AssignProcessToJobObject. New processes created by a process in a job object belong to the same job object by default. Calling TerminateJobObject will terminate all associ...
2,345,079
2,345,106
static array allocation issue!
I want to statically allocate the array. Look at the following code, this code is not correct but it will give you an idea what I want to do class array { const int arraysize; int array[arraysize];//i want to statically allocate the array as we can do it by non type parameters of templates public: array(); }; ar...
If your array size is always the same, make it a static member. Static members that are integral types can be initialized directly in the class definition, like so: class array { static const int arraysize = 10; int array[arraysize]; public: array(); }; This should work the way you want. If arraysize is not...
2,345,177
2,345,223
Basic C++ Idioms / Techniques
Note: marked as community wiki. In recent days, I've realized how little I know about C++. Besides: using the STL implementing RAII implementing ref-counted smart pointers writing my own policy-based template classes overloading operators << for fun What other techniques are must-know for a good C++ programmer? Than...
I think this should cover it: More C++ Idioms - Wikibooks
2,345,191
2,345,210
Windows game: UTF-8, UTF-16, DirectX and Lua
I'm developing a game for windows for learning purposes (I'm learning DirectX). I would like it to have UTF support. Reading this question I learned that windows uses wchar_t, which is UTF-16. I want my game to have Lua scripting support, and Lua doesn't really like Unicode much.. It simply treats strings as a "stream ...
It doesn't use 8859-1 either, it uses your system's local code page. You can convert to UTF16 and use DrawText() by converting the string yourself. If your class library doesn't have any support then you can use MultiByteToWideChar().
2,345,284
2,345,366
Can C++ policy classes be used to specify existence / non-existence of constructors?
Suppose I have: struct Magic { Magic(Foo* foo); Magic(Bar* bar); }; Is there a way to make Magic a template, and define template classes s.t. typedef Magic<FooPolicy, ...> MagicFoo; typedef Magic<BarPolicy, ...> MagicBar; typedef Magic<..., ...> MagicNone; typedef Magic<FooPolicy, BarPolicy> MagicAll; s.t. MagicF...
You can write a constructor accepting anything, and then delegate to whatever the policies provide: // "Tag" and "No" are used to make the class/function unique // (makes the using declarations work with GCC). template<int Tag> struct No { void init(No); }; template<typename P1 = No<0>, typename P2 = No<1>, typename...
2,345,347
2,345,440
Finding the "Nth node from the end" of a linked list
This seems to be returning the correct answer, but I'm not sure if this is really the best way to go about things. It seems like I'm visiting the first n nodes too many times. Any suggestions? Note that I have to do this with a singly linked list. Node *findNodeFromLast( Node *head, int n ) { Node *currentNode; ...
Another way to do it without visiting nodes twice is as follows: Create an empty array of size n, a pointer into this array starting at index 0, and start iterating from the beginning of the linked list. Every time you visit a node store it in the current index of the array and advance the array pointer. When you fill ...
2,345,390
2,345,421
How to find the time taken to send data across UDP
I have a simple UDP client server written in C++ on Ubuntu 9.10 where the client sends a set to the server. How can I check how much time s it taking to sent it. I need to find the time from start of transfer to end. Supposing my server and client are on the same machine then can I somehow save the system time and find...
If you are asking how long it takes for the packet to arrive at the server, there is no built in way to get that information. If the server sends a reply, you can time how long it takes between sending the request and getting the reply and divide by 2 (not accurate, but a decent estimate).
2,345,551
2,345,560
What does this dynamic allocation do?
Today, I found out that you can write such code in C++ and compile it: int* ptr = new int(5, 6); What is the purpose of this? I know of course the dynamic new int(5) thing, but here i'm lost. Any clues?
You are using the comma operator, it evaluates to only one value (the rightmost). The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is conside...
2,345,744
2,345,769
reference counting with cycles in C++ smart pointer
In shared_ptr smart pointer, reference counting is used. However, reference counting has a problem, that it can't break cycles of reference. I have four questions with this issue. 1) Could anybody offer me one snippet in which the cycles of reference happened? 2) If it can't break cycles of reference, how does RCSP gu...
The usual way to avoid cycles is to use weak references in any one point of the cycle. shared_ptr has a companion type, weak_ptr, which is designed for this purpose. Which part of the cycle to weaken is a matter of design. In designs where "parent" objects own "children", then the reference from parent to child should ...
2,345,774
2,345,777
Confused on C++ casting
I have been reading a lot about C++ casting and I am starting to get confused because I have always used C style casting. I have read that C style casting should be avoided in C++ and that reinterpret_cast is very very dangerous and should not be used whenever there is an alternative. On the contrary to not using reint...
Using reinterpret_cast is acceptable if you know that the pointer was originally of the destination type. Any other use is taking advantage of implementation-dependent behavior, although in many cases this is necessary and useful, such as casting a pointer to a structure into a pointer to bytes so that it can be serial...
2,345,933
2,345,936
Boost Regex Find host/domain name
I'm very new to c++ and boost. I'm trying to get the host name of a given url: this is what I have now: int main() { string url = "http://www.amazon.com/gp/product/blabla"; //Regular Expression from Javascript. boost::regex ex("/^((\w+):\/\/\/?)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#;\|]+)?([;\|])?([^\?#]+...
Since the backslash (\) is an escape character in C (& C++) string constants, you need to escape it. i.e replace all instances of \ with \\ LOL. I had the same problem with this post! All the backslashes disappeared because I forgot to escape them. Check this page to see the different regex types available in Boost. It...
2,346,060
2,346,146
Calling Lua function without executing script
I am embedding Lua into a C/C++ application. Is there any way to call a Lua function from C/C++ without executing the entire script first? I've tried doing this: //call lua script from C/C++ program luaL_loadfile(L,"hello.lua"); //call lua function from C/C++ program lua_getglobal(L,"bar"); lua_call(L,0,0); But it...
As was just discussed in #lua on freenode luaL_loadfile simply compiles the file into a callable chunk, at that point none of the code inside the file has run (which includes the function definitions), as such in order to get the definition of bar to execute the chunk must be called (which is what luaL_dofile does).
2,346,083
2,346,098
why implicit conversion is harmful in C++
I understand that the keyword explicit can be used to prevent implicit conversion. For example Foo { public: explicit Foo(int i) {} } My question is, under what condition, implicit conversion should be prohibited? Why implicit conversion is harmful?
Use explicit when you would prefer a compiling error. explicit is only applicable when there is one parameter in your constructor (or many where the first is the only one without a default value). You would want to use the explicit keyword anytime that the programmer may construct an object by mistake, thinking it may...
2,346,130
2,346,589
Does the GPLv2 preclude me from using KLone for my website?
I recently discovered Klone. Being a C++ developer, I'm fascinated by the idea of getting to use C++ for my web development work (I know, I'm a glutton for punishment!)... Anyhow, it looks like the open source version of KLone is licensed under GPLv2... Normally, this would be fine, but since you're app is compiled and...
I think the answer on the GPL version: Yes, if you are making a non-GPL compatible open source product, they are expressly asking that you not use the source code version of klone. That is sort of the point of the GPL. You can't use the source if you don't open up your source. As to the question of does the GPL cover...
2,346,163
2,346,223
pimpl idiom vs. bridge design pattern
I just noticed a new term pimpl idiom, what's the difference between this idiom with Bridge design pattern? I am confused about that. I also noticed the pimpl idiom is always used for swap function, what's that? Could anybody give me an example?
PIMPL is a way of hiding the implementation, primarily to break compilation dependencies. The Bridge pattern, on the other hand, is a way of supporting multiple implementations. swap is a standard C++ function for exchanging the values of two objects. If you swap the pointer to the implementation for a different implem...
2,346,189
2,346,203
How can I break out of my do/while loop?
void GasPump::dispense() { bool cont = true; char stop; do{ cout << "Press any key, or enter to dispense.\n" << "Or press 0 to stop: \n"; cin.get(stop); gasDispensed = gasDispensed + gasDispensedPerCycle; charges = costPerGallon*gasDispensed; d...
Try comparing stop to the zero char. stop == '0' Also you can simplify your code by doing this. void GasPump::dispense() { char stop; do { cout << "Press any key, or enter to dispense.\n" << "Or press 0 to stop: \n"; cin.get(stop); gasDispensed = gasDispensed + gasDispens...
2,346,277
2,346,290
Does the following code invoke Undefined Behavior?
#include <iostream> #include <cmath> #define max(x,y) (x)>(y)? (x): (y) int main() { int i = 10; int j = 5; int k = 0; k = max(i++,++j); std::cout << i << "\t" << j << "\t" << k << std::endl; }
No, it doesn't. In this case the situation is saved by the fact the ?: operator has a sequence point immediately after evaluating the first operand (the condition) and after that only one of the two expressions (second or third operand) is evaluated. Your code is equivalent to ... bool c = i++ > ++j; k = c ? i++ : ++j...
2,346,328
2,346,344
Breaking down WinMain's cmdLine in old style main()'s arguments
I want to convert WinMain's cmdLine argument to argc and argv so I can use the argument parsing function I wrote for console applications. This would be trivial except that I want to support "quotes" too. For example: test.exe test1 test2 "testing testing" should be argv[0] = "test.exe"; argv[1] = "test1"; argv[2] = "t...
CommandLineToArgvW looks like it would be helpful here.
2,346,462
2,346,538
Tracking down strange error
I'm trying to do some C++ exercises, but I'm running into a error on build, which doesn't just jump out at me. What am I missing? I'm just getting back to C++ from C# et al after having done it years ago. [ERROR] syntax error : 'return' [/ERROR] #include <iostream> using namespace std; /* Pre-compiler d...
The Corrected code sample its the while loop that needs replacement #include <iostream> namespace { bool isValidDrinkChoice(int Choice, int MaxNumDrinks) { return ((Choice < MaxNumDrinks) && (Choice >= 0)); } } /* Primary Entry Point for Executable */ int main() { using namespace std; const char *...
2,346,481
2,346,494
An initial value assumption about map in c++
I am initializing a map map<string,int> ex; in C++. I could not find contains_key or similar function in stl, hence I am just using ex[inputString]++; The debugger shows the int to be initialized to zero correctly, is it a good assumption?
Yes, values that do not exist when accessed with operator[] are default-constructed. For numeric values, this is 0. That said, you're looking for the count method: bool hasElement = ex.count("element");
2,346,533
2,346,647
partial specialization of template class issue!
The following code is confusing me //partial specialization of vector template<class t> class vector {.... }; template<class t> //teacher said that this partial specialization will handle all type of pointers class vector<t*> ... }; This is confusing me a lot, Suppose t is a char* , as the compiler will first look fo...
When the compiler instantiates vector<char*>, it matches the following template: template<class T> class vector<T*> { ... }; For this template to produce a class vector<char*> it needs to be instantiated with T=char, and this is exactly what the compiler does. When the compiler sees the type vector<char*> it will no...
2,346,616
2,346,658
Need clarifications in C-style, reinterpret, and const casts
Am I right in assuming that C-style casts (which are discouraged) are nothing but reinterpret_casts? Using the latter is visually striking and easy to search when looking for nasty casts, and hence it's recommended over C-style casts? If casting away const using const_cast and writing to a originally const object is un...
No. A C cast can do the equivalent of a const_cast, a static_cast, a reinterpret_cast, or a combination thereof. In case that wasn't quite enough, it can also do at least one minor trick that no combination of the newer casts can do at all! You can use const_cast with defined results if the original variable is defined...
2,346,653
2,347,752
How to globally mute and unmute sound in Vista and 7, and to get a mute state?
I'm using the old good Mixer API right now, but it does not work as expected on Windows Vista & 7 in the normal, not in XP compatibility mode. It mutes the sound for the current app only, but I need a global (hardware) mute. How to rearch the goal? Is there any way to code this w/o COM interfaces and strange calls, in ...
The audio stack was significantly rewritten for Vista. Per-application volume and mute control was indeed one of the new features. Strange calls will be required to use the IAudioEndpointVolume interface.
2,346,714
2,346,721
How can I sort a std::list with case sensitive elements?
This is my current code: #include <list> #include <string> using std::string; using std::list; int main() { list <string> list_; list_.push_back("C"); list_.push_back("a"); list_.push_back("b"); list_.sort(); } Does the sort() function sort the elements according to their character codes? I want ...
The default comparator (<) using the default char_traits< char > will sort your list as C a b. See list::sort. In order to achieve the desired order a b C you can either: compose your list of string types with custom char_traits, or provide an instance of a custom string comparator to sort, e.g. bool istring_less(cons...
2,346,728
2,347,737
What may be the causes of the error 0x80010108 (The object invoked has disconnected from its clients)?
In C++ program the call to method of coclass returns the error 0x80010108 (The object invoked has disconnected from its clients). What may be the causes of that?
It is an RPC error, you'll see it when you use out-of-process COM. It tells you that the server .exe stopped running. It probably bombed. Or decided to exit even though there were still active interface references. That could be a reference count problem. Or improper use of CAtlModule::Lock(). Etcetera, I can onl...
2,346,797
2,346,825
Why does a class used as a value in a STL map need a default constructor in ...?
Below is the class used as the value in a map: class Book { int m_nId; public: // Book() { } <----- Why is this required? Book( int id ): m_nId( id ) { } }; Inside main(): map< int, Book > mapBooks; for( int i = 0; i < 10; ++i ) { Book b( i ); mapBooks[ i ] = b; } The statement causing the erro...
operator[] performs a two step process. First it finds or creates a map entry for the given key, then it returns a reference to the value part of the entry so that the calling code can read or write to it. In the case where entry didn't exist before, the value half of the entry needs to be default constructed before it...
2,346,800
2,346,810
C++ EOF Getline Error
I was using the form used in one of the related questions. Only problem is that i keep getting right at the end of the file. The file is an fstream and the str is a string. Unhandled exception Microsoft C++ exception: std::ios_base::failure while (getline(file, str)) { } if (cin.bad()) { // IO error } else if ...
If you are getting std::ios_base::failure exceptions thrown it is most likely caused by you (or some code that you are using) turning them on for your file. They should be off by default. Just to test, you can try turning them off immediately before the while loop, but you probably need to investigate what is turning t...
2,346,806
2,346,849
What is a segmentation fault?
What is a segmentation fault? Is it different in C and C++? How are segmentation faults and dangling pointers related?
Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” It’s a helper mechanism that keeps you from corrupting the memory and introducing hard-to-debug memory bugs. Whenever you get a segfault you know you are doing something wrong with memory – accessing a variable that...
2,346,879
2,347,810
How do I fix class template has already been defined?
I am implementing ZipArchive library into my project, and I fought with it for over an hour getting it setup right to stop all the linker errors. But now I still have this left over and I am not sure of the best approach to fix it, could use some help. C:\Program Files\Microsoft Visual Studio 9.0\VC\atlmfc\include\afxt...
Both MS' ATL/MFC headers and the HL2 SDK contain a class template CThreadLocal. If you'd include those in the right order, i.e. ATL/MFC headers first (or the headers which include them), then the HL2 SDK headers, the HL2 SDK should handle that problem via an #ifndef __AFXTLS_H__.
2,346,940
2,346,953
How to copy string into fixed length string in C++
I have a string which I want to copy into a fixed length string. For example I have a string s = "this is a string" that is 16 characters long. I want to copy this into a fixed length string s2 that is 4 characters long. So s2 will contain "this". I also want to copy it into a fixed length string s3 that is 20 charact...
s.resize(expected_size,' ');
2,347,138
2,515,224
Fast implementation/approximation of pow() function in C/C++
I m looking for a faster implementation or good a approximation of functions provided by cmath. I need to speed up the following functions pow(x,y) exp(z*pow(x,y)) where z<0. x is from (-1.0,1.0) and y is from (0.0, 5.0)
Here are some approxmiations: Optimized pow Approximation for Java and C / C++. This approximation is very inaccurate, you have to try for yourself if it is good enough. Optimized Exponential Functions for Java. Quite good! I use it for a neural net. If the above approximation for pow is not good enough, you can stil...
2,347,230
2,347,253
Keeping encrypted data in memory
I'm working with a listview control which saves the data using AES encryption to a file. I need to keep the data of every item in listview in std::list class of std::string. should I just keep the data encrypted in std::list and decrypt to a local variable when its needed? or is it enough to keep it encrypted in file o...
To answer this question you need to consider who your attackers are (i.e. who are you trying to hide the data from?). For this purpose, it helps if you work up a simple Threat Model (basically: Who you are worried about, what you want to protect, the types of attacks they may carry out, and the risks thereof). Once thi...
2,347,357
2,347,995
how to get new vertex coordinates of a rectangular block after applying glRotate()
I am drawing a rectangular block: GLfloat cubeVertexV[] = { // FRONT -0.5f, -1.0f, 0.5f, 0.5f, -1.0f, 0.5f, -0.5f, 1.0f, 0.5f, 0.5f, 1.0f, 0.5f, // BACK -0.5f, -1.0f, -0.5f, 0.5f, -1.0f, -0.5f, -0.5f, 1.0f, -0.5f, 0.5f, 1.0f, -0.5f, // LEFT -0.5f, -1.0f, ...
Generally speaking, OpenGL will just accumulate the transforms, and only actually apply them to the data when you render it. In the plain old fixed-function graphics pipeline, there's no way to do it. However, as programmability has been increasing every generation, there is support for this now via OpenGL extensions, ...
2,347,370
2,347,760
How can i check that button is clicked in no modal dialog
I created main dialog and call no modal dialog, how can i check in main dialog that button is clicked in no modal? For example if i call modal i can check like this: Dialog Dlg; int DlgResult = static_cast<int>(Dlg.DoModal()); if (DlgResult== IDOK) { //do smth. }
If its a custom dialog, one way would be to use SendMessage() or PostMessage() to send the result to the main dialog when the non-modal dialog closes.
2,347,562
2,347,610
Program crashes only in Release mode outside debugger
I have quite massive program (>10k lines of C++ code). It works perfectly in debug mode or in release mode when launched from within Visual Studio, but the release mode binary usually crashes when launched manually from the command line (not always!!!). The line with delete causes the crash: bool Save(const short* data...
have you checked memory leaks elsewhere? usually weird delete behavior is caused by the heap getting corrupted at one point, then much much later on, it becomes apparent because of another heap usage. The difference between debug and release can be caused by the way windows allocate the heap in each context. For exampl...
2,347,599
2,347,751
assigning shared ptrs (boost) in constructor , unit testing
I have a C++ class(inside a dll project) whose member variables are boost::shared_ptrs to objects of other classes. Is it better to assign them inside the class constructor or have a separate init() function which does that. I am assuming the default value of pointer to T inside boost::shared_ptr is NULL. So if I do n...
I have a C++ class(inside a dll project) whose member variables are boost::shared_ptrs to objects of other classes. Is it better to assign them inside the class constructor or have a separate init() function which does that. It is usally better to do everything in the constructor. Having an init() function that is ...
2,347,823
2,347,855
How does delete differentiate between built-in data types and user defined ones?
If I do this: // (1.) int* p = new int; //...do something delete p; // (2.) class sample { public: sample(){} ~sample(){} }; sample* pObj = new sample; //...do something delete pObj; Then how does C++ compiler know that object following delete is built-in data type or a class object? My other question is that if I ne...
The compiler knows the type of the pointed-to object because it knows the type of the pointer: p is an int*, therefore the pointed-to object will be an int. pObj is a sample*, therefore the pointed-to object will be a sample. The compiler does not know if your int* p points to a single int object or to an array (i...
2,347,948
2,347,980
When should I define my own copy ctor and assignment operator
I am reading effective C++ in Item 5, it mentioned two cases in which I must define the copy assignment operator myself. The case is a class which contain const and reference members. I am writing to ask what's the general rule or case in which I must define my own copy constructor and assignment operator? I would als...
You must create your own copy constructor and assignment operator (and usually default constructor too) when: You want your object to be copied or assigned, or put into a standard container such as vector The default copy constructor and assignment operator will not do the Right Thing. Consider the following code: cl...
2,348,045
2,348,070
Resolve C++ virtual functions from base class
Sorry if this is a dupe, I cant find an answer quite right. I want to call a function from a base class member, and have it resolve to the subclass version. I thought declaring it virtual would do it, but it isn't. Here's my approach: class GUIWindow { public: GUIWindow() { SetupCallbacks(); } ...
Never call a virtual function in the constructor.
2,348,363
2,348,372
String array in C++ not working properly?
I'm working on a program for class that takes in a number from 0 to 9999, and spits out the word value (ie 13 would be spit out as "thirteen", etc) And I'm having a pain with the array for some reason. Here is the class so far: #include<iostream> #include<string> using namespace std; class Numbers { private: ...
The error message says it all: only static const integral data members can be initialized within a class You cannot do what you want, you have to separate declaration and initialization, and move the initialization either to the constructor, or use a static const, and put the initialization outside the class. This is...
2,348,371
2,348,436
GUI declarative language implementation
I've recently begun working on a project regarding GUI building using some form of declarative language. What i mean is that i need to describe an hierarchy of objects, without specifying the type of GUI widgets that will be used to "show" that hierarchy. For example, for some existing hierarchy H, using JSON notation ...
JSON would be one choice. XML would be another -- for example, Microsoft uses XAML (an XML dialect) for exactly this purpose and the W3C has a (fairly new) Widget packaging specification (using another dialect of XML). Any of these will let you use existing parsers instead of building yet another from the ground up.
2,348,442
2,348,447
What does "WINAPI" in main function mean?
Could you please explain to me the WINAPI word in the WinMain() function? In the simplest way.. #include <windows.h> int -->WINAPI<-- WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MessageBox(NULL, "Goodbye, cruel world!", "Note", MB_OK); return 0; } Is it just so...
WINAPI is a macro that evaluates to __stdcall, a Microsoft-specific keyword that specifies a calling convention where the callee cleans the stack. The function's caller and callee need to agree on a calling convention to avoid corrupting the stack.
2,348,581
2,349,256
How to know when a wxFrame is closed?
I have a wxDialog where I open a wxFrame. Now I want to know when the wxFrame is closed, so I can do something in the Dialog caller [on the frame I modify a list which is present too in the dialog, and I need to update this (with a function provided by me)]. Any Ideas? I'm using C++ with wxWidgets 2.8-10 Here is the co...
You'll know when the frame is closed by handling the wxCloseEvent. In the handler, do whatever to notify the "Dialog caller" that it should reload (e.g by posting an event). BTW, ShowModal won't return until the dialog is dismissed, and it will return a value (set by EndModal). Then you wouldn't need to mess with the O...
2,348,759
2,349,638
OOP: self-drawing shapes and barking dogs
Most of the books on object-oriented programming I've read used either a Shape class with a Shape.draw() member function or a Dog class with a Dog.talk() member function, or something similar, to demonstrate the concept of polymorphism. Now, this has been a source of confusion for me, which has nothing to do with polym...
My solution would be for the Dog class to be passed an audio device in the bark function. The dog should not store a pointer to the audio device all the time, that's not one of its responsibilities. If you go that route, you end up with the constructor taking two dozen objects, essentially pointing to all the rest of t...