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
3,904,977
3,905,153
Can I write an Extension for External Harddisk
I want to secure my external hard disk by writing sort of ShellExtension. But Shell extension is Workstation Specific. Is there a way I can write an application that will show a authentication or an extension encrypt my drive data so user will get a failure message when double click on my drive.
You can't secure an external harddrive by the use of a shell extension, period. If you want to keep your data safe, there's only one thing you can do: encrypt it. NTFS has built-in encryption, but I wouldn't recommend using that for an external drive, because of the way the encryption keys are handled. There's a nice p...
3,905,235
7,835,439
Unicode File Writing and Reading in C++?
Can anyone Provide a Simple Example to Read and Write in the Unicode File a Unicode Character ?
On linux I use the iconv (link) library which is very standard. An overly simple program is: #include <stdio.h> #include <stdlib.h> #include <iconv.h> #define BUF_SZ 1024 int main( int argc, char* argv[] ) { char bin[BUF_SZ]; char bout[BUF_SZ]; char* inp; char* outp; ssize_t bytes_in; size_t b...
3,905,280
3,909,069
boost::filesystem::path and std::string
I have a String class which has a member std::string. One of the constructor is String (std::string s) { // member: std::string _mString; _mString = s; // error on path assignment } I now have functions that take String as parameter, e.g. Load(String path); but it turns out that boost::filesystem::path::stri...
in your constructor: String (std::string s) should be String (const std::string& s)
3,905,295
3,905,337
FIX communication model - messaging or socket
My situation is: A c++ program needs to talk with a Java program using FIX protocol. My solution: - Messaging: C++ program publishes a text in FIX format which Java progrma can consume and parse with quickfix/j. - Socket: Setup a FIX server in Java program, then C++ program as a client can connect to this socket and...
FIX messaging would be an easier solution, rather than implementing sockets. There are socket communications already embedded in the quickfix libraries. It is no use to reimplement then unless you are doing something very different. The engine is meant to decipher FIX messages. And if you want to modify any of the sock...
3,905,338
3,905,559
Is there any perf hit using DLL functions?
As the title says, compared to a normal function, is there a perf hit in calling dll functions? The dll will be loaded by dlopen. EDIT: Ignore dlsym time because I only do it once per each function.
Calls to DLL functions are indirect by address and the compiler can't inline them, so there is a slight performance hit. You should only worry if you use them in a performance critical inner loop and after profiling them.
3,905,538
3,905,643
Testing for an invalid windows handle: should I compare with 'NULL', '0' or even 'nullptr'?
I'm coming from a background whereby pointers should generally be compared with 'NULL' and integers with '0'. Since I didn't perceive Windows handles to be 'pointers' in the pure sense (being 'handles'), I'd got into the habit of comparing them with 0 rather than 'NULL'. Clearly they're implemented internally as pointe...
Compare it against the documented error return value. That means that you should compare it against INVALID_HANDLE, 0, -1, non-zero, or <=32 (I'm not kidding with the last one, see ShellExecute).
3,905,549
3,905,649
The Important Difference: Overloading vs. Specialization
HI friends , Any one help me The Important Difference: Overloading vs. Specialization in C++ It's important to make sure we have the terms with proof .Thanks in advance The doubt arised "Why Not Specialize Function Templates?"
Check out the article Why Not Specialize Function Templates? by Herb Sutter.
3,905,784
3,905,916
What (not) to do in a constructor
I want to ask you for your best practices regarding constructors in C++. I am not quite sure what I should do in a constructor and what not. Should I only use it for attribute initializations, calling parent constructors etc.? Or might I even put more complex functions into them like reading and parsing configuration d...
Complex logic and constructor do not always mix well, and there are strong proponents against doing heavy work in a constructor (with reasons). The cardinal rule is that the constructor should yield a fully usable object. class Vector { public: Vector(): mSize(10), mData(new int[mSize]) {} private: size_t mSize; ...
3,905,829
3,905,925
Linking Error in Sun Studio 10 under Solaris
I wrote a test program like this: #include <sys/socket.h> int main( void ) { int sock = socket(AF_INET, SOCK_DGRAM, 0); return 0; } And tried to compile it: $ /tool/sunstudio/bin/cc test.c Undefined first referenced symbol in file socket ...
Here's the question. I wrote a test program like this: #include <sys/socket.h> int main( void ) { int sock = socket(AF_INET, SOCK_DGRAM, 0); return 0; } And tried to compile it so (this is the output that really helps, you have to remember that modern compilers really try their best to help you fix any proble...
3,905,869
3,905,921
Isn't return value optimization (RVO) a bug?
I maybe asking a dumb question, but I looked at the wikipedia page for RVO here and could not stop wondering if that behavior is wrong. I tried it in my machine and RVO is fully kicked in despite optimization level. What if there was actually something BIG happenning in a constructor? I know it shouldn't, but what if? ...
The standard mandates that operations with concern a program's observable state must not be optimized away, except for copy construction in certain circumstances. You must not rely on copy constructors to be executed, even if they have side effects you expect to see (e.g., console output).
3,906,098
3,906,130
Operator overloading in c++
struct T { int a; int b; }; class Ptr { public: Ptr(int a, int b) { t_.a = a; t_.b = b; } T* operator->() {return &t_;} T& operator*() {return t_;} private: T t_; }; int main() { Ptr ptr(1, 2); cout << "a = " << ptr->a << " b = " << ptr->b << endl; ...
That's the rule. When overloading operator -> it must return either a pointer or something else that has overloaded operator -> and that operator is applied recursively until a pointer is returned. And the evenutal -> is applied to that pointer. The rule makes sense. Otherwise you'd expect that operator -> take another...
3,906,129
3,906,178
address of elements of structure of different types
i want to find address of elements of structure in memory here is my code #include <iostream> using namespace std; struct B{ int k; float t; char s; unsigned int m; long q; double x; unsigned long z; }; int main(){ B b[]={3,4.23,'A',123,123L,23.340,700}; void *t=&b[0]; void *n=&b[0]+7; while(t...
You cannot increment a void pointer (the last instruction in the while loop), because the compiler cannot know by how much it has to be increased. The address of structure elements can be taken as for normal variables using the & operator: std::cout << "Address of b.k: " << (void*)&b.k << std::endl To get the offset o...
3,906,295
3,916,212
C++ unique_ptr and map
I'm trying to use the C++0x unique_ptr class inside a map like so: // compile with `g++ main.cpp -std=gnu++0x` #include <string.h> #include <map> #include <memory> using namespace std; struct Foo { char *str; Foo(char const *str_): str(strdup(str_)) {} }; int main(void) { typedef std::map<int, u...
I don't believe it's possible to correctly use unique_ptr in a map::insert yet. Here's the GCC bug for it: Bug 44436 - [C++0x] Implement insert(&&) and emplace* in associative and unordered containers It looks like it may be fixed for GCC 4.6, but it won't build from SVN on vanilla Ubuntu 10.04.1 to confirm. Update0 Th...
3,906,384
3,906,468
Why its dangerous to use pass by value when function parameter expects an Abstract class object?
I read below statements in Addison Wesley FAQs. Beware: passing objects by value can be dangerous in some situations. Often it is better to pass objects by reference-to-const than to pass them by value. For example, pass-by-value won't work if the destination type is an abstract base class and can resul...
How it can be erroneous behavior at runtime if destination type is an Abstract class and if the parameter's class has derived class ? It won't even compile. "Pass by value" means that you would try to copy the abstract class parts of the argument to a new object. But you cannot create an object with an abstract class...
3,906,515
3,906,570
cannot convert from 'std::string' to 'LPSTR'
As I clould not pass LPCSTR from one function to another (Data get changed) I tried passing it as a string. But later I need to again convert it back to LPSTR. While trying the conversion I am getting the above error: cannot convert from 'std::string' to 'LPSTR' How can I resolve this?
That's just because you should use std::string::c_str() method. But this involves const_cast in given case because const char * returned by c_str() can not be assigned to a non-constant LPSTR. std::string str = "something"; LPSTR s = const_cast<char *>(str.c_str()); But you must be sure that lifetime of str will be lo...
3,906,529
3,906,552
String Manipulation Methods giving RunTime Error
This seems to be giving me a bit of trouble. This method is supposed to generate a random number and assigns it to a char. getline grabs the entire string from the text file and assigns it to foods. y has the purpose of holding the place of where it finds c in the foods string. It will then use that int to erase from ...
Try: Note that foods.erase(y) will erase the characters from 'f' forward. If you want to erase the characters up to 'f', then see this example: Here's a simple example of how to erase characters: string x = "abcdefghijk"; // find the first occurrence of 'f' in the string int loc = x.find('f'); // erase all th...
3,906,772
3,906,805
Tool for finding non-virtual destructors
Anyone know of a tool that can find non-virtual destructors of polymorphic base classes?
Compiling with g++ -Wall will give a warning about that. Or -Wnon-virtual-dtor if you just want that warning.
3,906,796
3,906,817
How to fold STL container?
I need an analog of Haskell's foldl function to fold any STL containers. Expected signature is like following: template Iterator, FoldingFunction, Result Result foldl( Iterator begin, Iterator end, FoldingFunction f, Result initValue); Standard STL has no such function. Does Boost have any? I know it's pret...
STL does have such a function: std::accumulate. However, it is in the header <numeric>, not <algorithm>. Actually the Wikipedia page on "Fold" already listed the foldl/foldr functions on most programming languages, including C++.
3,906,909
3,907,282
Any way we can work with hex bytes and chars like in c++?
Well my question is simple and straightforward. Is there any way we can use hex values like in c++? I am going to write binary files, but for that i will have to define certain characters like this for example. \x00\x00\x11\x22\x33\x00\x00 I would first need to convert stuff like this to a byte array, and then write it...
No, that's a problem with modern compilers, like VB.NET's. There is no one-to-one mapping between bytes and strings anymore when Unicode became the preferred way of handling text. Codepoints like 0x80 don't have a corresponding character, it is going to get munched when you convert the string to bytes. You'll need to...
3,906,974
3,907,013
How to programmatically create a shortcut using Win32
I need to programmatically create a shortcut using C++. How can I do this using Win32 SDK? What API function can be used for this purpose?
Try Windows Shell Links. This page also contains a C++ example. Descriptive Snippet: Using Shell Links This section contains examples that demonstrate how to create and resolve shortcuts from within a Win32-based application. This section assumes you are familiar with Win32, C++, and OLE COM programming. ED...
3,906,978
3,907,181
operator[]= overload?
Okay, I'm trying to make a quick little class to work as a sort of hash table. If I can get it to work then I should be able to do this: StringHash* hash = new StringHash; hash["test"] = "This is a test"; printf(hash["test"]); And it should print out "This is a test". It looks like I have 2 problems at this poi...
I would firstly question why you are writing your own HashMap when there are some versions available albeit not a standard one. (that was written in 2010, but there is now std::unordered_map) Does your hash-map store const char* pointers or std::strings? (It might store const char * pointers if it is simply a lookup ta...
3,907,147
3,907,237
C++ scanf/printf of array
I've written following code: int main() { double A[2]; printf("Enter coordinates of the point (x,y):\n"); scanf("%d,%d", &A[0], &A[1]); printf("Coordinates of the point: %d, %d", A[0], A[1]); return 0; } It's acting like this: Enter coordinates of the point (x,y): 3,5 Coordinates of the point: 3,...
You are reading double values using the decimal integer format (%d). Try using the double format (%lf) instead... scanf("%lf,%lf", &A[0], &A[1])
3,907,177
3,907,278
Using an object in unrelated class
I have the following situation: In project A, an object (say Obj1 of class A1) instantiates Obj2 of class A2. Then, from Obj1, by many code paths, an object Obj3 (of class A3) can be instantiated. The A3 class is in another project. The stack trace from Obj1's main method to instantiating an object of class A3 is 20 ca...
There's not enough information here to answer. Does A1 have an A2 or A3 member? Does A2 or A3 have an A1 member? What are the arguments to the instantiation of A2 or A3? If A3 wants to call Obj2.test(), then either A3 needs a member of type A2 A3 needs a member of type X that has a member of type A2 -- probably sh...
3,907,293
3,912,681
Using exceptions within a boost::thread thread
I began to play around with boost::threads, but I'm kind of stuck with this problem: I don't understand why this program crashes as soon as the exception is thrown, because I try to catch it within the thread. I thought that it would be possible to work with exceptions as long as the handling happens in the same thr...
I found the problem: it's a bug in the boost library that only occurs when working with a minGW Version newer than 3.17. Boost trac ticket #4258 After applying the suggested workaround, and setting the Preprocessor Definition BOOST_THREAD_USE_LIB I am now able to link against the static library, and I can work with exc...
3,907,309
3,907,479
TCP connection failure
I’m having trouble with a simple TCP socket with the connect() and read() function. This program works if I start the server first, and the client second. However, when I start the client first, it continues to try to connect to the server, then when I start the server, it connects but the subsequent read returns 0 byt...
A return of 0 read bytes from a socket is perfectly legal. This only means you have to wait and try again. For instance look at this read_data() function. It checks if number of read bytes are > 0, then it stores them. It checks if number of read bytes are < 0, then it is an error. The 0 case is not really a great suc...
3,907,356
3,976,859
Eclipse CDT Source->Implement Method generates code not following defined code style
I am using Source->Implement Method sometimes, but I noticed that the generated code does not follow the defined code style from the preferences (the style is applied when I use Source->Format correctly) - Is there some setting I missed or is that a bug? Using Eclipse Version 3.5.2 and CDT 6.0.2 on Ubuntu Linux 10.04 L...
I just tried, and I do not encounter this issue (I am using Eclipse 3.3, 3.4 and 3.6). I don't know if you are aware of this Eclipse feature, but in Preferences > Java > Editor > Save actions, you can define the list of actions that are automatically run when you save the Java class you are currently editing. The inter...
3,907,607
3,907,644
std::list fixed size
How can I create std::list with a fixed element count?
#include <list> // list with 5 elements, using default constructor const size_t fixedListSize(5); std::list<int> mylist(fixedListSize); If you want it to always have exactly 5 elements you'd have to wrap it in a facade class to prevent insertion and erasure. If that is indeed what you want, you'd be better off usin...
3,907,735
3,907,805
how to remove some data from pe (exe) file in C
in first exe i have defined array of char with some special bytes as label, i mapping it to memory from another exe, finding needed label and putting in it new data, but this data could be shorter then defined array, so i want to cut this array to needed size! how can i do it?
There is no fine and simple way to cut out pieces of PE file. Obvious solution is to additionally define a length field in the original (in your terms first) exe and mark it with another label. Then additional work of second exe would be to write to this field actual data length. EDIT: If cutting is your primary goal ...
3,907,778
3,907,802
Open WPF application in Windows in c++ application
I have a situation where I need to start a WPF application and have it run using a child window created by my C++ application. So the sequence of events would be - Start C++ application C++ application creates a window that it wants WPF app to run in. Launch WPF using CreateProcess function. Included in create proce...
You should setup the WPF program as a library, not an application. You could then provide it's user interface with direct access to your "child window", which it could host directly or via HwndHost. Trying to launch a separate process, and share a window via a HWND cross process is going to be very problematic.
3,907,818
3,907,850
OpenGL headers for OS X & Linux
I'd like to have both the includes for OS X as well as linux in my opengl program (C++) how can I set my program to use one if the other is not available? Here's what i'm currently doing: if(!FileExists(OpenGL/gl.h)) #include <GL/glut.h> //linux lib else { #include <OpenGL/gl.h> //OS x libs #include <OpenG...
Here is what I use: #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/glut.h> #else #ifdef _WIN32 #include <windows.h> #endif #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #endif All compilers for the mac (well,I guess that's gcc, and maybe clang) should define __APPLE__. I...
3,908,140
3,908,833
Google's Protocol Buffers in c#
We are looking at using Google's Protocol Buffers to handle serialization between a c++ application and a c# application via networking. My question is, I've found a couple of different verisions for c#. Both look pretty good, however, does anyone know what is different (if anything) between the two protobuf-net jske...
Sure; dotnet-protobufs is a port of the java version, so shares a very similar API and approach to the core google implementation; code-gem, immutability, etc. Protobuf-net is byte compatible, but is a complete from-scratch re-implementation, following standard .NET idioms - so is familiar to users of XmlSerializer etc...
3,908,562
3,908,651
How to specify INFINITY (U+221E) in C++ using an escape sequence?
How can I specify the Unicode character INFINITY (U+221E) in C++ without directly pasting the symbol (∞) into my code file? I've tried \x221e but that results in a warning, and \u221e gives me a LATIN SMALL LETTER A WITH CIRCUMFLEX (U+00E2). QString label; label.append(tr("HP: \u221e\n\n"));
Try \xE2\x88\x9E. But to make Qt use UTF-8, it seems you'll need QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); Somewhere before it.
3,908,603
3,908,637
Read the current battery charge/discharge rate on a laptop
I've wrote a small piece of code that reads the current battery charge/discharge on my laptop. I followed the example code on this MSDN page. My program updates the information every 100ms (by calling the DeviceIoControl function with IOCTL_BATTERY_QUERY_STATUS as control code) but the read value changes only after 5-1...
Depending on the accuracy of the sensor, it is likely that the status is only updated by the power device driver every 5-10 seconds or when significant changes take place.
3,908,771
3,908,791
Sorting an array, from high to low
I have an array containing multiple integers, is there a common way for sorting it from high to low?
#include <algorithm> #include <functional> int arr[ 5 ] = { 4, 1, 3, 2, 5 }; std::sort( arr, arr + 5, std::greater< int >() );
3,908,835
3,909,777
Which winapi function will allow me to change logged in user's password?
I'm looking for a winapi function that will allow me to change current logged in user's password. In my case, I know current password of logged in user. I use Windows 7 Ultimate. Thanks. Background The background will look weird, but I'm going to describe it for clarification. My personal home PC is used by several use...
You're looking for NetUserChangePassword(). Check this MSDN link for sample code: http://support.microsoft.com/kb/151546
3,908,851
3,910,281
How to throw EXCEPTION_FLT_UNDERFLOW?
I need a sample code, that throws EXCEPTION_FLT_UNDERFLOW. I already have code to handle that exception. Now I need sample, that throws it. Any advises?
Assuming you want actual code that will trigger this: #include <float.h> int main() { _controlfp_s(NULL, 0, _MCW_EM); // enable all floating point exceptions float f= 1.0f; while (f) { f/=2.0f; // __asm fwait; // optional, if you want to trap the underflow sooner } return 0; ...
3,908,881
5,097,281
Designing live video stream for wxWidgets
In my application we will present the video stream from a traffic camera to a client viewer. (And eventually several client viewers.) The client should have the ability to watch the live video or rewind the video and watch earlier footage including video that occurred prior to connecting with the video stream. We in...
You should check out this C++ RTMP Server: http://www.rtmpd.com/. I quickly downloaded, compiled and successfully tested it without any real problems (on Ubuntu Maverick). The documentation is pretty good if a little all over the place. I suspect that once you have a streaming media server capable of supporting the typ...
3,909,210
3,909,231
Segfault immediately after pthread creation
I have a producer/consumer concurrency problem that I'm working on. The problem is that I'm getting a segfault thrown immediately after trying to create my first thread. Relevant code: customer is a struct declared as: struct pr2_customer { pthread_t customer_id; }; typedef struct pr2_customer customer; customer...
What appears to me is that you haven't reserved any space in customers. I think this is what you need: vector<customer> customers(ncustomers);
3,909,272
3,909,326
Sorting two corresponding arrays
I have this code here that has two arrays. It sorts arr[], so that the highest value will be in index 0. Now the second array arr1[] contains strings, I'd like the code to apply whatever changes where made to arr[] to arr1[]. So that arr[0] would return 6, while arr1[0] would return the string "d1". Notice how "d1" wa...
Rather than sort the arrays, sort the indices. I.e., you have int arr[5]={4,1,3,6,2} string arr1[5]={"a1","b1","c1","d1","e1"}; and you make int indices[5]={0,1,2,3,4}; now you make a sort indices comparator that looks like this (just and idea, you'll probably have to fix it a little) class sort_indices { privat...
3,909,309
3,909,324
Boost::Scoped_Ptr breaks code
Examine the following code: This works: T *p = (std::find( this->first(), this->last(), *pPos )); if( p != last() ) { this->push_back(data); T *right = (this->last() - 1); T *left = (this->last() - 2); while( *pPos != data ) std::iter_swap( left--, right-- ); return const_cast<T*>(pPos)...
boost::scoped_ptr will delete the pointer when it (i.e. boost::scoped_ptr instance) goes out of scope. I don't think you want to delete the pointer, which appears to be an iterator in your class.
3,909,386
3,909,437
Using unmanaged library
So in visual studio i have my solution with two projects, first one is managed c++ code and second one is unmanaged c++ library (waffles). I want to use classes from library in my managed code. If i simply add 'include "GMacros.h"', then i get 'cannot compile with /clr' error. Tried to wrap include in #pragma unmanaged...
Unmanaged code can't be called directly in managed .NET. You need to add __declspec(dllexport) to your functions' declarations that should be visible outside the unmanaged library: public: void __declspec(dllexport) MyUnmanagedMethod(); And then in your managed code write a simple wrapper like this: public ref cla...
3,909,406
3,909,588
Color(int, int, int) vs Color(float, float, float) ambiguous call
How can I resolve the ambiguous call between these two in C++? Color(int, int, int) Color(float, float, float) It is both ambiguous when the values are hardcoded i.e. Color(1, 2, 3) and when they are variables Color(r, g, b). Why wouldn't the compiler resolve according to data type? In variable form? EDIT: Sorry, too ...
The problem seems to be that you have declared Color(unsigned, unsigned, unsigned); Color(float, float, float); ie, all three args must be either float or unsigned. If you try to call it with other types (such as int or double), its ambiguous -- the compiler doesn't know which you want as both are just a good (or as ...
3,909,711
3,909,770
C++ vector of pointers problem
I'm currently trying to implement the A* pathfinding algorithm using C++. I'm having some problems with pointers... I usually find a way to avoid using them but now I guess I have to use them. So let's say I have a "node" class(not related to A*) implemented like this: class Node { public: int x; Node *parent; ...
So, the first issue that you have here is that you are using the address of individual Nodes of one of your vectors. But, over time, as you add more Node objects to your vector, those pointers may become invalid, because the vector may move the Nodes. (The vector starts out at a certain pre-allocated size, and when yo...
3,909,713
3,932,061
Xlib: XGetWindowAttributes always returns 1x1?
I'd like to have width and height of the currently focussed window. The selection of the window works like a charm whereas the height and width are always returning 1. #include <X11/Xlib.h> #include <stdio.h> int main(int argc, char *argv[]) { Display *display; Window focus; XWindowAttributes attr; int...
You're right - you're seeing a child window. GTK applications, in particular, create a child window under the "real" window, which is always 1x1, and that always gets the focus when the application has the focus. If you're just running your program using the GNOME terminal, you'll always be seeing a GTK application wit...
3,909,720
3,909,825
C++0x: conditional operator, xvalues, and decltype
I am reposting a comp.std.c++ Usenet discussion here because that group has become very unreliable. The last few posts I've submitted there have gone into the void, and activity has all but ceased. I doubt I've been banned and/or everyone else just lost interest. Hopefully all interested people will find this discussio...
I think GCC 4.5.1 is nonconforming wrt §5.16/4. Have you filed a bug report? Anyway, I think it is conforming with that ternary operator code. decltype is defined by §7.1.6.2/4: The type denoted by decltype(e) is defined as follows: if e is an unparenthesized id-expression or a class member access (5.2.5), declty...
3,909,784
3,909,788
How do I find a particular value in an array and return its index?
Pseudo Code: int arr[ 5 ] = { 4, 1, 3, 2, 6 }, x; x = find(3).arr ; x would then return 2.
The syntax you have there for your function doesn't make sense (why would the return value have a member called arr?). To find the index, use std::distance and std::find from the <algorithm> header. int x = std::distance(arr, std::find(arr, arr + 5, 3)); Or you can make it into a more generic function: template <typen...
3,909,970
3,910,095
C++ std::getline size limit on Mac OSX
I'm having problems with std::getline on Mac OSX Snow Leopard. For some reason it limit the size of the input, while on Debian/Ubuntu it's unlimited size? std::getline(std::cin, input) Any clues about the limit?
The C++ standard says this about the getline function: 21.3.7.9 Inserters and extractors [lib.string.io] template<class charT, class traits, class Allocator> basic_istream<charT,traits>& getline(basic_istream<charT,traits>& is, basic_string<charT,traits,Allocator>& str, charT delim); Eff...
3,910,083
3,910,420
Deleting virtual functions in C++0x
It isn't clear what happens if I delete a virtual method in C++0x: virtual int derive_func() = delete; Does this mean this class and everything that inherits from it can not define/implement the derive_func() method? Or is this illegal/compile error?
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2326.html#delete A deleted virtual function may not override a non-deleted virtual function and vice-versa. meaning its pretty useless (as i read it at least) the only valid use would be: struct A{ virtual void b() = delete; }; struct B:A{ virtual void...
3,910,092
3,910,157
Single-select Win32 ListView (Common Controls)
I'm using the ListView control from Common Controls 6.0 in C++ and I need the ListView to be single-select only. All of the higher level controls have this feature (e.g. .Net and Qt), but I imagine they are based on this control deep down somewhere. Any ideas on how I can get this to behave as a single-select list? Ju...
You want the flag LVS_SINGLESEL This flag must be used in window creation, changing it after creation will fail - can't toggle between single and multi select without creating 2 separate controls.
3,910,105
3,910,490
Bulk download of web pages using Qt
I want to write a program using Qt that downloads a lot of HTML web pages, about 5000, from one site every day. After downloading that pages I need to extract some data using DOM Query, using the WebKit module, and then store that data in a database. Which is the best/correct/efficient way to do that, in particular the...
To download the pages it makes sense to use a dedicated library like libcurl
3,910,120
3,942,338
Playing with OpenGL and input from separate threads
I'm using GLFW for creating OpenGL context and capturing user's input and I wanted to capture whole input actions from other thread than OpenGL context was initially created. Am I able to achieve this by using GLFW, SDL or similar library or need I, for example, use different libraray for each task? And if so, which li...
GLFW has good input API and you don't really need to process input in separate thread. If your framerate is high enough, checking input once per frame should be enough (if your frames are taking seconds to render, that may be not the case).
3,910,253
3,910,433
(c/c++) trying to force EOF from parent process sending input to child process
i have a very simple c/c++ program that forks a child process to execute another program, and then sends some data to that child program, and waits for the response. the child program reads from stdin and waits for EOF before it continues. my problem is, the child program receives the initial input from the pipe writin...
The most common reason for this is that you aren't closing the write end of the pipe, so the EOF never gets sent. The common example is when you have code that looks like: int fds[2]; pipe(fds); // open a pipe if (fork()) { // parent process write(fds[1], ... // write data close(fds[1]); // close it } el...
3,910,296
3,910,323
mingw. how to use static and dynamic linking both
lets make the simpliest application: result: ok. it works. lets add some SDL with default dynamic linking here! result: works great. at stdout.txt we can see "puchuu" lets change our makefile a little. just group 2 object files to the static lib: result: Who is to blame? Me or mingw developers? is it clear ...
mingw is not to blame. With the (GNU) linker, static libraries have to be listed in the reverse dependency order. g++ -o program.exe libpuchuu.a -lSDL will not work if something in libpuchuu.a depends on something in libSDL. It should be g++ -o program.exe -lSDL libpuchuu.a If you have a cyclic dependency, you even h...
3,910,326
3,910,610
C++ Read file line by line then split each line using the delimiter
I want to read a txt file line by line and after reading each line, I want to split the line according to the tab "\t" and add each part to an element in a struct. my struct is 1*char and 2*int struct myStruct { char chr; int v1; int v2; } where chr can contain more than one character. A line should be som...
Try: Note: if chr can contain more than 1 character then use a string to represent it. std::ifstream file("plop"); std::string line; while(std::getline(file, line)) { std::stringstream linestream(line); std::string data; int val1; int val2; // If you hav...
3,910,356
3,910,442
ILMerge using 2 third party dll's C++
I have written a program that utilizes 2 3rd party dll's and I want to use ILMerge to merge both dll's into 1 executable. I have tried using the command line: ilmerge /target:winexe /out:final.exe normal.exe 3rd_party_dll_1.dll 3rd_party_dll_2.dll but this returns this error: `Could not load assembly from the lo...
ILMerge doesn't work on native dlls out of the box, but there is a workaround.
3,910,375
3,910,406
Placement new and non-default constructors
Can I call the C++ placement new on constructors with parameters? I am implementing a custom allocator and want to avoid having to move functionality from non-default constructors into an init function. class CFoo { public: int foo; CFoo() { foo = 0; } CFoo(int myFoo) { foo = my...
To use placement new, you need to include the header <new>: #include <new> Otherwise the placement forms of operator new aren't defined.
3,910,608
3,957,310
How to access the ancestor vertex during a breadth-first search with the Boost Graph Library?
I'm trying to write my own version of connected components discovery using the breadth-first search algorithm included in the Boost Graph Library and I need to access the ancestor (the vertex which leads to the discovery of the current vertex) vertex from withing the discover_vertex callback of my visitor to set the c...
Create an examine_vertex callback that records the vertex being examined (popped from the queue). This vertex will be the ancestor of whatever vertex is being discovered. From the pseudo code in BGL's BFS documentation: vis.examine_vertex(u, g) is invoked in each vertex as it is removed from the queue. BFS(G, s) ...
3,910,615
3,910,624
C++ detect space in text file
How can I go about detecting a space OR another specific character/symbol in one line of a file using the fstream library? For example, the text file would look like this: Dog Rover Cat Whiskers Pig Snort I need the first word to go into one variable, and the second word to go into another separate variable. This shou...
This is pretty simple. string a; string b; ifstream fin("bob.txt"); fin >> a; fin >> b; If that's not quite what you want, please elaborate your question. Perhaps a better way overall is to use a vector of strings... vector<string> v; string tmp; ifstream fin("bob.txt"); while(fin >> tmp) v.push_back(tmp); This wi...
3,911,008
3,911,063
Collate Hash Function
In the local object there is a collate facet. The collate facet has a hash method that returns a long. http://www.cplusplus.com/reference/std/locale/collate/hash/ Two questions: Does anybody know what hashing method is used. I need a 32bit value. If my long is longer than 32 bits, does anybody know about techniques fo...
No, nobody really knows -- it can vary from one implementation to another. The primary requirements are (N3092, §20.8.15): For all object types Key for which there exists a specialization hash, the instantiation hash shall: satisfy the Hash requirements (20.2.4), with Key as the function call argument type, the Defaul...
3,911,098
3,911,107
Object Oriented way to iterate through a std::vector?
I have a class which has a std::vector of child control pointer. For obvious reasons, I do not want the user of the class to have direct access to the std::vector. All I would want is a way to give the caller the pointers. What would be a good OO way to do this? (this function will be called often) Thanks
Provide a function that returns a const_iterator to the vector. It is also useful to add one to return the iterator to the end of the vector. class MyClass { public: typedef vector<T>::const_iterator c_iter; c_iter getBegin() const {return v.begin();} c_iter getEnd() const {return v.end();} // and perhaps if ...
3,911,147
3,911,175
What are the good alternatives for communication between local C++ and Java programs?
By "local" I mean both run in the same subnet, in most cases the same host/VM, therefore some standard cross-network cross-platform RPC mechanisms like SOAP, XML-RPC, CORBA, etc. seem unnecessary. The payload is mainly numerical (mostly tabulated) data with some small amount of meta data (for example available data ser...
Options 3 and 4 are used in real-world heavy-duty situations. Options 1,2,6 do not reach another host. Option 5 is probably too troublesome for the non-Java side. I'd go with Option 4, because Option 3 is too low-level (unless Option 4 turns out to be too slow). Choose your favourite cross-platform light-weight messagi...
3,911,170
3,911,187
C++ remove trailing new line from text file
Is there a way in C++ to remove/trim a trailing new line from a text file? For example content content content content content content <- this line in the text file is empty and needs to go ->
Sure! One way to do it would be to read the file to a std::string #include <fstream> #include <string> // Add this code inside your main() function std::ifstream ifs("filename.txt"); std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); and then use any of the techniques de...
3,911,226
3,911,288
Redeclaration of enumerator
I got an error: redeclaration of enumerator message when I compile my codes, please kindly see the code below from my foo.h header file, //foo.h struct FG { enum { black = 1, red = 2, green = 3 }; }; struct BG { enum { black = 1, red = 2, green = 3 }; }; My q...
As noted in the comments, if you are using a C compiler instead of a C++ compiler to compile the code, then you will inevitably get the errors shown. The code is only valid in C++, so you must use a C++ compiler to compile it. Further, if you are using a C compiler, you would not be able to use the qualified names lik...
3,911,342
3,911,357
Different char type in windows programming
Recently, I meet some tasks about the char/string on windows platform. I see that they are different char type like char, TCHAR, WCHAR, LPSTR, LPWSTR, LPCTSTR. Can someone give me some information about it? And how to use like the regular char and char *. I cam confused about these types? Best Regards,
They are documented on MSDN. Here's a few: TCHAR: A WCHAR if UNICODE is defined, a CHAR otherwise. WCHAR: A 16-bit Unicode character. CHAR: An 8-bit Windows (ANSI) character. LPTSTR: An LPWSTR if UNICODE is defined, an LPSTR otherwise. LPSTR: A pointer to a null-terminated string of 8-bit Windows (ANSI) characters. L...
3,911,547
3,911,599
Dynamic allocation with scanf()
My question is exactly the same as this one. That is, I'm trying to use scanf() to receive a string of indeterminate length, and I want scanf() to dynamically allocate memory for it. However, in my situation, I am using VS2010. As far as I can see, MS's scanf() doesn't have an a or m modifier for when scanning for stri...
If you want to use scanf you could just allocate a large enough buffer to hold any possible value, say 1024 bytes, then use a maximum field width specifier of 1024. The m and a are specific non-standard GNU extensions, so thats why Microsofts compiler does not support them. One could wish that visual studio did. Here i...
3,911,578
3,911,792
How to call C++ functions in my assembly code
I need to call PrintResult from my assembly to display the result. I know I have to use extrn _PrintResult somewhere, and I should call the function using call _PrintResult but I'm not sure quite sure how to use it. any suggestions public _Square .386 .model flat .code _Square proc mov eax, [esp+4] imul eax ret ...
I usually don't like to post full code for things, but give this a try: 32-bit Assembly .386 .model flat .code _Square proc mov eax, [esp+4] imul eax push eax ; Save the calculated result ; Call PrintResult here push eax ; value push 0 ; ShowSquare call _PrintResult add esp, 8 ; Clear the stack pop eax ; Return the...
3,911,620
3,913,941
Interprocess communication: one server and multiple clients
I have one "server" process running, which will fetch data over the network for other processes running on the same machine as the server process. How should I transfer data from the local server process and the local clients?
For retrieval of network data by the server process, Boost.Asio as suggested by @radman is a good choice. Between server and local clients, Boost.Interprocess would be more efficient as this is interprocess data transfer, not requiring network usage. Each of these Boost libraries provides a ready-to-run wrapper aroun...
3,911,689
3,911,942
Why is memcpy not functioning properly?
I have a class for an RDT Header that holds information for an implementation of several reliable data transfer protocols. I need to attach that information (a total of 12 bytes) to my send buffer to transfer it over the socket. I am trying to use memcpy to do this but for some reason it just leaves junk inside the buf...
This may be too obvious, but exactly how are you inspecting the buffer? Have you tried printf( "%s\n", send_buf + sizeof(RdtHeader) ); ? If you instead are doing ... printf( "%s\n", send_buf ); ... then you should expect to see just garbage (with correct operation) since the win field acts as zero-terminator for the ...
3,911,701
3,911,708
Returning a pointer from a member function in C++
Hello I have a class with a function that returns a pointer: int* Maze::GetStart() { int startNode = 1; return &startNode; } Will the value of startNode be erased after the function returns the pointer? If I did this instead would the value be saved? int Maze::GetStart() { int startNode = 1; return s...
Will the value of startNode be erased after the function returns the pointer? The variable startNode will cease to exist once the function GetStart() returns, so in that sense, yes. But, your code opens up a huge opportunity for undefined behavior by returning addresses to things that will disappear once GetStart...
3,911,814
3,911,873
C++ in G++ - Segmentation Fault when not using pointers
I'm trying to use G++ to compile some C++ code. It seems to work fine in other compilers, but for whatever reason, G++ won't produce working output. Disclosure: This is part of a homework assignment, but I feel like it's more of a compiler issue, since it works in other compilers. Here's the snippet that's wreaking hav...
Here's a general hint that will make your life a million times easier. Compile this program with the "-g" and "-Wall" flags: gcc -g -Wall foo.cpp The "-g" adds debugging information. The "-Wall" spits out additional warnings when compiling. Then use the debugger: gdb ./a.out Hit run to start your program. Use bt t...
3,912,026
4,736,325
Networking for Xna (C#) and C++?
Me and some friends were thinking about making an online game with XNA game studio. Our games mainly used Winsock for the networking portion, but our most recent project used RakNet where the server was in C++ and the Client used a small RakNet wrapper I wrote. As far as I know XNA can't really use DLLs, so I was wonde...
There is nothing wrong with writing a server in C#. The open source MMORPG software that simulates a Ultima Online server, RunUO, runs in C# with good results. Yes, Winsock and C# Sockets are compatible.
3,912,092
3,912,593
Is there any way to speed up frequent file write operations? CFile
My task is to write small parts of data to file frequently and guaranteed. It's a some type of logging system, that must provide a guaranteed safety and speed of saving data to disk. I found that brakes appear in the Flush() function that is called too often. So, I decided to get rid of it. I used flags, that prohibit ...
flush() takes so long, precisely because it establishes the guarantee you're looking for. Files are usually written to disk, which (probably) are spinning rusty disks. Files are physically scattered over the surface of these disks, and it takes milliseconds to move the read/write head to the right place. 50 flushes per...
3,912,103
4,008,244
How can completely port a qt3 library to qt4?
I have been stumbling through some different steps to do this. I ran the qt3to4.exe on the files with compile errors and got though a lot of conversion steps, however now I am getting this error: 1>c:\qt\4.7.0\src\qt3support\widgets\q3toolbar.h(64) : error C2039: 'ToolBarDock' : is not a member of 'Qt' and 55 other s...
Actually qt34qt4 doesn't do all things right. There are many methods, enums etc, which are not converted. It is more or less simple find-replace tool which replace following instructions from qt\tools\porting\q3porting.xml In many cases there is a replacement definition for a class, but not for a method of this class....
3,912,117
3,912,154
Get a process Owner Name in mfc
I want to get the user name who has launched the given application. For Example if Outlook or IE is launched I need to get the Name of the user who has launched it. This should be generic across all Windows OS . But the solution given below is failing in Windows 2003 user ,in both ADMIN and Standard User.
I found this page which gives a function to recover a process owner's name. Here is the code (not my code and I couldn't test it): bool ExtractProcessOwner( HANDLE hProcess_i, CString& csOwner_o ) { // Get process token HANDLE hProcessToken = NULL; if ( !::OpenProcessToken( hProcess_i...
3,912,137
3,912,328
Where should default parameters be specified?
At my workplace, usually default parameters are specified in the declaration.What is the normal custom? Should I specify default parameters in method declaration or method definition? EDIT: Is there any way to specify default parameters for references? EDIT: Can someone please provide an example of default arguments f...
ybungalobill has already answered the question about where. Regarding references, for a reference to const T you can just specify a default value directly. For a reference to non-const you need to specify the default "value" as a reference to non-const. This might be a global, or an instance of a class with suitable co...
3,912,170
3,912,181
Call a C++ function from a C source code
Is it possible to call a C++ function from a C source code? Please advice. Many thanks.
You will want to look into the extern C construct. From the link: // This is C++ code // Declare f(int,char,float) using extern "C": extern "C" void f(int i, char c, float x); ... // Define f(int,char,float) in some C++ module: void f(int i, char c, float x) { ... } You can also declare/define multiple f...
3,912,298
3,912,481
Writing a library with C and C++ interfaces, which way to wrap?
When preparing a library (let's call it libfoo), I find myself presented with the following dilemma: do I write it as a C++ library with a C wrapper: namespace Foo { class Bar { ... }; } /* Separate C header. #ifdef __cplusplus omitted for brevity. */ extern "C" { typedef void *FooBar; FooBar* foo_bar_new(...
Small points: When you write C library it is useful anywhere - in C, in C++ (with wrapper) and many other languages like Python, Java using bindings etc and most important it requires only C runtime. When you write C++ wrapper you also need to write a C wrapper, but it is not as simple as you think, for example: c_api....
3,912,359
3,912,403
C++ Linker error iostream overloading
i get 2 linker errors when trying to compile my program which includes these two files (causing the problem, in particular the lines in bold) and i'm new to C++ so excuse my ignorance. Assignment1.obj : error LNK2001: unresolved external symbol "public: class Vector __thiscall Vector::operator^(class Vector)" (??TVecto...
Its hard from the information given to see the problem; you have C++ code in a .c file, but presumably your compiler would complain if you hadn't got it to recognize that. To avoid doubt, rename your point.c file point.cpp. Generally, its a good idea to use forward declarations of things you want to be friends; this e...
3,912,417
3,912,525
Is there a way to abort an SQLite call?
I'm using SQLite3 in a Windows application. I have the source code (so-called SQLite amalgamation). Sometimes I have to execute heavy queries. That is, I call sqlite3_step on a prepared statement, and it takes a lot of time to complete (due to the heavy I/O load). I wonder if there's a possibility to abort such a call....
I don't understand why you want the interruption to come from the same thread and I even don't understand how that would be possible: if the current thread is blocked, waiting for some IO, you can't execute any other code. (Yeah, that's what "blocked" means) Perhaps if you give us more hints about why you want this, we...
3,912,672
3,913,035
Functional Code Breaks When Used Twice
I'm still working on my Field class, and tried to improve my piss-poor insertion/erase performance. However, the new function works once, then breaks catastrophically when I use it a second time. This is the code: template <class T> T *Field<T>::insert(const T *pPos, const T& data) { // Special case: field is emp...
// ... if( p != last() ) { this->push_back(data); After this line pPos may not be a valid pointer anymore. The console then proceeds to never shutdown again until I close VSC++08 itself. Tried clicking the Stop button in the debugger?
3,912,699
3,912,734
Why swap with xor works fine in c++ but in java doesn't ? some puzzle
Possible Duplicate: Why is this statement not working in java x ^= y ^= x ^= y; Sample code int a=3; int b=4; a^=(b^=(a^=b)); In c++ it swaps variables, but in java we get a=0, b=4 why?
By writing your swap all in one statement, you are relying on side effects of the inner a^=b expression relative to the outer a^=(...) expression. Your Java and C++ compilers are doing things differently. In order to do the xor swap properly, you have to use at least two statements: a ^= b; a ^= (b ^= a); However, th...
3,912,828
3,912,902
Logical error in Function template
My professor has given me this assignment. Implement a generic function called Max, which takes 3 arguments of generic type and returns maximum out of these 3. Implement a specialized function for char* types. Here's my code : #include <iostream> #include <string> using namespace std; template<typename T> T ...
There are two problems here. The other two answers have already described the problem with your third call. But your second call is also wrong: char a = 'A'; char b = 'B'; char c = 'C'; char Cptr = *Max(&a, &b, &c); This should produce undefined behaviour since strcmp expects zero-terminated strings but this isn’t wha...
3,912,970
3,913,108
libxml2 XPATH - Selecting subset of data from XML
I am fairly new to XML dev.. I had a few questions regarding XML parsing with XPATH and libxml. I have an XML structured as : <resultset> <result count=1> <row> <name> He-Man! </name> <home> Greyskull </home> <row> </result> <result count=2> ...
Try this XPath - /resultset/result[@count=2]/row/name This will give a list of all nodes falling under this XPath. From this just take the first element (as you needed only the first record).
3,912,971
3,940,442
UDP socket starting to fail to receive
I have a very annoying bug showing up. We have left our iPhone app running overnight. Every 2 seconds it sends a broadcast ping out on to the network via the open socket to inform that the device is alive. Now the other application detects that ping and attempts to send messages back. The problem is that despite th...
Well this turned out to be a very strange problem. I broke out a packet sniffer to inspect what was going on and I found that my PC was sending out ARP broadcasts trying to identify who had the ip address. These ARP requests were not getting answered by the router or the iPhone. This was very strange. In the end I sta...
3,913,009
3,913,057
Is there any alternative for printf?
I have to create a software that must work on several *nix platforms (Linux, AIX, ...). I need to handle internationalization and my translation strings are in the following form: "Hi %1, you are %2." // English "Vous êtes %2, bonjour %1 !" // French Here %1 stand for the name, and %2 for another word. I may change th...
POSIX printf() supports positional arguments. printf("Hi %1$s, you are %2$s.", name, status); printf("Vous êtes %2$s, bonjour %1$s !", name, status);
3,913,015
3,913,149
Is this a good concept for sending serialized objects over Network?
I have a client and a server I want to send objects from client to server The objects must be send bundled together in a "big packet" containing many objects The objects could be in a random order The number of objects is not fixed There could be objects in the packet which are unknown to the server (so he needs to du...
The approach you describe is a start, but have you thought about how you'd serialise references between objects. I.e. serialising an object graph. Also, if you may need to think about data format versioning if your client and server can change out of sync with each other. Its not necessarily a simple problem. Are the...
3,913,051
3,913,190
class implementation of operator delete() not being invoked
I have the following code #include <iostream> #include <cstddef> #include <string> #include <memory> class Object { public: Object() { std::cout << __PRETTY_FUNCTION__ << std::endl; } std::string x; void *operator new( size_t bytes ) { std::cou...
You're crashing well before delete() is called, because you haven't allocated any storage for std::string x; - if you comment out this instance variable then the code should compile (with warnings) and run OK.
3,913,503
3,913,555
Metaprogram for bit counting
I need bit counter utility in C++ that is capable of counting number of the most significant bit in a numeric constant value and present this number as compile-time constant. Just to make everything clear - number of the most significant bit for a set of numeric values: 255 => 8 (11111111b) 7 => 3 (111b) 1024 =...
Edit: I totally misread what you wanted. Here's what you want: The number of significant bits in 0 is 0. The number of significant bits in x is the number of significant bits in x/2 plus one. So you get: template <unsigned int x> struct SignificantBits { static const unsigned int n = SignificantBits<x/2>::n + 1; };...
3,913,525
3,913,628
Is there a legal way to define type with zero-size in C++? <eom>
Possible Duplicate: Can sizeof return 0 (zero) Is there a legal way to define type with zero-size in C++?
C++ Standard. 1.8.5. Unless it is a bit-field (9.6), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class sub-objects may have zero size. An object of POD type (3.9) shall occupy contiguous bytes of storage. 9.6.2. A declaration for a bit-field that omits the identi...
3,913,558
4,650,929
How Protocol buffer interact with legacy protocol code
every one, I have a question about how protocol buffer interact with existed protocol mechanism,Say code below: class PacketBase { public: PacketBase(); private: int msgType; int msgLen; private: MessageBuilder* m_pMsgBuilder; /// do Write and Read From msg stream }; class LoginRequest : public PacketBa...
Well, since your msgType and msgLen fields are both private, I think your question boils down to "Can I replace LoginRequest with a protocol buffer that has a no-args constructor?" and the answer here is an unqualified "yes". Protocol buffers take care of (de-)serializing fields while maintaining type information; the...
3,913,577
3,923,049
fatal error LNK1127: library is corrupt --> after adding extern "C" to function prototype
I have an external library made using C code. I wish to call a function from the library in my c++ project. The original format of the function prototype was. extern void butterThreeBp(real_T eml_dt, real_T eml_fl, real_T eml_fu, real_T eml_b3[7], real_T eml_a3[7]); And this caused the following linker error in MSVC20...
You do not have to use the included LCC compiler with MATLAB. The simplest solution is to get MATLAB to use VC++. http://www.mathworks.com/support/compilers/R2010b/index.html
3,913,617
3,913,715
Design problem with Shared object loader
I have been developing this class for loading plugins in the form of shared objects for an application. I currently have thought of 2 ways of loading the file names of all the plugins to be loaded by the app. I have written an interface for loading file names. I have a few questions about how to improve this design. Pl...
You created a fine interface, but then you don't use it. And you then store the file names in a private member l_FileNames. I would change the PluginLoader constructor to accept a FileNameLoader reference and use that reference to load file names. This way you won't need the LoadingMethod in the PluginLoader class. Wr...
3,913,726
3,913,752
Why base classes can have a zero size?
Basically it is a follow up of this question.. When I look into the Standard docs I found this.. In Classes 9.3, Complete objects and member subobjects of class type shall have nonzero size.96) ... Yeah, true.. But, 96)Base class subobjects are not so constrained. So, when I looked into Stroustrup's FAQ, there is a...
Base classes cannot have zero size. Only base class subobjects can. Meaning the base part of the derived object.
3,913,892
3,914,869
Learning Path for Qt "C# Developer"
Im a .net developer , i have studied a course in C followed by one in C++ before as an introduction to Programming, i want to learn Qt, im not sure if it is even possible for me to start right away read a book in Qt or should i start reading a book in C++ first ! Do you think that a Senior C# developer would be able to...
Having done what you are describing, I would make the following suggestions - For a book, take a look at C++ GUI Programming with Qt 4 (2nd Edition) . This is best book I've seen. But there are others, so do look around at them. Pick a topic you wish to learn, then work through one of the examples. They are very g...
3,913,901
3,914,681
Generic Database Manager(Wrapper)
AFAIK, we all must programming to database through database wrapper/manager such as sqliteman or CppSQLite. But the database wrapper is specific to one type of database and this is not convenient for programmer cause require a lot of modification in case the database was cahnged. Therefore, i would like to write a ge...
ODBC is the protocol. It is open database connectivity, which defines functions which a database should expose so that the user can use it in their C/C++ code. Normally the databases provides their own ODBC compliant driver. Soci is the library which does something that you want. It is a library, so it must be having ...
3,913,932
3,914,017
c++ pointer to const class member problem
I'm having this problem with C++ classes. I would like to get pointer to myBar object and store it in quxBar. The reason is I would like to be able to check the value using quxBar->getX() but I would also like to prevent from accidentally modyfing it from Qux so I tried using Bar const*. class Bar { private: int x;...
I don't think this is your actual code, firstly due to the syntax errors it has, and secondly due to the fact that it actually is correct (mostly). More specifically, with this piece of code, quxBar->setX(100); would result in compilation error. However, quxBar->getX() would also be a compilation error, you need to tel...
3,914,013
3,914,043
General Array/Pointer Data Type
I'm coding a C++ function that accepts a string, an array and the size of the array. It looks like this: bool funcname (string skey, string sArr[], int arrSz) I want to pass several array data types, such as double, char, long int, etc. Is it right to use string as data type for the array? Or is there a general data t...
Using a string in this way is bad imo. Amongst other things you are sending an array of strings. You'd be better off using a std::vector. You could then template the function as follows: template< typename T > bool funcname (const std::string& skey, const std::vector< T >& arr ) This way you can directly query the v...
3,914,177
3,914,715
Member subobjects of zero size. Why not?
This is the third question in the series of zero-size objects and subobjects today. The standars clearly implies that member subobjects cannot have zero size whereas base class subobjects can. struct X {}; //empty class, complete objects of class X have nonzero size struct Y:X { char c; }; //Y's size may be 1 struct...
The compiler could conditionally allow zero-size member objects as well as base classes, sure, but it would be more complex. The empty base class optimization always applies, regardless of type. Any time the compiler sees a class derive from a class with no data members, it can use the empty base class optimization. Fo...
3,914,251
3,914,271
Undefined references
Linker Error: $ make g++ -Wall -g main.cpp SDL_Helpers.cpp Game.cpp DrawableObject.cpp `sdl-config --cflags --libs` -lSDL_mixer /tmp/ccdxzrej.o: In function `Game': /home/brett/Desktop/SDL/Game.cpp:16: undefined reference to `Player::Player(Game*)' /home/brett/Desktop/SDL/Game.cpp:16: undefined reference to `Player::Pl...
You're missing Player.cpp in your compilation line. You're having a link error.
3,914,539
3,914,613
C++ - mapping type to enum
Is is possible to make compilation-time Type -> Enum Series mapping? Illustrating with an example: Let's say, I have some Type and a enumerated value: typedef int Type; enum Enumerated { Enum1, Enum2, Enum3, Enum4 }; and now I somehow state the following: "let's associate Enum1 and Enum4 with type Type (don't know ho...
You can do it this way even without boost.mpl: template< Enumerated Value > struct Enumerated2Type { typedef void type; enum { value = false }; }; #define DEFINE_ENUMERATED_TYPE(TYPE, ENUM) template<> struct Enumerated2Type<ENUM> { typedef TYPE type; enum { value = true }; } DEFINE_ENUMERATED_TYPE(int, Enum1); DEFINE_E...