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
4,479,961
4,479,968
How to cast const std::string& to integer?
I have a variable like this: const std::string& iterations = "30"; I want to use it to determine number of iterations for a "for" loop: for ( int i = 0; i < iterations; i++ ) { // do something } How to do that? I know I can cast to string like this: iterations.c_str(); So I tried c_int() but it won't work: iterati...
You could use this: int foo = atoi( iterators.c_str() ); See here for a description of atoi.
4,479,992
4,480,104
How do I remove dependency on mfc80.dll and msvcr80.dll?
My code does not use MFC. However, when I built my static lib the party that is trying to use it is stating that they are having a hard time because my code lib has the following dependencies in it: mfc80.dll and msvcr80.dll Is there a way to remove those and rebuild? I am using vs2008.
A static library by default links to the dynamic runtime, which is why your code has a dependency on msvcr80.dll. Visual C++ programs must link to a runtime. You can change your static library to use a static runtime to remove the dependency. This is done in the Configuration Properties | C/C++ | Code Generation | Runt...
4,480,021
4,480,069
Rendering from SDL and OpenGL at the Same Time
Hey all, I'm very new to OpenGL (just started seriously programming with it today) and I'm trying to use it to give my SDL games a 3D boost. I've setup a small test program below: #include <SDL/SDL.h> #include <gl/gl.h> int main(int argc, char *argv[]) { SDL_Event event; float theta = 0.0f; SDL_Init(SDL_INIT...
There's one simple rule about OpenGL: It doesn't play well with others. What happens in your case is, that the double buffer swap (initiated by SDL_GL_SwapBuffers) will in some way replace everything in the window, not being rendered by OpenGL. Just draw everything using OpenGL.
4,480,098
4,480,128
memmove doesn't move
memmove doesn't really move memory isn't that right? It just copies memory from one region to other and allows those two regions to overlap. I'm asking this question because I just want to know why is this fnc called in very misleading manner. For I understand that when something is moved from one place to the other, t...
You are right, it copies it. However, there is a difference between memmove and memcpy, because memmove can treat correctly the case when the buffers overlap, so it is recomended in these cases. However, because of additional checks that memmove performs, when the buffers are small and surely does not overlap, memcpy ...
4,480,163
4,480,183
Add prefixes to ostream outputs
I am looking for a way of adding a prefix to an ostream, pass it down to other functions so that their outputs are prefixed and then remove it to continue. Check the following pseudocode: ... void function(ostream &out){ out << "output 1\n"; out << "output 2\n"; } cout << "Whatever\n"; add_suffix(cout,"funct...
The general way goes like this: Define YourStreamBuffer that is a streambuf that inserts your prefix after any newline that is written to it, and sends the output to a destination buffer. Then use it like this: streambuf *oldBuf = cout.rdbuf(); YourStreamBuffer yourBuf(oldBuf, "function: "); // everything written to y...
4,480,199
4,480,605
C++/multiple files with vector of object pointers
The basic idea of this problem should make sense by looking at the code below but I'll try to explain. Basically I have two classes which reference each other via pointers and then these classes are in two separate header files. The program only works without the part where a vector of type b pointers is added into A.h...
Qualify vector with std namespace. class a { ... std::vector<b*> vecb; };
4,480,239
4,480,623
Converting infix notation expression to postfix notation
I'm doing an assignment for my Data Structures course where I have to convert an infix expression to a postfix expression. I'm almost done with it but I keep getting an error when I try entering something like a+b+c It can handle a+b and a+b*c just fine. I'm really not sure what's wrong with it. If someone could point...
You don't check whether the stack is empty before popping an element in the code for operators. That's part of the problem. By the way, it should be int main() instead of void, and you don't need to compare things with true: charStack.empty() == true is the same as charStack.empty().
4,480,251
4,480,272
Taking integer as parameter and returning an array
I want to create a function that takes an integer as it's parameter and returns an array in C++. This is the pseudo-code I had in mind: function returnarray(integer i) { integer intarr[i]; for (integer j = 0; j < i; j++) { intarr[j] = j; } return intarr; } I tried the common way of declaring returnarray ...
You need to use dynamic memory. Something like this int* returnArray(int size) { int* array = new int[size]; for(int i = 0; i < size; ++i) array[i] = i; return array; }
4,480,437
4,481,173
Win32 API Renderer Thread and OpenGL
I am trying to get threads running in my OpenGL program. Right now I am just working on a prototype to present to my group. Essentially, I have to render a large piece of terrain, using the ::PeekMessage() function from the Win32 API, is producing choppy results. Thus I am trying to get a render thread to run that will...
This is all over the internet in pieces. Anyways, I will leave my code up at my site for anyone else who runs into these problems. There were were two things wrong with my code. One I had to actually create a new ControllGL before I passed it to WinMaker. Once I did that it resolved all my issues. After my issues were ...
4,480,643
4,481,401
SDL: Two Event Loops?
Take a look at this piece of code here: void game::startLoop() { while(QUIT == false) { getRoomUpdate(); applySurface(-15, 280, zombie_lefthand, buffer); applySurface(455, 280, zombie_righthand, buffer); SDL_Flip(buffer); while(SDL_PollEvent(&gameEvent)) { if(gameEvent.type == SDL_QUIT) { QUIT...
The name keyEvent is misleading. SDL_WaitEvent will wait for any sort of event, including QUIT. SDL_Event event; SDL_WaitEvent(&event); switch (event.type) { case SDL_QUIT: quit = true; break; /* cases for keyboard events, etc. */ }
4,480,722
4,480,729
Should new/new[] match delete/delete[]?
I knew that when we allocate memory by using new/new[], then we should release the memory by using the delete/delete[] respectively. Here is the question, Can I use delete[] to release the memory allocated by new? For example, int *pInt3 = new int; delete [] pInt3; pInt3 = NULL; T *pT3 = new T; delete [] pT3; pT3 = NU...
No, you should match the non-array form of new with non-array delete, and likewise for the array forms. See the C++ FAQ Lite section on Freestore Management This is especially good: http://www.parashift.com/c%2B%2B-faq-lite/freestore-mgmt.html#faq-16.12 [16.12] What if I forget the [] when deleteing array allocated vi...
4,480,761
4,480,889
Why does Base *pd = new Derived; generate an error?
Given this code: class Base{ public: Base(); virtual ~Base(); }; class Derived: protected Base{ public: virtual ~Derived(); }; In main I am trying to assign derived to base in this way: Base *pd = new Derived; Why is this statement generating an error? Here new will return a pointer of the obje...
To convert a pointer to one class to a pointer to a different class type the conversion must be accessible at the point that it is invoked. As Base is a protected base of Derived you can't initialize a variable of type Base * from the expression new Derived (which has type Derived *) outside of a member function of Der...
4,480,944
4,481,205
gprof on MacOS 10.6 with c++ program has call data but no timing data --- why?
I have a C++ single-threaded program running on MacOS 10.6. It's getting call counts but not time information. Here's an example of the output: 0.00 0.00 9/31377020 __ZNSaISsEC1Ev [454] 0.00 0.00 9/31377020 __ZNSaISsED1Ev [314] 0.00 0.00 ...
I have heard some time ago that gprof did not work correctly on Snow Leopard and symptoms were like you described. If you find no solution then you may try out some other profiler like shark.
4,481,002
4,481,042
what is better to learn for pattern recognition?
c or c++?? if i want to make a project on pattern recognition( artificial computing) using c or c++ which one should i choose??
Object Oriented Programming can probably be of some help if you start programming something complex. That is possible with C but will probably be easier using C++. That said there is a risk to get lost on the multitude of features of the language if you are just learning it, and it's probably less so with C. But it's n...
4,481,224
4,481,304
Towers of Hanoi question
I read through a few of the discussions about the Towers of Hanoi problem. I understand the recursive solution using the following code: void Hanoi3(int nDisks, char source, char intermed, char dest) { if(nDisks == 1){ cout << "Move the plate from " << source << " to " << dest << endl; } else{ ...
Pass a reference to the stacks: stack<int>& Also consider using a vector rather than a stack so you can iterate it to see the current content of the towers. PigBen's answer also correctly identifies a bug in your code where you're not moving the disks from the intermediate tower to the destination tower.
4,481,285
4,481,374
How to store a magic number for each derived class that is then accessible from the base class?
class User { public: int v() { return min_pass_len; } static const int min_pass_len = 10; }; class AdminUser : public User { public: int w() { return min_pass_len; } static const int min_pass_len = 42; }; Then int main() { AdminUser a; st...
Just use a virtual method that returns a different number, skip the static var. class User { public: virtual int v() { return 10; } }; class AdminUser : public User { public: virtual int v() { return 42; } };
4,481,305
4,481,327
check my logic? (average gpa calculating program)
program reads the following data from a .txt file: f 3.40 f 4.00 m 3.56 m 3.80 f 2.30 f 3.95 m 3.90 m 4.00 m 2.00 f 4.00 f 2.80 m 3.70 m 2.98 f 3.89 m 4.00 f 3.90 m 1.90 m 2.90 f 1.50 f 2.67 m 3.80 m 2.35 Then calculates the average (gpa) for each gender (m for male, f for f...
Wouldn't these lines: skip every other line: while( inData >> gender >> gpa ) { inData >> gender >> gpa; You're using the return of the >> operator to indicate success for the test of the while loop, but each time it executes that, does it not consume that line and move to the next, so then when you execute it again...
4,481,308
4,481,470
Are QT mouse move events in a separate thread? And how to fix painting app problem related to this
I'm making a paint program to paint on 3D meshes using a circular brush. Because of the way I'm specifying the area to change to the brush color, I believe that the MouseMove Events are firing off quicker than the program can finish drawing, thus instead of just changing a circle to a different color, it's overflowing ...
Your suspicion is incorrect... Qt only uses a single thread (the main thread) for its GUI stuff. So your problem is somewhere else. It could be a bug in your code (I won't try to debug the logic here, since I don't think I could do a decent job of it), or it could be that Qt is combining MouseMove events when possibl...
4,481,379
4,481,452
Template arguments to template functions
I just released a skiplist container library. And the Sun compiler complains about this: template <class T, class R> bool operator==(const IndexedSkipList<T,R> &left, const IndexedSkipList<T,R> &right) { return ((left.size() == right.size()) && (std::equal(left.begin(), left.end(), right.begin()))); } The ...
As explained at Comparing C++ Standard Libraries libCstd and libstlport, the Sun C++ compiler ships with two implementations of a "C++ standard library": libCstd and libstlport. Unfortunately, libCstd is not standards-conforming, but it is the default for backward-compatibility reasons. Among other differences, libCstd...
4,482,005
4,482,013
Nested Class Definition in source file
If I have a nested class like so: class MyClass { class NestedClass { public: // nested class members AND definitions here }; // main class members here }; Currently, the definitions of MyClass are in the CPP file but the definitions for NestedClass are in the header file, that is, I c...
You can. If your inner class has a method like: class MyClass { class NestedClass { public: void someMethod(); }; // main class members here }; ...then you can define it in the .cpp file like so: void MyClass::NestedClass::someMethod() { // blah } Structures are almost the same thi...
4,482,106
4,482,180
Other ways for creating dynamic two-dimensional array?
Edit: I've completely revised my question as I have a better idea of what I want to do. #include <iostream> #include <cstdlib> using namespace std; int main(){ const int max_rows = 10; const int max_cols = 10; int *test = new int[max_rows * max_cols]; for(int i = 0; i < 100; i++){ test[...
Of course there is simple way, you need allocate one-dimensional array but use it as 2 dimensional: const int row = 5; const int col = 7; int *twoD = new int[row * col]; std::cout << twoD [4*row + 3]; //sample to access [3][4] return 0;
4,482,107
4,535,384
Event tracing using WPP from user mode, native application using Visual Studio
I'm looking for an example of utilizing "Event Tracing for Windows" (ETW) using WPP (a pre-processor) for applications developed in the Visual Studio environment. Whilst MSDN documentation promise that WPP is usable also for user mode, native application, it contains only examples of doing so for a device driver and a...
Found the answer I was looking for in the article: "WPP Tracing in Visual C++ 2010 Projects" by Trey Nash!
4,482,149
4,482,492
How to upload file to Amazon S3 in Qt 4
How to upload file to Amazon S3 in Qt 4 using their REST API? Maybe there are ready libraries already? Thanks!
Uploading a file using a REST API is just using HTTP POST method. You can already find answer on this question on Stackoverflow - see Upload file with POST method on Qt4
4,482,196
4,482,450
Qt: what are the differences between QtScript and Javascript in Webkit
I am familiar with web development so I know exactly what Javascript can do in webkit. If I want to employ the scripting feature in my apps, I think there are two ways: Employ qtwebkit and open a hidden webpage running my own Javascript scripts. Using qtscript. Right now I want most of my app logic are implemented wi...
Reading the following Qt 4.3 and later provides support for application scripting with ECMAScript. in Making Applications Scriptable section in Qt docs one comes to conclusion that QtScript is just a name of Java Script (ECMAScript is the name of the Java Script's official specification) implementation in Qt. A...
4,482,242
4,482,273
Trouble with: 'const int * const & alias_for_ptr = ptr;', why do both identifiers have different values?
Im having trouble understanding the meaning of const int* const &alias_for_ptr = ptr; with regards to the following: #include <iostream> using namespace std; int main() { int a = 10; int* ptr = &a; const int* const &alias_for_ptr = ptr; ptr = NULL; //or ptr = 0; if (ptr == alias_for_ptr) ...
Which compiler are you using? I've compiled under MSVC++ 2010, and it works as you expect. I think what's happening is a temporary is being assigned to a const-reference, since the type of "ptr" is converted from "int*" to a "const int*". What happens if you remove the first const? EDIT: Read here for more on reference...
4,482,372
4,482,391
How to guarantee bits of char and short for communication to external device
Hello I am writing a library for communicating to an external device via rs-232 serial connection. Often I have to communicate a command that includes an 8 bit = 1 byte character or a 16 bit = 2 byte number. How do I do this in a portable way? Main problem From reading other questions it seems that the standard does ...
AFAIK, communication with the serial port is somehow platform/OS dependent, so when you write the low level part of it, you'll know very well the platform, its endianness and CHAR_BIT. In this way the question does not have any sense. Also, don't forget that UART hardware is able to transmit 7 or 8 bit words, so it do...
4,482,403
4,482,410
What does C in C and C++ refer to?
Please let me know what this C in C programming and C++ programming is used for? I'm serious as this question was put in front of me in an interview.
Nothing at all. It was just the successor of B, which was a stripped-down version of BCPL.
4,482,416
4,482,497
why start a timer in SDL when setting FPS?
this is regarding this tutorial page from lazyfoo's set of SDL tutorials. There he first starts a timer to calculate how much time each frame should stay alive for, before it is refreshed. He does this using the following if( ( cap == true ) && ( fps.get_ticks() < 1000 / FRAMES_PER_SECOND ) ) { //Sleep the remaining ...
Let's say you want 50 fps. 1000miliseconds / 50 = 20miliseconds delay. But it takes time to render, compute physics, AI, whatever you are doing. Let's say that all this stuff I wrote takes 10miliseconds. You have 1000 miliseconds / (20ms delay + 10ms everything else) = 33.3 frames per second. You need to substract this...
4,482,518
4,486,058
Setting up an 'environment' for an embedded Lua Script
I am embedding a Lua interpreter in a C++ application. I want to setup an 'environment' for running scripts, such that certain variables are made available to all scripts. For example, I want to expose READ ONLY objects Foo and FooBar to scripts, such that Foo and FooBar are available to all running scripts. Does anyo...
I haven't heard of read-only variables in Lua but you can prevent modification by making the environment available via a function call instead. If the C++ application is large, you will probably want to use a tool to generate an interface you can call from Lua. I have used tolua++ in the past with some luck: Suppose de...
4,482,550
4,482,562
How do you avoid calling a grandparent constructor in C++?
The Child constructor in the code below calls its parent constructor to initialise itself. However the code won't compile unless Child also calls the Grandparent constructor, even though this is an implementation detail that's supposed to be hidden within Parent. I don't want to expose this detail to users of the Chi...
It's because the inheritance is virtual. Virtual inheritance can never be an implementation detail because the Child class has to manage the instances of any multiply-inherited class. If you use normal inheritance then this should not be a problem.
4,482,568
4,482,792
How make hierarchy of friend classes?
I have class A which has only private members (inclusive data, methods, constructors, destructor .... ). Also I have class B which is friend of class A. And I want all derived classes of B (also there are templates which are inherited from B) to be friends of class A too. Is there any way to do this?
C++ doesn't support this directly: "a kid of my friend is not my friend". You have to use another way to implement this; for example, define a set of protected accessor functions in class B: class A {friend class B; int x, y}; class B { protected: int& AccessX(A& a) {return a.x;} int& AccessY(A& a) {return a.y...
4,482,646
4,482,680
Is there a way to deduce the signature of a lambda as an mpl sequence?
Is there a way to deduce the signature, result- and parameter-types, of a c++0x lambda as a Boost.MPL sequence, for example a boost::mpl::vector? For example, for a lambda []( float a, int b ) -> void { std::cout << a << b << std::endl; } I would like to get a boost::mpl::vector<void,float,int>.
C++0x lambdas which are "closure-objects" are functors. So you can use boost.Boost.FunctionTypes to decompose its operator(). Example: #include <boost/function_types/parameter_types.hpp> #include <boost/mpl/at.hpp> #include <boost/mpl/int.hpp> int main() { int x = 1; auto f = [x](char a, short b, int c){ retu...
4,482,740
4,535,202
Creating several precompiled header files using GNU make
I use gcc (running as g++) and GNU make. I use gcc to precompile a header file precompiled.h, creating precompiled.h.gch; the following line in a Makefile does it: # MYCCFLAGS is a list of command-line parameters, e.g. -g -O2 -DNDEBUG precompiled.h.gch: precompiled.h g++ $(MYCCFLAGS) -c $< -o $@ All was well until...
It seems weird to answer my own question; anyway, here goes. To detect whether a suitable precompiled header file exists, i add a deliberate error to my header file: // precompiled.h #include <iostream> #include <vector> ... #error Precompiled header file not found This works because if gcc finds a precompiled header,...
4,482,784
4,483,242
C++ Array bound exception on overflow - "cout" and no "cout"
#include <iostream> int main() { int array1[10] = {0}; char* array2[10] = {'\0'}; for (int i = 0; i <= 100; i++) { std::cout << array1[i]; // This does not crash //std::cout << array2[i]; // This crashes array1[i]; // Wont crash here array2[i]; // nor here, Why? because there is no cout?? ...
EDIT: In response to the changed version of the question, the reason it crashes for array2 but not array1 is that (at least under MSVC) the operator<< for char* tries to get the length of the pointed-to string and ends up dereferencing a NULL pointer. You get the same behaviour if you do: std::cout << (char*)NULL; The...
4,482,851
4,482,913
Creating a numerical data type exceeding its normal size
There is a calculator program that I have came across on Windows long ago. I couldn't recall its name, but one impressive thing about it is that it can calculate numbers up to 512 bytes size. Requesting a pi value, for instance, it can give out numbers with hundreds of digits. (but of course it takes a few seconds to o...
Google around for the terms arbitrary-precision arithmetic and multiple-precision arithmetic. The number of libraries plus the number of applications which implement such arithmetic probably exceeds 2^32.
4,482,884
4,482,907
c++ simple reading from registry problem
platform- win. Well i'm trying to get a value of a key named SunJavaUpdateSched but i'm getting an error. i'm getting the second error, somehow i can open the key but can't get the value. So this is the code so far: void dealWithRegistry() { HKEY regkey1; char data[100]; DWORD datasize = sizeof (data) / sizeof (char...
Print out the actual error value. You can look up the system error code which will tell you exactly what the problem is. Note that RegGetValue is going to return a wide character string, not a character string, which means your variable using chars is going to give you garbage. Couple issues with the code itself: deal...
4,482,901
4,482,917
Is there a usecase for nested classes?
I've recently seen several people doing things like this here on Stackoverflow: class A: foo = 1 class B: def blah(self): pass In other words, they have nested classes. This works (although people new to Python seem to run into problems because it doesn't behave like they thought it would)...
It allows you to control the access of the nested class- for example, it's often used for implementation detail classes. In C++ it also has advantages in terms of when various things are parsed and what you can access without having to declare first.
4,482,906
4,482,929
Is it possible to see if two MP3 files are the same song by analyzing the files' bytes?
This is to be done in C++ or C.... I know we can read the MP3s' meta data, but that information can be changed by anyone, can't it? So is there a way to analyze a file's contents and compare it against another file and determine if it is in fact the same song? edit Lots of interesting things coming out that I hadn't th...
It's possible, but very hard. Even the same original recording may well be encoded differently by different MP3 encoders or the same encoder with different settings... leading to different results when the MP3 is then decoded. You'd need to work out an aural model to "understand" how big the differences are, and make a...
4,482,911
4,482,923
Making a program see another program's memory
There are tools such as TSearch, Cheat Engine, etc. These are hacking programs for viewing and modifying parts of memory of another program. If I am to create a C++ program that can see and modify other program's memory, how can I do that? What are some of the things I should be looking for?
This is not a feature of C++, it's under the control of the OS itself. For example, Windows provides the ReadProcessMemory() API call so that you can get your grubby little hands on the memory of another process. And of course, the equivalent for writing as well so you can cause even more damage :-) All this depends on...
4,483,087
4,483,122
c++ get registry key returns only one char
I'm trying to retrieve a value of a key but i'm only getting the first char of the value.. can anyone help? my code: void dealWithRegistry() { HKEY regkey1; char data[100]; DWORD datasize = sizeof (data) / sizeof (char); LONG rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentV...
It is probably returning Unicode data and you are only printing the first character. A quick test of that would be to change the call to RegGetValueA.
4,483,262
4,483,338
mingw g++ vector<T>::insert bug
vector<int> nums; nums.push_back(0); nums.push_back(1); nums.push_back(2); nums.push_back(3); vector<int>::iterator it = nums.begin(); it++; cout << "it points to " << *(it) << endl; for(vector<int>::iterator jt = nums.begin(); jt != nums.end(); jt++) { cout << (*jt) << endl; } cout << endl; nums.insert(it, 1005...
When you insert a new element into a vector, any iterators to elements after the insertion position are invalidated and if a reallocation occurs then all iterators into the container are invalidated. A reallocation occurs any time that v.capacity() - v.size() is less than the number of elements you are trying to inser...
4,483,309
4,493,879
Move packaged_task into lambda
I want to move and call a boost::packaged_task inside a lambda. However, I can't figure out an elegant solution. e.g. This won't compile. template<typename Func> auto begin_invoke(Func&& func) -> boost::unique_future<decltype(func())> // noexcept { typedef boost::packaged_task<de...
With a proper implementation of std::bind (or something equivalent with respect to move-enabled types) you should be able to combine bind and a C++0x lambda like this: task_type task (std::forward<Func>(func)); auto future = task.get_future(); execution_queue_.try_push(std::bind([](task_type const& task) { try{tas...
4,483,366
4,483,421
How to get a list video capture devices NAMES (web cameras) on linux ( ubuntu )? (C/C++)
So all I need is simple - a list of currently avaliable video capture devices (web cameras). I need it in simple C or C++ console app. By list I mean something like such console output: 1) Asus Web Camera 2) Sony Web Camera So I know how to get cam props such as W, H etc using code like: #include <stdio.h> #include <u...
You are using the V4L1 API which is deprecated - V4L2 is the preferred API for new code. In any case, the VIDIOC_QUERYCAP ioctl() is probably what you are looking for. You will want to have a look at the .card field of the returned struct v4l2_capability structure. EDIT: You could have a look at the source code for the...
4,483,552
4,483,612
Semantic of -> operator in lists (and in general C++)
My current assignment is writing a list with iterators. The list isn't being a problem so much as creating the iterator class is. From a couple of sources I've seen that I have two operators to define in my iterator class: operator* and operator->. Great so far! Supposing my iterator structure is so // Nested class o...
Whatever you do, (*something).somethingElse should be equivalent to something->somethingElse. The latter is just a short syntax for the former. Therefore, T& operator*() { return pCurr_->data; } T* operator->() { return &**this; } is fine because *this just dereferences this which has the type _Iter*, not _Iter, so no...
4,483,642
4,483,680
C++, the term/idiom for programming using template
I keep reading the term : template programming generic programming meta-programming maybe another idiom/term.. for any c++ code that use template, which one is the correct or more accurate term of this?
AFAIK: Template programming is just referring to the classic "programming with templates", i.e. "I have a function/class that I want to make usable with any type, I'll just make it template". It can also be can also be seen as the "catch-all" category that includes any programming technique that employs templates. Gen...
4,483,653
4,483,664
Can you explain the concept of the this pointer?
I need to understand this pointer concept, preferably with an example. I am new to C++, so please use simple language, so that I can understand it better.
this is a pointer to an instance of its class and available to all non-static member functions. If you have declared a class, which has a private member foo and a method bar, foo is available to bar via this->foo but not to "outsiders" via instance->foo.
4,483,735
4,483,774
How to know object creation is on heap or not..?
We want to work on low latency system, heap allocation is costlier in the application. but for some extent object creation on heap is allowed. Thats why we want indication whether object is created is on heap or not..? Is the below methodology is the correct way to find out object created on heap memory..? Will have g...
Note that your scheme fails miserably as soon as a MyClass object is a sub-object (inherited or contained) of another object which might or might not by allocated dynamically. (And the tricks I know for preventing dynamic allocation fail on that one as well.) So what you're doing just further slows down heap allocati...
4,483,873
4,483,954
Semantics of comparison of char objects
While I was reading through some old code today, I noticed the following assert line: assert(('0' <= hexChar && hexChar <= '9') || ('A' <= hexChar && hexChar <= 'F') || ('a' <= hexChar && hexChar <= 'f')); The purpose is to assert that hexChar is a hexadecimal digit ([0-9A-Fa-f]). It does this by relying on an...
The first line, comparison against the values of '0' and '9' is 100% portable. It's guaranteed by the C language to behave identically for all implementations. The second and third lines are in principle implementation-defined, but there has never been, and never will be, an implementation where their behavior differs....
4,484,076
4,484,103
Take a reference to a class template'd on any type
I'm writing C++ code that takes a reference to a class that depends on specific hardware, firmware and drivers. I would like to stub out the interface for testing, but there are a few roadblocks that have me stumped. The class I'm interfacing with is auto-generated (not my idea) so I can't have it inherit from a base c...
A common way to solve it is to factor out the virtual functions into their own interface that doesn't depend on template parameters: class DriverInterfaceBase { public: virtual ~DriverInterfaceBase( void ) { } virtual void GetDataBuffer( char *&pData, int &bufLen ) = 0; virtual void WriteDa...
4,484,098
4,484,182
I am a little confused about memory pointers
I have been teaching myself C++ in the last few days, and have run into some situations that I could use some further explanation on. What is the difference between the following methods besides the obvious class, naming, etc? void OnTimer(wxTimerEvent &event) ... void addNPC(Sprite *spr) ... Are both those methods r...
void addNPC(Sprite *spr) In above code, you need to pass address of Sprite object like below, as it receives pointer. addNPC( &sprite ); And for the function void OnTimer(wxTimerEvent &event) call has to be like below as it takes reference to wxTimerEvent object. wxTimerEvent evt; OnTimer(evt);//Passing object b...
4,484,150
4,874,094
Sparse Matrix multiplication like (maxmin) in C++ using Octave libraries
I'm implementing a maxmin function, it works like matrix multiplication but instead of summing products it gets max of min between two numbers pointwise. An example of naive implementation is double mx = 0; double mn = 0; for (i = 0; i < rowsC;i++) { for(j = 0; j < colsC;j++) { mx = 0; for(k = 0...
I don't know if anyoe would ever be interested, but i managed to find a solution. The code of the solution is part of fl-core1.0 a fuzzy logic core package for Octave and it is released under LGPL license. (The code relies on some octave functions) // Calculate the S-Norm/T-Norm composition of sparse matrices (single t...
4,484,235
4,484,273
temporary and copy constructor
With the below program, I tried to experiment with the copy ctor, there is one point which is not clear, when function f( ) returns it should use the copy-ctor to create a new object for h2, however I guess that is accomplished by the temporary object which uses the constructer of the object and then makes the copy how...
h copy copy is basically h2 from this line: HowMany2 h2 = f(h); It's destructed when you exit from main. h copy is the argument of f, it's destructed when f is returning. Since f returns before main, h copy is destructed before h copy copy. Note that RVO (return value optimization) was done by the compiler. There are ...
4,484,306
4,484,432
Binding a template function from within a template
In a continuation from this question. I'm trying to bind a given function that returns something-other-than void to be able to simply call f() later. However the following code fails to compile on GCC 4.4. It compiles on VS 2010, but the resulting program crashes. template<typename RetType> void _hideRet(std::function<...
This is absolutely amazing, but replacing : auto f = std::bind(func, std::forward<ParamType>(param)); return std::bind(_hideRet<RetType>, f, ret); by : std::function<RetType ()> f = std::bind(func, std::forward<ParamType>(param)); return std::bind(_hideRet<RetType>, f, ret); under Visual Studio 2010 runs as expected ...
4,484,545
4,484,591
C++ inheritance, and hiding unwanted inherited functions
I am trying to implement a QToolBar subclass, which has its items specified by a model, instead of added individually. This means a selection of functions to add/remove items (toolbar buttons), such as addAction shouldn't be publicly accessible. What is the best way to inherit from this object, but make a selection of ...
As long as you inherit publicly from QToolBar, you make it possible for a client code to treat your object as such and call for example the addAction member function. If you want to ensure that these functions are inaccessible, you'll have do this the other way : Inherit privately from QToolBar Publicly expose the fun...
4,484,714
4,484,740
C++ -- FindWindow win32 API always fails!
I am having problem with FindWindow() function in C++. I am using two programs -- Program A and program B. Both are console-applicaitons in native code. Program A initialises int i and string s with values. Program B reads them from Program A's memory using addresses shown when program A runs. Currently I am only int...
This cannot work at all the way you want it to work. Even if the FindWindow call would succeed: the window is not created by your console program. Instead, Windows has a separate server process taking care of console window creation, so that multiple processes can share a single console window. Instead, I recommend tha...
4,484,758
4,484,866
template metaprogramming problem
template <int p> bool FComapare (Node *lId, Node* rId) { if(lId->getDiff(p) < rId->getDiff(p)) return true; else if(lId->getDiff(p) == rId->getDiff(p)) { if(lId->getLT() < rId->getLT()) return true; else if(lId->getLT() == rId->getLT()) return (lId...
You can't use a variable for the non-type argument. Instead of a template function, try a function object that stores the value of i. class FCompare { int p; public: FCompare(int p): p(p) {} bool operator()(const Node *lId, const Node* rId) const {...} }; set<Node *, FCompare > f((FCompare(i)));
4,484,790
4,484,822
virtual member function necessity
when a have the same function name in a base class and a derived class with a different code for each function is it necessary to set my function as virtual or is it just part of better programming?
It's not necessary at all to make the method virtual. However, it should be virtual if you want it to be called through "late binding", i.e. if, given a base pointer, you want the derived method to be called. If you don't want that to happen, it's often because these methods are unrelated, in which case you better give...
4,484,962
4,485,001
c++ RegSetValueEx sets only one char value in registry
I'm casting (char * ) on data and i'm getting only one char value in the registry. if i don't use the casting msvc 2010 tells me that the argument type LPCTSTR is incompatible with const char *. can someone help me? HKEY hKey; LPCTSTR sk = TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"); LONG openRes = RegOp...
strlen(data) is probably returning a value of 1, as strlen expects a char* and L"TestData\0" is wide. Use TEXT("TestData\0") and call _tcslen(data). Note that RegSetValueEx expects the sizeof the data, so use _tcslen(data) * sizeof(TCHAR)
4,484,982
4,485,051
How to convert typename T to string in c++
While playing with templates in c++ I encountered a problem converting typename T to string. For example: template <typename T> class Matrix { public: Matrix() { //my_type = string type of T. i.e. if T is char. I want my_type to be "char". } string my_type; } How do I convert T to a st...
There is no built-in mechanism for this. typeid(T)::name() can give some info, but the standard does not mandate this string to be human-readable; just that it has to be distinct for each type. (E.x. Microsoft Visual C++ uses human-readable strings; GCC does not.) You can build your own system though. For example, trai...
4,485,030
4,485,218
C++ Call private / protected function of a common base class
Is there a nice way to call A::foo() from B::bar() in the following sample? class A { protected: void foo() {} }; class B : public A { public: void bar(A& a) { // edit: called with &a != this a.foo(); // does not work } }; I can't think of anything other than declaring B to be a friend of A, but that could ...
Yes, you can use a base-class function. class A { protected: void foo() {} void do_other_foo(A& ref) { ref.foo(); } }; class B : public A { public: void bar(A& a) { // edit: called with &a != this this->do_other_foo(a); } };
4,485,069
4,485,122
C++ -- OpenProcess returns error code 87
I have this problem with OpenProcess function for the win32 api. Program is intended to read an integer from a program given the program PID and address of integer through userinput. int main() { DWORD pidz; int buffer[1]; int temp; int* ptr_i; std::cout << "Type the address of i in programA: "; std::cin >> ...
OpenProcess returns ERROR_INVALID_PARAMETER when you give it a PID of zero. Check to ensure the operator>>(std::istream&, int&) call succeeded before calling OpenProcess.
4,485,434
4,485,734
Cursor in application window not correct type
After messing around a little with making a GUI with the Windows API, I recently realized a problem with the cursor. When I compile and run my application, it shows a window like its supposed to. When I drag my cursor from the left side of my screen into my applications window, as it goes over the border it becomes t...
Yes, that example code will behave as you describe because the hCursor member of WNDCLASS is set to zero, and WindowProc() doesn't handle WM_SETCURSOR. If you want the same cursor all the time then it's easiest to do something like this when setting up your window class: wc.hCursor = LoadCursor(0, IDC_ARROW); If you w...
4,485,447
4,565,052
Qt Code Editor on QPlainTextEdit How to tab the code
I am trying to implement a simple dialog to edit some part of code. I use this which is based on QPlainTextEdit. However, I cannot insert tab into code text. The main reason could be that I show the Code editor as dialog as seen in the code. When I press Tab button the dialog closes and then reopens. CodeEditor* editor...
Thanks guys, I solved the problem and it is totally about the part I did not mention in the question. This code is part of qtpropertybrowser code base. I am trying to add a property editor which will open code editing widget I pointed out in the question. When I drill down the qt property code base, I found that tab ke...
4,485,476
4,485,492
How to save an array to two class methods?
I have two classes: void Dice::toss() { int dices[SIZE]; for(int i = 0; i < SIZE; i++) { dices[i] = rand() % 6 + 1; } } int Dice::getValue() { return dices[i] ? } How can I save the value from dices[i] in first class to the other?
You have one class with (at least) two methods. It looks like you want dices to be a class member, and that way both methods can see it. Your class definition would be: class Dice { int dices[SIZE]; void toss(); int getValue(); }; And then take the declaration of dices[SIZE] out of toss.
4,485,913
4,487,068
vectors in python structs
is there a way to store vectors in structs in python? specifically, im trying to do: struct data{ string name // name of event string location // location of event vector <int> times // times the event happens in 24 hour format }; im not sure how to do it with the structs module, since ive...
It's not clear from your question, but if you just want a similar structure in Python you can use a list in place of the vector<int>. data = ('John','Los Angeles, CA',[1,2,3,4,5,6]) Another alternative is to use a namedtuple: >>> import collections >>> Data = collections.namedtuple('Data','name location times') >>> da...
4,485,916
4,485,950
SDL: SDL_WaitEvent exceptions?
(I'm still on the same track as the last two questions I've asked, I just can't hit this in the right spot!) Anyway my question is this: How do I add or only allow certain things to be registered by SDL_WaitEvent? The current program that I am working on requires to wait for the user to give their input before returnin...
You probably want the SDL_EventState() function. The terrible wiki documentation might be able to help get you up to speed. The basic idea, though, is that you simply set SDL_IGNORE or SDL_ENABLE depending on whether you want to ignore or receive certain events.
4,485,941
4,486,144
ZeroMQ linker error C++
I get the following error: "Error 1 error LNK2019: unresolved external symbol _imp_zmq_init referenced in function "public: __thiscall zmq::context_t::context_t(int)" (??0context_t@zmq@@QAE@H@Z) ZeroMQPlay.obj ZeroMQPlay" With this C++ code: include "stdafx.h" include <zmq.hpp> int _tmain(int argc, _TCHAR* argv[])...
You have to tell the linker about the ZeroMQ library. If you've built ZeroMQ as a VS project, the easiest way is to add the ZeroMQ project to the solution containing your own project and mark your project as dependent on it.
4,486,140
4,486,148
Which C/C++ header file defines a BYTE data type?
I'm porting a header with this declaration: struct tMaterialInfo { char strName[255]; // the texture name char strFile [255]; // the texture BYTE color [3]; // the color of the object }; The header has the following includes: #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <ma...
I'm guessing it's from Windows. A byte (8 bits). This type is declared in WinDef.h as follows: typedef unsigned char BYTE;
4,486,213
4,486,319
Programming Quicksort Algorithm Q
I'm trying to write quicksort and understand the algorithm. I understand the 3 basic principles of quick sort The element a[i] is in its final place in the array for some i. None of the elements in a[l], a[i1] is greater than a[i]. None of the elemtns in a[i+1],..., a[r] is less than a[i]. I think I'm missing somet...
My first question is l and r, those are the min and max of the array? or is it any place within the left and right side of the array. No, those are the left and right borders of the current sub-array being sorted. I have no idea why you invoke method with parameters 4 and 7: it means none of the elements before 4-th or...
4,486,265
4,486,282
Pointer Array Question
Creating an array can be done both of these ways? But isn't all an array is the beginning of the array address and allocate enough bytes for the type. So my question is what's the difference either using a pointer to an array of bytes or using just the first option? int numbers[10]; int* num = new int[10]; or int* nu...
Your second version there declares a pointer to an integer initialised to 10. That's not an array.
4,486,301
4,486,485
GCC function padding value
Whenever I compile C or C++ code with optimizations enable,d GCC aligns functions to a 16-byte boundary (on IA-32). If the function is shorter than 16 bytes, GCC pads it with some bytes, which don't seem to be random at all: 19: c3 ret 1a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi It alway...
The padding is created by the assembler, not by gcc. It merely sees a .align directive (or equivalent) and doesn't know whether the space to be padded is inside a function (e.g. loop alignment) or between functions, so it must insert NOPs of some sort. Modern x86 assemblers use the largest possible NOP opcodes with the...
4,486,309
4,505,775
DX10 SwapChain ResizeBuffers(...) vs ResizeTarget(...)
What's the difference? Google / MSDN don't seem to have any info. MSDN: ResizeBuffers ResizeTarget
Found this while searching for something entirely different... From MSDN ... DXGI resizes the front buffer to match the newly selected full-screen mode, and it sends a WM_SIZE message to the application. The application again calls ResizeBuffers, just as it would if the window border was dragged. The methodology of th...
4,486,326
4,486,356
Does "const" just mean read-only or something more?
What does const really mean? Read-only seems to encapsulate its meaning for me, but, I'm not sure I'm right. If read-only and const are different, could someone tell me why? What prompted this question was this answer where he states const "just" means read-only in C. I thought that's all const meant, regardless of whe...
By declaring a variable as const you indicate compiler that you have no intentions of modifying that variable. But it does not mean others don't have! It's just to allow some optimization and to be notified by a compile error (note, that it's mostly compile error, while const == ReadOnly would mean runtime errors). con...
4,486,350
4,486,400
using CreateProcess with a relative path
Is it possible to pass a relative path to create my child process? This code will compile, but it gives an error because I'm using a relative path. void Cminivideo3App::creerChildProcess(void) { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &...
Couple things: As @Oswald says, \ is the root folder of the current drive, not a relative path. You forgot to escape your backslashes. You really want TEXT("..\\Debug\\traitement.exe").
4,486,383
4,486,422
buffer overflow literature for C/C++?
does someone know good literature for C/C++? language: german/english thanks
This is the classic treatsie ... Smashing The Stack For Fun And Profitl
4,486,403
4,486,434
c++ getting conversion error when trying to overload subscript operator
I am working on a school assignment that requires operator overloading. I am having difficulty with my subscript overload method. Have the return type set to int yet when I write a command like int myInt = myVector[i] I get a compiler error: C2440: '=' : cannot convert from 'MyVector' to 'int' #include <stdexcept> #i...
Try tmp = (*mv)[i]; in line 111. You pass a pointer to MyVector in line 106, you need to dereference that pointer before applying operator[].
4,486,419
4,486,443
Default value for boost::shared_ptr on class constructor
Suppose I have class like class A{ public: A(int a, boost::shared_ptr<int> ptr){ // whatever! } }; My question is, what's the default value for that ptr? I'd like to be able to create an instance of that class using A myA(5); Sure I know I could create another constructor with just one parameter, ...
#include <boost/make_shared.hpp> A(int a, boost::shared_ptr<int> ptr = boost::make_shared<int>()) Check http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/make_shared.html
4,486,442
4,486,532
How does "const" differ in C and C++?
How does the const qualification on variables differ in C and C++? from: Does "const" just mean read-only or something more? "What prompted this question was this answer: https://stackoverflow.com/questions/4024318#4024417 where he states const "just" means read-only in C. I thought that's all const meant, regardless o...
const in C cannot be used to build constant expressions. For example : #include <stdio.h> int main() { int i = 2; const int C = 2; switch(i) { case C : printf("Hello") ; break; default : printf("World"); } } doesn't work in C because case label does not reduce to an integer constant...
4,486,584
4,486,599
What is difference between libmysqlclient.a and libmysqlclient_r.a?
Which should I use to link for mysqlclient library? What is the difference between them? I can't seem to find the answer. Thanks.
libmysqlclient_r.a is thread-safe
4,486,609
4,486,715
When can compiling c++ without RTTI cause problems?
I'm using gcc's -fno-rtti flag to compile my C++ without runtime type information. Assuming I'm not using dynamic_cast<> or typeid(), is there anything that could lead me to later problems?
Since your question is specific to GCC you should consult carefully the documentation for the version you are using. The documentation for GCC 4.5.2 says the following. Which from my reading would indicate that if you avoid dynamic_cast and typeid, you should be ok. That said, I have no personal experience with -fno-rt...
4,486,642
18,418,391
Obtaining cross-platform path for config file (C/C++)
I would like to store my application's settings in a configuration file. Under Linux (and Mac?) this (might) be /home/user/.config/app.conf while under Windows it (might) be "C:\Documents and Settings\username\Application Data\app.conf". It can of course be stored elsewhere, so the only way to get the correct locatio...
This came up again, so I decided to bite the bullet and create my own solution since the only existing ones are part of huge frameworks and impractical for small programs. I have published the code at https://github.com/Malvineous/cfgpath It is placed in the public domain so free to use by anyone for any purpose. It h...
4,486,663
4,486,671
Why does my Button look like it's from 1990?
I'm writing a Windows GUI app and I have come on the need to have a normal button. I am using this code to generate the button: hwnd = CreateWindowEx( NULL, "BUTTON", "Button", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON, CW_USEDEFAULT, CW_USEDEFAULT, 60, 25, parentHwnd, NULL, GetModuleHandle(...
See Normal looking button with c++ / win32
4,486,882
4,486,898
What's the best (for speed) arbitrary-precision library for C++?
I need the fastest library that is available for C++. My platform will be x86 and x86-64 which supports floating points.
GMPLIB GMP is a free library for arbitrary precision arithmetic, operating on signed ... C++ class based interface to all of the above.
4,487,002
4,487,043
Problem using Connect(), send(), recv, with UDP sockets
For my Uni assignment I have to create a fast action paced networked game and so have chosen to use UDP as opposed to TCP. I am aware of a lot of the differences in programming both UDP and TCP and have read through most of the relevant parts of MSDN's documentation on winsock. On MSDN it states that creating a UDP soc...
You will need to call bind() if you want your program to receive UDP packets. connect() only sets the address that the socket will send packets to if you call send(); it does not associate the socket with a local UDP port to receive on; for that you must call bind().
4,487,038
4,490,972
Win32 windowless application - wait for program exit
I have a windowless application whose only purpose is to install a 32 bit hook DLL file and wait until the parent program (a 64-bit program) exits. The 64-bit program is written in C#, and the windowless application is written in C++. I originally had this GetMessage loop which held the program open: while(GetMessage(&...
GetMessage never returns is because you don't have a window created! To use a message-queue you have to have some GUI. You Can for instance create a hidden window.
4,487,063
4,487,711
float vs unorm 0->1, which one is more precise?
Float - standard 32 bit IEEE float unorm - 32 bit (range 0->1) Which one is more precise when used to represent data in the 0->1 range? Or are there no precision differences?
A float represents values outside of the [0,1] range as well (only about 1/4 of floating point numbers lie in that range). So there are ~2^30 floats in that interval, but 2^32 unorms. Floats deliver more precision close to zero, but averaged over the whole range, unorms are more precise. (The resolution of floats ove...
4,487,147
4,487,290
Using GNUMP how to find logarithm of base10
I am facing a problem in C++. i need a double which is more precise than standard c++ double. (C++ long double is even not enough) so.. i found GNUMP that does satisfy me.. but.. How do i find the logarithm of base 10 of a given number..
The short answer is that the GNU MP Library is not the complete solution; it only provides integer and rational functions. However, the MPFR library is built on top of and used/linked with the GNUMP library and it provides the transcendental functions you need.
4,487,370
4,490,236
store negative number in char array ( still no requirred/desired solution )
EDIT: platform unix type : ansi c I have data in form ; 1 2 3 -1 2 -9 1 3 + -1 2 -3 -4 - * integer in range between -9 and 9 '+ - *' operator and shows that you should take data which lies at following line data is char double pointer each line must be stored in double pointer char array example : data[...
I believe the key here is to take advantage of the limited range of your input values. Since your input numbers will only be single-digit integers, find several impossible input values and reserve them for operators. For example, you can let 64 be '+', 65 can be '-', etc. Use strtol() to read in the numbers one at a...
4,487,517
4,487,632
Unable to Create or Write to a file as standard user
My application creates a log file when it connects or disconnects a server. This works well win win XP. There are no issues while I run it as admin in Vista and Win 7. But if I run this as a standard user in Vista or Win7 then it fails to create the log file, and I know this is for UAC. But how can I bypass this situat...
If you really want to, you can add a manifest that causes your application to require UAC elevation when it is launched, but more often than not that's not what you should do. More likely, you're writing to a path you shouldn't be. User mode applications should only write to the current users folders or the C:\Users\Pu...
4,487,646
6,513,340
Linking to boost through SConstruct
I'm trying to work on a cross-platform project that uses boost for the file/directory operations. I've been using visual studio, but in order to compile on linux, I've decided to switch to SConstruct. I cannot [correctly?] link to the filesystem library however. my SConstruct file is as follow: vLibs = [ ...
I got the exact same error until I rebuilt boost with the address-model=64 parameter to bjam
4,487,684
4,487,815
Linking to the correct library
I dont think my question here was answered here already. So here it is, I have a static library that I maintain and update periodically. I also update the version number correctly. Now my application which uses this library must link to exactly the same version of the library and not to the older or newer ones. O...
I'm not sure that I'd recommend it, but... The header could include: #define LIB_VERSION_SUFFIX _3_17 #define LIB_PASTER(x, y) x ## y #define LIB_EVALUATOR(x, y) LIB_PASTER(x, y) #define LIB_FUNCTION(x) LIB_EVALUATOR(x, LIB_VERSION_SUFFIX) #define lib_functionA LIB_FUNCTION(lib_functionA) extern int lib_funct...
4,487,739
5,300,127
How to check whether a jpeg is a RGB or CMYK format?
I am using c++, gdi+,WINDOWS. How to check whether a jpeg is a RGB or CMYK?
If you use the IJG libjpeg library, you can open the JPEG file, read the header, and see whether is it grayscale (monochrome), RGB, or CMYK. (Actually, there are several free JPEG libraries, but the IJG libjpeg is probably the most commonly used.) You can find libjpeg sources at: http://www.ijg.org/files/jpegsrc.v8c....
4,487,799
4,488,650
Export data from qtablewidget to csv
I have a little problem with export data to csv (comma-separated values). All data was exported, but headers and name of rows from QTableWidget don't. I need headers of columns and rows. Do you have any idea how to get name headers of columns and name of rows? Here is my code: QFile f( "money.csv" ); if (f.open(QFile...
You can use QTableWidget::horizontalHeaderItem(int column), which returns the header item for the column column. QTableWidget * table = ui->tableWidget; for( int c = 0; c < widget->columnCount(); ++c ) { strList << "\" " + table->horizontalHeaderItem(c)->data(Qt::DisplayRole).toString() + ...
4,487,914
4,488,595
Which function to call? (delegate to a sister class)
I just read about this in the C++ FAQ Lite [25.10] What does it mean to "delegate to a sister class" via virtual inheritance? class Base { public: virtual void foo() = 0; virtual void bar() = 0; }; class Der1 : public virtual Base { public: virtual void foo(); }; void Der1::foo() { bar(); } class D...
What is happening behind the scene. The simple explanation is that, because inheritance from Base is virtual in both Der1 and Der2, there is a single instance of the object in the most derived object Join. At compile time, and assuming (which is the common case) virtual tables as dispatch mechanism, when compiling De...
4,488,053
4,603,063
How can I cope with 32bit/64bit mismatches when doing IPC via SendMessage?
I have a piece of C++ code which reads out the text of a tree item (as contained in a plain Common Controls Tree View) using the TVM_GETITEM window message. The tree view which receives the mesage is in a different process, so I'm using a little bit of shared memory for the structure which is pointed to by one of the a...
I ended up checking whether the remote process is 32bit or 64bit at runtime, and then writing the right structure to the shared memory before sending a message. For instance, here's how you can use the TVM_GETITEM message even if there's a 32bit <-> 64bit mixup between the caller and the receiver of the message: /* Thi...
4,488,125
4,488,603
Enumeration type comparison error
typedef enum { TYPE_A = 0, TYPE_B, TYPE_C } OBJTYPE; Assume there is the enum type above. I'm using arm-g++ for my working. And some macro for any type is defined like this: #define ANY_TYPE ((OBJTYPE)-1) But following comparision was false as I tested: if (param->type == ANY_TYPE) something(); else error(); p...
-1 is an illegal value for your enumeration. The language standard (7.2 Enumeration declarations) says: For an enumeration where emin is the smallest enumerator and emax is the largest, the values of the enumeration are the values of the underlying type in the range bmin to bmax, where bmin and bmax are,...
4,488,128
4,488,201
How can I fetch data from a website inside a C++ program
I want to write a program in C++ that helps to manage my hockey pool, and one of the key things i will need to do is read off the schedule for the week ahead. I was hoping to use the NHL website. is there any way to have the program download the HTML file for a given url, and then parse that? i suppose that once i have...
I would use some library providing Http abstraction. For example: cpp-netlib #include <boost/network/protocol/http/client.hpp> #include <string> #include <iostream> int main() { boost::network::http::client client; boost::network::http::client::request request("http://www.example.com"); request << boost::ne...
4,488,709
4,488,782
Why does C++ not allow user-defined operators?
I've been wondering this for quite some time. There are already a whole bunch of them and they can be overloaded, so why not do it to the end and allow custom operators? I think it could be a great addition. I've been told that this would make the language too hard to compile. This makes me wonder, C++ cannot really be...
http://www2.research.att.com/~bs/bs_faq2.html#overload-operator The possibility has been considered several times, but each time I/we decided that the likely problems outweighed the likely benefits. It's not a language-technical problem. Even when I first considerd it in 1983, I knew how it could be implemented. Howev...
4,488,718
4,488,827
How to exchange data between classes?
I'm learning C++ and moving my project from C to C++. In the process, I stumbled on this problem: how to save/update variables that are in use in several classes? In C I used global variables, but it is not good for C++. So, let's assume we have 4 classes: class Main_Window { //... void load_data_menu_selected(...
Start from observing what are possible relations between instances of two classes. Let us say a is an instance of class A and b is an instance of class B. If a uses b, class A can have as its member instance of class B (b), pointer to b (which is of type B*), or reference of b (which is of type B&). If only one method ...
4,488,794
4,492,612
visual c++ 2010 can't add resource file
i want to add to my project a resource file but vs2010 won't let me. what do i do?
If you use Express Edition, then you can't compile resources (may be it is a reason, why you can't add them too).