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,293,351
4,293,440
Calling upper level class member C++
So suppose I have: Class A { void A::DoSomething(); A::A() }; Class B : public A { void B::DoSomething(); B::B() } Class C : public A { void C::DoSomething(); C::C() } B obj1; C obj2; void RemoveObjectFromListOrSomethingSimiliar(A objToLookFor) { //assuming you found the object, how would you call the top-level DoS...
I'm not sure I got your question right, but I guess what you need is dynamic binding. Here is an example based on your pseudocode. #include <iostream> class A { public: A() {} virtual void DoSomething() { std::cout << "A did something!" << std::endl; } }; class B : public A { public: B...
4,293,365
4,294,038
Don't have access to template template parameters
Why can't I do this: template<template<class E>class Derived> struct X { static void f() { Derived<E>::value; } }; The problem that I have is that I cannot compile this code for the reason that I'm getting an error saying that param E hasn't been declared. Is there a way that I can use this form...
Parameters of template template parameters don't get arguments, and therefore don't usually have names. Partial specialization is the exception to this rule. Try this instead: template<class> // Derived<E> is only only parameter struct X; // but you actually need two parameters, Derived and E template< template <class...
4,293,423
4,293,447
Inheriting non-default
Is there a syntax that will allow me to inherit from a class without dflt ctor? For example: template<class T> struct X : private Y(T)//HERE I'm trying to inherit via cnv (conversion) ctor { };
Definitely. You just have to call a base constructor explicitly in the derived class's constructor's initializer list struct X { X(int a) {} }; struct Y : X { Y() : X(123) {} };
4,293,509
4,293,546
What is difference between callback function and regular function?
Ok I'll give two examples of function is using CALLBACK and regular function. Note: I didn't write these examples. Regular Function int sumExample (int a, int b) { return a + b; } int main() { int = sumExample(1, 3); cout >> int; return 0; } Function using _stdcall int __stdcall sumExample (int a...
Basically, a calling convention specifies implementation details of how the function will be called. Most libraries use the Standard C calling convention - __cdecl. WinAPI however expects __stdcall. You only need to know two things about calling conventions: that they have to match, e.g., you can't convert a void(*)(in...
4,293,526
4,293,673
Problem using accessors in V8
I'm writing a wrapper class around the V8 engine so that eventually I'll be able to do something like this script->createClass("Test"); script->getClass("Test")->addFunction("funct1",testfunct1); script->getClass("Test")->addVariable("x",setter,getter); So far I can create classes and add functions to them and it work...
SetAccessor on Object is available as of V8 2.2.12, which was released May 2010. (Before that, it was indeed only available on ObjectTemplate.) You should probably update your copy of V8.
4,293,572
4,293,586
Passing on a char* which contains a path
I'm trying to pass through several functions a string with a path but the every '\\' I put in the path becomes a single '\' in the inner function and I can't use it this way. Is there a way to preserve the "\\" when entering a new function? I'm using C++ on windows. thanks :)
Be prepared for some obfuscated answer. The \ is the escape character (you have probably already encountered the \n escape sequence for example), and \\ is the escape sequence that represents a single \ character (in a sense, it can be understood as an escape of the escape character). If you really want to have \\ in y...
4,293,625
4,293,703
Curl CURLE_COULDNT_RESOLVE_HOST in debug mode
I am using curl to access a file in a specified url. I use VC++ 2010 and curl 7.21.2 (I compiled it myself) with wxWidgets for user interface (all built in unicode except curl). I have no problem in my release build but the same code (below) fails in debug build with CURLE_COULDNT_RESOLVE_HOST error for the same url. ...
The following line seems to be the problem: curlcode = curl_easy_setopt(pEasyHandle, CURLOPT_URL, url.ToStdString()); If my assumptions are correct, ToStdString returns an std::string and not a C string. curl is a C library, so it expects char *-s. Could you tell what type url is?
4,293,653
4,293,676
Dynamically allocated array inside std::list leads to memoy leaks
The following code leads to a memory leakage: std::list<float*> vertices; float* v; for (int i = 0; i < 50000; i++){ v = new float[3]; v[0] = v[1] = v[2] = 13; vertices.push_back(v); } std::list<float*>::iterator curr; for(curr = vertices.begin(); curr != vertices.end(); curr++) { ...
You are mis-interpreting your results. The "leak" you are seeing is not actually a leak, but pre-allocation, which is basically where the CRT or STL keeps around allocated memory incase you need it again for faster allocation time. Moreover, you should really, really use self-releasing pointers. They're guaranteed neve...
4,293,720
4,293,872
Overloading new as a friend function?
For one of my classes, I'm writing a program that's going to be using a templated memory pool structure to handle the allocation of new instances of a class while keeping them together. It is currently declared as follows: template<typename T, unsigned int N> class MemoryPool { //Stuff }; Where T is the class to ...
It is possible to overload the new operator, however I would advice against it. I think you are going in the wrong direction. You don't want to hide things and make users unsure what is happening. In this case you should be explicit that you are allocating through a pool. Here is what you could do. template<typename T...
4,293,749
4,293,833
Testing function with BOOST.Test
I have a fnc: template<class T, T constraint> inline void CheckSize(const T& value) { if (value < constraint) { throw BadSize_ex(value); } } but I cannot test it with Boost. What I'm doing is this (): BOOST_REQUIRE_THROW(CheckSize<int,2>(1),std::BadSize_ex); Where is the problem? but I'm getting lots of min...
It is the comma between template parameters. Try with additional paranthesis: BOOST_REQUIRE_THROW( (CheckSize<int,2>(1)),std::BadSize_ex);
4,293,759
4,293,804
Ifstream infinite loop (it never seems to find the marker to stop reading)
A rather quick question... I can't figure out why this loop never ends... #include <iostream> #include <fstream> using namespace std; int main() { //[city1][city2][distance] ifstream sourcefile; int data[50][50]; sourcefile.open("a5.txt"); if(!sourcefile) { cout << "file not found" << endl; return ...
peek lets you see the next character, which I think in this case is the newline after the distance value. since it's not Q, the loop tries to read another three integer values, fails, and sets the error bit. peek, when there's a failure, returns EOF - so you never get to see the Q.
4,294,023
4,294,036
Why is swap() sometimes implemented by passing an array?
In some comp-sci papers and tests, I see swap() implemented like so: void swap(int x, int y, int *a) { int t = a[x]; a[x] = a[y]; a[y] = t; } Why not simply implement it like so: void swap(int& x, int& y) { int t = x; x = y; y = t; } Is the idea to the former to make the calling code cleaner, ...
Not all programming languages support calling by reference. For instance, the latter way of doing swap doesn't apply to Java. In books containing pseudo-code, usually there's a convention that arrays and pointers are not copied when passed and everything else is copied in a function call. The former way requires no sp...
4,294,052
4,294,256
Convert 128-bit hexadecimal string to base-36 string
I have a 128-bit number in hexadecimal stored in a string (from md5, security isn't a concern here) that I'd like to convert to a base-36 string. If it were a 64-bit or less number I'd convert it to a 64-bit integer then use an algorithm I found to convert integers to base-36 strings but this number is too large for t...
A base-36 encoding requires 6 bits to store each token. Same as base-64 but not using 28 of the available tokens. Solving 36^n >= 2^128 yields n >= log(2^128) / log(36) or 25 tokens to encode the value. A base-64 encoding also requires 6 bits, all possible token values are used. Solving 64^n >= 2^128 yields n >= log...
4,294,066
4,294,108
Is the whole object freed with a non-virtual destructor and a Base class pointer?
If a Base class does not have a virtual destructor (in order to avoid the vtable entry for instance) and the Derived class has only basic attributes, does it free all the memory allocated by new, when the pointer of the Base class is deleted? I know the destructor of the Derived class will not be called but I am wonder...
It's undefined behavior, so anything can happen. Quote from the standard [expr.delete]: In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type ...
4,294,100
4,294,152
Creating a class indexer operator[] allowing string parameter (string index)
I want to create a class in c++. This class must manage with a collection. OK, no problem, I would like to use operator[] of course but, in this case, my wish is to index not by position, but by name ==> that means using a string indexer. It seems that something of this kind is not so nice to my compiler: // In hpp cla...
It should work fine. See this example which compiles and works ok for me: #include <iostream> #include <string> class MyClass { public: std::string operator[] (const std::string& key) { std::cout << key << std::endl; return key; } }; int main() { MyClass obj; std::string s = obj["50"]; std::co...
4,294,285
4,294,455
!= operator and file streams
#include <iostream> #include <fstream> using namespace std; int main() { ifstream file0( "file0.txt" ); ifstream file1( "file1.txt" ); if (file0 != file1) { cout << "What is being compared?" << endl; } } If the above code, what is being compared in the conditional? I believe it is pointer...
When doing a comparison on an ifstream the operator void* will be called. If you are using visual studio you can see this if you choose to see the disassembly of the code. The operator can be found here. As you can see mentioned: The pointer returned is not intended to be referenced, it just indicates success when non...
4,294,335
4,294,371
Comparison operator "no match" error
I have searched the site for something similar, however the other posts on "no match for operator" errors do not help in my situation. I have a struct node in the beginning, and then the following piece of code: Function end() returns a type node. Therefore the statement op != end(OPEN) should resolve just fine, howeve...
You need to define a comparison operator for your node type: bool operator!=( const node& lhs, const node& rhs ); Edit: Just define an equality comparison, then define inequality in terms of that: bool operator==( const node& lhs, const node& rhs ) { return ...; // whatever } bool operator!=( const node& lhs, con...
4,294,690
4,294,716
Visual Studio 2010 or C/C++ performance monitors
I was wondering if there were any tools that allow me to see roughly how long it takes to run through a function or program. Such as it would tell you that your typical merge sort alogrithim ran ~nlogn or took x time per n or to complete. Stuff like that. It seems like Visual Studio Ultimate and Team has something tha...
You mean a performance profiler What's the best free C++ profiler for Windows?
4,294,813
4,294,825
operator precedence (void* before bool?)
When answering this question I made some research which really confuses me. I noticed that two ifstreams that succesfully open are not equal but two ifstreams that fail are. At first i checked cplusplus.com. The operator ! returns the status of the badbit and failbit. I think that the opposite of this would still be t...
1.) You cannot overload multiple times but with different return types. 2.) Yes, operator! returns the badbit/failbit, but operator! is something entirely different from operator!=, which is the one you are using.
4,294,846
4,294,860
Why such loop does not catch error when inputting a string?
int SelectedIndex; int i = 4; while(SelectedIndex > i-1 || SelectedIndex < 0) { try{ std::cout <<"please input index from 0 to " << i-1 << std::endl; std::cin >> SelectedIndex; } catch(std::exception& e){SelectedIndex = 999;} } Why such loop does not...
Assuming are trying to read in an integer using std::cin and detect if the user input a string instead: If the user does input a string, an exception will not be thrown (which is why your code doesn't work as expected). Instead, the input will be left in the buffer, and cin will be in an error state. The next cin >> wi...
4,294,857
4,294,874
Are . and -> in C and C++ really operators?
you probably have been tought, are tought yourselves, that . and -> are operators which retrieve members of a struct (C) or class (C++). However, I doubt they are operators - because, if they are operators, what are their input types? Furthermore, the identifiers on both sides are interdependent - a feature which for e...
This reference says they're both operators in C++: http://www.cplusplus.com/doc/tutorial/operators/ Is that not authoritative enough?
4,294,873
4,294,891
define both operator void* and operator bool
I tried creating a class with one operator bool and one operator void*, but the compiler says they are ambigous. Is there some way I can explain to the compiler what operator to use or can I not have them both? class A { public: operator void*(){ cout << "operator void* is called" << endl; return 0;...
You could call the operator directly. int main() { A a1, a2; if (static_cast<bool>(a1) == static_cast<bool>(a2)){ cout << "hello"; } } In this case, though, it looks like you should define operator==() and not depend on conversions.
4,294,921
4,295,545
Scale a custom matrix class by a vector
I'm terrible with matrix maths but I have a situation where I need to scale one. The matrix is an instance of a custom class defined here and my scaling object is a vector containing 3 floats (x,y,z). I'd like the actual code I need rather than a generic explanation because I've already gone down that path and just don...
I looked at the API link you provided, and based on that, this is how I would implement a scaling method for the matrix class so that it's consistent with the existing Translate() and Rotate() methods. That is, it does a right side multiplication with a scaling matrix. Though personally I find it a bit weird, because ...
4,294,926
4,295,677
How to get access to external libraries and header files VC10
I'm going to get a book that uses Xerces C++. I'm currently using VS 2010 ultimate, so the program doesn't miss any features. I've downloaded the precompiled binaries for windows x86 VC10. My question is what do I have to do to my environmental variables and files to be able to have Visual studio import the header file...
Right click on your project -> Properties -> C/C++ -> General -> Additional Include Directories Include the path of Xerces include files. For Lib Properties Linker -> General -> Additional Library Directories Include the path of Xerces lib files. In Linker -> General -> Input -> Additional dependencies Add the libs ...
4,294,927
4,442,927
c++ call class's function of another class's function
i hope this makes sense for you, i get confused. let me know if there is a simpler way: double A::a(double(b::*bb)()) { b.init(); return (b->*bb)(); } void A::run(); { cout<< a(b.b1); cout<< a(b.b2); } class A { B b; void run(); double a(double(b::*bb)()); }; class B { void init(); double b1(); d...
It doesn't make sense. This makes sense though: class B // <- class B definition comes first { void init(); double b1(); double b2(); }; class A { B b; void run(); double a(double(B::*bb)()); // <- B instead of b }; double A::a(double(B::*bb)()) // <- B instead of b { b.init(); return (b->*bb)(); } v...
4,295,117
4,297,948
Pointer to member conversion
I just found the following paragraphs in c++03 standard draft relevant to pointer to member conversion. 4.11/2 Pointer to member conversions An rvalue of type “pointer to member of B of type cv T,” where B is a class type, can be converted to an rvalue of type “pointer to member of D of type cv T,” where D is a derive...
The code you wrote is perfectly valid. There's nothing wrong with it (aside from the fact that Derived::a is private). It is well-formed and the behavior is defined (so far). As the quoted portion of the standard says, it is perfectly legal to upcast member pointers using an explicit static_cast, which is exactly what ...
4,295,324
4,295,457
C++ assign vector pointer
I have this vector. vector<CXFileEntity>* menu;// CXFileEntity is class When i try load an x file to it there is a problem. Here is my code menu->at(0)=menu->at(0).LoadXFile(CUtility::GetTheCurrentDirectory()+"\\meshes\\Menu\\background.x", 1, menu->at(0), d3dx->d3ddev); menu->at(1)=menu->at(1).LoadXFile(CUtility::G...
LoadXFile() seems to be returning a pointer, ie. CXFileEntity * while the vector only accepts objects of CXFileEntity. I don't understand your design. You have instances of CXFileEntity in your std::vector. Then you access those instances and call LoadXFile() on them... which return pointers to CXFileEntity, which you'...
4,295,332
4,295,353
How many characters can fit in a C++ string?
I need to store in a variable, kilobytes or even megabytes of plain text, so I want to know how many characters can fit in a standard string (aka std::string plus string library).
std::string has the member function max_size() which returns the maximum length of a std::string in that implementation.
4,295,346
4,295,365
Variable created on the heap, 2 pointers pointing to same variable have different addresses?
I just learned the difference between the stack and the heap. After creating a function which will dynamically allocate memory on the heap for me, I return the pointer and display (in and out of the function) the address and value of each pointer. The values are the same, which I expected, but the addresses to the same...
You are reporting the address of the pointers, not the address that the pointer is pointing to. Of course the address of the pointer will be different for pTemp and pHeap2; these are different pointers that happen to be pointing to the same address in memory. Remove the & prefixing pTemp and pHeap2 to see the results t...
4,295,352
4,295,479
C++ "error: multiple types in one declaration" and "error: expected initializer before 'KeyType'"
When I run the following code... #ifndef KEYEDITEM_H_INCLUDED #define KEYEDITEM_H_INCLUDED #include <string> typedef std::string KeyType; class KeyedItem { public: KeyedItem() {} KeyedItem(const KeyType& keyValue) : searchKey(keyValue) {} KeyType getKey() const { return searchKey;...
Solved... Turns out I was missing a header include in my main.
4,295,432
4,295,495
Typedef function pointer?
I'm learning how to dynamically load DLL's but what I don't understand is this line typedef void (*FunctionFunc)(); I have a few questions. If someone is able to answer them I would be grateful. Why is typedef used? The syntax looks odd; after void should there not be a function name or something? It looks like an an...
typedef is a language construct that associates a name to a type. You use it the same way you would use the original type, for instance typedef int myinteger; typedef char *mystring; typedef void (*myfunc)(); using them like myinteger i; // is equivalent to int i; mystring s; // is the same as char *s; my...
4,295,488
4,295,532
How do I create a C++ library in VS 2008?
I am working in VS 2008 and have several C++ projects and want to build my own library to share across projects. The first project is called "Project 1". I created the library as a separate Win 32 project, and chose DLL. I added a reference in Project 1 to the library using "Add reference". I also added an "Additional ...
If the projects are in separate folders, you may have you do something like: #include "../libproject/Library.h"
4,295,529
4,295,587
Detecting EOF in C++ from a file redirected to STDIN
Executing the command: ./program < input.txt with the following code checking: string input; while(cin) { getline(cin, input); } The above code seems to generate an extra getline() call where input is empty. This happens regardless of whether or not there's a \n on the last line of input.txt.
@Jacob had the correct solution but deleted his answer for some reason. Here's what's going on in your loop: cin is checked for any of the failure bits (BADBIT, FAILBIT) cin reports no problem because nothing has yet been read from the file. getline is called which detects end of file, setting the EOF bit and FAILBIT....
4,295,661
4,296,545
How to prevent instantiation of a C++ template class method when a specific condition is met?
I'm currently writing a generic vector template class (the geometric entity, not the container) with the following signature... template&lt typename T, unsigned N &gt class vector {...} ... where T is an arithmetic type and N, the dimension. I would like to define the cross product as an overload of operator ^ (locat...
The proximal cause of the error message is that, according to the docs, "The second argument of lazy_enable_if must be a class type that defines a nested type named type whenever the first parameter (the condition) is true." That's clearly not satisfied here (unless your vector type just happens to contain typedef som...
4,295,681
4,295,704
Evil samples of subtly broken C++ code
I need some samples of bad C++ code that will illustrate violation of good practices. I wanted to come up with my own examples, but I am having a hard time coming up with examples that are not contrived, and where a trap is not immediately obvious (it's harder than it seems). Examples would be something like: Not defi...
The most vexing parse is an amazingly counterintuitive result of the way C++ parses things like this: // Declares a function called "myVector" that returns a std::vector<float>. std::vector<float> myVector(); // Does NOT declare an instance of std::vector<float> called "myVector" // Declares a function called "foo" t...
4,295,695
4,295,709
How can I include a data file at compile time?
Possible Duplicate: C/C++, can you #include a file into a string literal? I have several data files that will be used as a strings in my program. I want to avoid the extra overhead of reading in the files at runtime. I could hard code them all in but I much prefer to keep them in separate files. I could included t...
Make a script to convert the files into code. Have this script executed as part of your build process. The original files are what you check into source control and edit.
4,295,808
4,296,155
Protection against cracking - specifically ways to make a program harder to decompile
I'm making a commercial product that will have a client and server side. The client is totally dependent on the server , just to make it harder to crack/pirate . Problem is , even so there is a chance that someone will reverse engineer the protocol and make their own server. I've thought about encrypting the connectio...
Read how Skype did it: The binary is decrypted into memory at startup. The import table is overwritten. The startup code is erased from memory. Code integrity checks bust most debuggers: in random points in the code it computes a checksum of some other chunk of code and uses the checksum for an indirect jump to the ne...
4,295,851
4,296,289
Presenting sent and received chat messages in "order" for both the client and server
I have a simple (very simple:) ) client and server which can send text messages over TCP, It's flawed because I don't know how to listen to the messages and print them on the screen as well as send messages at the same time (for both client and server). Also I have difficulty in presenting all the sent and received mes...
The core problem is how to wait for incoming messages and for user input at the same time. (Once you'll be able to do it, the "synchronization" will follow naturally, since messages will be displayed as they are sent or received). The solution to this problem is using select. select can wait for input on several file h...
4,295,911
4,295,924
cannot pass a subclass pointer to a function when the function need a reference to the parent pointer, why?
class Parent{ }; class Child: public Parent { } void Func(Parent*& param) { } Child* c=new Child; Func(c); //error
This is by design. c is not a Parent*, it is a Child*. To turn it into a Parent*, an implicit conversion is required. This implicit conversion generates a temporary Parent* object (at least conceptually), and a non-const reference cannot be bound to a temporary object.
4,296,090
4,296,118
Some Problems while learning STL
I am using g++ in CodeBlocks IDE in Ubuntu. I am new to STL and some part of C++. Q1: //answered std::istream_iterator< std::string > begin ( dictionaryFile ); std::istream_iterator< std::string > end; std::vector< std::string> dictionary; std::copy ( begin, end, std::back_inserter ( dictionary ) ); is correct, but wh...
std::istream_iterator< std::string > end(); C++ interpretes this as declaration of function which name is end return value type is std::istream_iterator< std::string > and argument list is empty. Thats why you get such error. In C++ to make any object by calling default constructor of its class you just must do this ty...
4,296,180
4,296,322
Regarding representation of Josephus puzzle using arrays
Algorithms by Robert Sedwick, It was mentioned that linked list can be represented using Arrays, at following link http://flylib.com/books/en/3.55.1.34/1/ Fig 3.8, here if 5 is removed from my understanding next 4 should be changed to index 6 as val 5 is removed, as we go thourgh the figure at item 4 is removed next...
the index is zero-based as opposed to the value itself (letters would be better values). Example of removing the value 5: before removing, next index of the node with value 4 is 4, which points to value 5; after removing, next index is changed to 5, pointing to value 6 (next changed from 4 to 5). Or, using the prefix...
4,296,273
4,296,966
Embedding Python in C++ - Running Python from C++ program
thank you both for a quick response :) i think i understood what you suggest but it is not exactly what i need. To be honest i don't know what is the right technique to do what i need. I have a program which during it's run sometimes needs to call python in order to preform some tasks. I need a function that calls pyt...
First of all, make sure you read and understand svenor's answer if you're trying to build anything more complicated than a trivial interpreter. However, in this particular case you can replace the line int boostOutputStr = extract<int>(result); with std::string boostOutputStr = extract<std::string>(str(result...
4,296,276
4,296,300
C++ : Cannot declare field to be of abstract type
I get this error on compile -> cannot declare field M1::sc to be of abstract type I1 because the following virtual functions are pure within I1. Please help. class I1 { public: virtual void a(int dir) = 0; virtual void b() = 0; virtual void c() = 0; void a(int dir) { ...
Abstract classes can't be instantiated, but you're asking the compiler to do just that by embedding an instance of I1 into every instance of M1. You can work around that by slightly changing your design and embedding a pointer (or a smart pointer, if you can use those) to an instance of I1 instead: class M1 : public G1...
4,296,281
4,296,290
How Can I Pass a Member Function to a Function Pointer?
class Child; class Parent { public: void (*funcPointer)(); void (*funcPointer2)(Parent* _this); void (Child::*funcPointer3)(); }; class Child: public Parent { public: void TestFunc(){ } void Do(){ Parent p; p.funcPointer=TestFunc; // error, '=': cannot convert from 'void (__thiscall Child::* )(voi...
You can't. You either pass a pointer to a static method or Parent has to accept also a pointer to the object. You might want to look at boost::bind and boost::function for that: #include <boost/bind.hpp> #include <boost/function.hpp> struct Y { void say(void) { std::cout << "hallo!";} boost::function<void()> g...
4,296,339
4,296,790
C++ #include external function issue
I'm a real beginner and I'm programming in C++ using Visual Studio. I've a simple cpp code that recalls some functions written in a .c and .h file. I included that file by means of #include directive and the IDE "sees" the function. When I compile, I get this Error 7 error LNK2019: unresolved external symbol _IMUsendAc...
If you get an error in Visual Studio you can actually google for the error code and you will get pretty extensive information for that. In this case, googling LNK2019 gives this MSDN page as first hit, which also provides some examples on how you get the error. Your vendor should have provided some .lib files for you (...
4,296,439
4,296,467
Dynamic Linking C++ DLL ... What am I doing wrong?
I've been trying to create a DLL and link the DLL to my program but every time I try my program can't find the function. The DLL loads fine but the function cant be found. Program: #include <iostream> #include <windows.h> using namespace std; typedef void (*HelloPtr)(); int main() { HelloPtr hello; HINSTANCE...
You need to put your DLL code in an extern "C" block, otherwise the compiler will mangle the names of all functions. Take a look at this question for further info: C++ DLL Export: Decorated/Mangled names
4,296,464
53,208,880
Visualize QT Signals and Slots
I'm currently working with a lot of custom widgets which provide different signals and slots for communicating with each other. E.g. there is one widget which establishes a network connection and then emits a signal to the others which then change their state from disabled to enabled. I now want to visualize how these ...
I know the question is dated but maybe it will help someone. KDAB created a tool to visualize signals and slots and to do a lot of other debugging on Qt applications. You can get it here: https://www.kdab.com/development-resources/qt-tools/gammaray/
4,296,494
4,296,526
User defined data type that uses another user defined data type as a parameter
I am having trouble getting the compiler to accept my below defined user data type (Term) that accepts another user data type (Rational) as a parameter. Any suggestions on how to make this work would be great! #ifndef _TERM_H #define _TERM_H #include "Rational.h" using namespace std; class Term { public: //co...
First, change the definition of coefficient to this: const Rational& coefficient; Then change the constructor to this: Term (const Rational& a, const int& b) : coefficient (a), exponent (b) { }
4,296,774
4,296,792
copy n symbols to container
Possible Duplicate: How to read arbitrary number of values using std::copy? Hello. I'm reading nums from file. I do it with std::copy copy(istream_iterator<int>(input_file), istream_iterator<int>(), back_inserter(first)); But this function copy only whole file, although I want to copy only N symbols...
SGI's STL reference is quite good. The second argument needs to be the number of items you want to read. Update (After changing your initial post, which used copy_n) You can use a simple loop to do what you want, as in template <typename Input, typename Output> Output copy_n (Input i, size_t N, Output o) { for (;...
4,296,785
4,296,823
Impossible expected class-name before ‘{’ token error to solve
It's a well known issue this damn error expected class-name before ‘{’ token Well, despite my hard working and googling, I could not solve this error. Sorry. This is my last shore. In ui.cpp of a project of mine I do: #include "wfqueue_proxy_factory.hpp" OK, this raises this stupid error in my compiler: In file incl...
Just a wild guess: Your error says that in class WFQueueManagerProxy : public WFQueue { // This is the problem (line 42) //... }; there must be a class name before {. Therefore I assume that the compiler doesn't know that WFQueue is a class. Are you sure that its definition is included? I mean, maybe in wfqueue.hpp t...
4,296,813
4,296,862
Deploying application developed using C++
I have an application that uses wxWidgets as a the UI framework and compiled using Visual Studio 2010 on Windows 7 machine. I am linking wxWidgets statically. My application also uses a C dll for processing. Now I am trying to run this application on another freshly installed machine (Win7). This doesn't have a develo...
It is trying to use a debug only DLL on a machine that doesn't have it. Your problem arises from the fact that msvcr100d.dll is a debug only dll indicated by the trailing d. Thus you are NOT using /MT you are actually using /MDd. If you used /MT then it would nto try and load that DLL ... So in answer to your question...
4,296,831
4,296,851
My little program compiles, but it prints out giberish?
Okay. . . pointers are driving me bonkers!!! Okay, now that I have that out of my system, the following code compiles, however, it does not print out the correct output. What am I doing wrong? #ifndef _TERM_H #define _TERM_H class Term { public: //constructors Term( Rational &a, const int &b) ...
Why is print //print the Term void print()const { cout << &Term::coefficient << " x^" << &Term::exponent << endl; } Instead of just void print() const { cout << coefficient << " x^" << exponent << end; } ?
4,296,924
4,296,938
How to order functions in C++?
I'm not sure how to order my functions in C++. In C, I simply placed a function that uses another function below that function, as closely as possible - that's pretty common. Like this: void bar() { } void foo() { bar(); } However, in C++, there are several types of functions: Free functions Private member funct...
It's possible. You have to use forward declaration. Declare a function before defining it, and other functions will see it without problem even if they are defined before. So, you should be able to do this in C++: void bar(); // forward declaration; note that function bar isn't defined yet void foo() { bar(); /...
4,297,095
4,298,148
Practical Use of Zero-Length Bitfields
I am not totally sure about C, but C++ allows unnamed bit-fields of 0 length. For example: struct X { int : 0; }; Question one: What practical uses of this can you think of? Question two: What real-world practical uses (if any) are you aware of? Edited the example after ice-crime's answer Edit: OK, thanks to th...
You use a zero-length bitfield as a hacky way to get your compiler to lay out a structure to match some external requirement, be it another compiler's or architecture's notion of the layout (cross-platform data structures, such as in a binary file format) or a bit-level standard's requirements (network packets or instr...
4,297,233
4,297,298
C++ Can we create overrides of class functions?
To have like 3 functions with same names like: bool VideoEncoder::AddFrame(AVFrame* frame, const char* soundBuffer, int soundBufferSize) bool VideoEncoder::AddFrame( const char* soundBuffer, int soundBufferSize) bool VideoEncoder::AddFrame(AVFrame* frame) Can we?
Not only is it possible, but it is a very useful feature of C++ called function overloading. Also note that functions who share the same name must differ by more than their only return type, but they may differ in their const-ness only (and this is incredibly frequent and useful) : struct A { void doSomething() ...
4,297,391
4,297,860
C++ compiler won't recognize a member function and a type
Today it's the day of strange things.... Got a stupid hpp file and another stupid cpp file trying to implement a stupid class. Here they are: // HPP #ifndef _WFQUEUE_MANAGER_PROXY_HPP_ #define _WFQUEUE_MANAGER_PROXY_HPP_ #include <iostream> #include <string> #include "workflow.hpp" #include "wfqueue.hpp" //--------...
OK, this was the error.... I also compiled headers.. many gch were so created.... g++ didn't update those precompiled headers and got an old code... that's why it was indifferent to any change I did... sorry for disturb you guys... thanks a lot for your help
4,297,480
4,297,756
One Definition Rule: Can corresponding entities have different names?
I read and reread the relevant clauses about ODR in the C++ standard, but this question still remains open to me. The standard says that the definition of an inline function shall appear in every translation unit in which it is used, and the definitions shall be identical in a sense which is described in almost a page....
Identifier is a kind of token, each identifier is a separate token, so yes, you need to have the same identifier to respect the ODR. It can make a difference in a compiler which detect this (someone ready to build an example for como with exported template? it can detect some violation of the ODR). Then there is a dif...
4,297,496
4,297,545
Conversion of Function Pointer Non-Type Template Parameter to Type Template Parameters
The following example code compiles under gcc and works as I would hope. It allows me to instantiate an object with a function definition as a template parameter, but then the class is able to use the different types in the function as if they were passed individually as type template parameters. template<class FuncSi...
Why shouldn't it work? The instantiation matches the specialization, which extracts the component types (char and int) of the compound type (a function, char(int)) as Type1 and Type2. By the way, you don't have a non-type template parameter. A function type is a type. If you had a non-type template parameter, then it w...
4,297,822
4,297,849
Copy a substring from const char* to std::string
Would there be any copy function available that allows a substring to std::string? Example - const char *c = "This is a test string message"; I want to copy substring "test" to std::string.
You can use a std::string iterator constructor to initialize it with a substring of a C string e.g.: const char *sourceString = "Hello world!"; std::string testString(sourceString + 1, sourceString + 4);
4,298,266
4,299,244
Generating sample audio data: trying to generate music plate crackling sound? (C++)
I try such code: static float shift = 0.0; double amplitude = 1000000 * pow(10, 1 / 400.0); for (int i = 0; i < nSampleSize / nBlockAlign; i ++) { // Sound :) Buffer [i] = amplitude * sin((shift + i)) / 100; } shift = shift + amplitude * nSampleSize / nBlockAlign ; return (char *)Buffer; It generally give co...
sin() will return a value between -1 and 1, so when multiplied with a number x the result will vary between -x and x. If x is bigger or smaller than the numeric bounds of the array type it will cause artifacts. Buffer is a char array it seems, which is not really common for an audiobuffer. Usually they are ints or d...
4,298,298
4,298,303
C++ function problem,
I have this code, but when I compile it with Borland Turbo C++, Turbo C++ say: Error filename.cpp 13: Call of nonfunction in function main() my code is: #include <iostream.h> int reload (int yes, int no) { int reload; cout << yes << no; cin >> reload; return reload; } main () { int ...
int a, av = 1, reload = 1; You named a variable reload which hides the reload() function. The compiler thinks you are trying to "call" the int reload variable, thus "call of nonfunction". Rename either the function or the variable.
4,298,314
4,298,333
Correct allocate and free memory for arrays in C++
I'm dealing with dynamic arrays. The function empty_matrix() creates a new array, representing a matrix. delete_matrix() frees all memory, allocated for the matrix. Do I get a memory leak in function example() if I call add(add(a, b), c)? What will happen to the memory allocated in the function add(...)? Do I have to ...
What you should do is use Object Orientation/RAII. Your data member of matrix class should be private, and memory for it should be allocated in the constructor, and freed in the destructor. This way, you won't have to worry about memory leaks. For example... class matrix { public: typedef int element_type; ...
4,298,331
4,298,362
EXE or DLL Image base address
Is there a way in C++/windows to get the exe/DLL image base address? thanks :)
If you load the binary into your own process you can use GetModuleHandle. It returns a HMODULE, but that is the same as HINSTANCE and the base address. If you want to know what base address the binary prefers you should read the PE header. See here and look for the ImageBase field in IMAGE_OPTIONAL_HEADER. Edit: GetMod...
4,298,403
4,298,450
C++ writing an assign procedure for a container
I have a container, a class, and I would like to provide it with a method assign like STL do. class myclass { public: //... template < typename InputIterator > void assign(InputIterator first, InputIterator last); // ... private: // ... std::vector<int> mystlcont; // ... }; template < typename Inp...
What you have is not your own container, but rather container wrapper. But I see only one problem with your code: your myclass::assign definition does not have a return type specified. This code actually works for me: #include <vector> #include <algorithm> #include <iostream> class MyWrapper { public: temp...
4,298,410
4,298,455
Allocating C-style string on the Heap
guys, I need a little technical help. I'm working in C++, don't have much experience working in it but know the language somewhat. I need to use a C-style string (char array) but I need to allocate it on the heap. If you look at this very simple piece of code: #include <iostream> using namespace std; char* getText() {...
Use a std::string, from the <string> header. Then use its .c_str() member function. Then you don't have to care about allocation and deallocation: it takes care of it for you, correctly. Cheers & hth.,
4,298,473
4,298,497
How to init parent's member?
class Parent { public: int member; Parent(): member(0) { } }; class Child: public Parent { public: Child(): member(1) //error { } };
class Parent { public: int member; Parent(int m = 0): member(m) // constructor takes an argument, default as 0 { } }; class Child: public Parent { public: Child(): Parent(1) // refer to super class's constructor here { } };
4,298,508
4,298,586
C++ to C#: Pointers & Arrays
Below is a Win32 Console App procedure that demonstrates the dependence of various pointers on an array. A change to the values in the original array (model) by for example uncommenting the lines marked '// uncomment ...' results in a change to the output. My question is how do I get or mimic this behaviour in a C# m...
You can do the same thing in C# without unsafe code: struct ArrayPointer<T> { private T[] array; private int offset; public ArrayPointer(T[] array) : this(array, 0) { } private ArrayPointer(T[] array, int offset) { Debug.Assert(array != null); Debug.Assert(offset >= 0); ...
4,298,543
4,298,572
How do I return a char from a function that uses winsock to recv from socket?
My application is crashing when I try printing the buffer. Otherwise, it works fine. This is the code: irc.h class IRC { public: void sockconnect(char * hName, int portNum); void sockwrite(char* sendbuf); char sockread...
If you want to print the first character use printf ("Buffer: %c\n",buffer); If you want to print the whole then sockread should return the whole buffer, not the first character. For that you will need to return the address of the first element of the buffer which in this case should already be dynamically allocated. ...
4,298,809
4,298,819
returning a reference to temporary
I understand that it's illegal to return a reference to a temporary, but here's my problem: const stringSet & Target::dirList( const dirType type ) const { switch( type ) { case SOURCE_DIR: return m_sourceDirs; case HEADER_DIR: return m_headerDirs; case RESOURCE_D...
Keep a default set as a member too... and return a reference to it. That is of course if the default case is theoretically possible. If it is not, throw an exception and don't return anything. default: throw invalid_argument_exception();
4,298,834
4,299,471
Passing by reference 3-Dim Fixed length array
Can anyone hint on how to pass by reference an array of the kind int array[2][3][4]; so that I may save his pointer in order to use and modify the array? Like, if I were speaking about a single integer: // Scope 1 int a = 3; increment(&a); // End Scope 1 // Scope 2 int *pa; void increment(int *tpa) { pa = tpa; *...
Thanks to everyone who participated in this! sskuce provided a very good solution, taking advantage of a "container". I had thought about this but didn't really like the extra stuff. I realized after a little jumbling that James McNellis had given the answer all along. So... here's the solution I prefer with no contain...
4,298,875
4,300,868
Can C++ templates check if a function has been overloaded for a given type?
I have a template function that I expect to be templatized for different types at different places. The problem is that I would like to know at compile time if there is an specialization for the given type to generate in 2 different ways another template. template<typename T> bool tobool(const T&){ throw Exception("Can...
As a (somewhat ugly and brittle) workaround, you could require specialization of a struct rather than a function and include a class constant to indicate whether the struct has been specialized: template <typename T> struct ToBool { static bool tobool(const T&); static const bool specialized = false; }; Another...
4,298,881
4,315,933
Receive mic input and process
I am writing a small program in C++ that receives mic input and does some simple live audio processing. I have been looking around and the only things I have been able to find that work on Linux are PortAudio, QAudioInput, and fmod. I am trying to stay away from any super low level programming and use a minimal amount ...
Check out JUCE. Juce will build on many platforms. JUCE does a lot more than just audio, but it was made with audio programmers in mind. Look at he JUCE demo application and then just chop up the source code from the audio demo to suit your needs. The API documentation is really good also. The abstraction from the low ...
4,298,961
4,298,985
Abolish include-files in C++
Suppose i have the following code (literally) in a C++ source file: // #include <iostream> // superfluous, commented-out using std::cout; using std::endl; int main() { cout << "Hello World" << endl; return 0; } I can compile this code even though #include <iostream> is commented-out: g++ -include my_cpp_std_l...
The only thing "wrong" is that you are relying upon a compiler-specific command-line flag to make the files compilable. You'd need to do something different if not using GCC. Most compilers probably do provide an equivalent feature, but it is best to write portable source code rather than to unnecessarily rely on feat...
4,298,981
4,298,998
Dev-C++ compile errors
I want to use "Dev-C++" for compile c++ codes. So I download and install it, and write this code: #include <iostream.h> main () { cout << "124"; } but when I compiled it, it said: In file included from E:/Dev-Cpp/include/c++/3.4.2/backward/iostream.h:31, from [myfile path]\Untitled1.cpp:1: ...
First, make sure you write out the full definition of main, including the int return type. Leaving out the return type is an old, antiquated practice which doesn't fly these days. Second, in the new-style headers—the ones missing the .h extension—the standard library is under the std namespace. There are two ways to ma...
4,299,191
4,299,214
How to initialize a vector in the constructor of a class
How could I initialize a two dimensional vector in the contstructor of a class with zero values? This won't work: #include <vector> using namespace std; class matrix { public: typedef int element_type; matrix(int dim):data(dim, vector<int>(dim, 0)) { } private: vector<vector<element_type>> data; }; Do I hav...
Update: OP's code is now valid from C++11 onward. Original answer for earlier versions of C++: You need to write it like this: vector< vector<element_type> > data; because >> is otherwise parsed as stream operator, which is invalid here. And: No, you do not need to free this in the destructor, because you aren't crea...
4,299,276
4,299,745
array size dependent on sizeof() a struct field
I have a global include file which contains a set of structures. Somewhere in my program, I have a class that contains a member array. The number of elements in this array is dependent on the size of a specific field in a specific struct. I want to make it so that the array size will get automatically updated if t...
Here is one possible answer: #include <iostream> struct A { int a; int b; int c; }; bool items[sizeof(reinterpret_cast<A *>(0)->b)]; int main() { std::cout << sizeof(reinterpret_cast<A *>(0)->b) << ","; std::cout << sizeof(items) << std::endl; return 0; }
4,299,298
4,299,331
How to allocate memory for an object I don't know the real type of? C++
I want to store an object of some derived class as a property of another object. The problem for me is to know the size of the object to be stored, as it can be any derived class of a given base class. I cannot just allocate memory for the base class' object, right, as it's smaller. I suppose, typeof operator would als...
Well, first of all, since you pass in your BaseA by value, and not by reference or pointer, you DO know the type; it's BaseA. BaseB was copied into a BaseA and that BaseA copy is sent to the function. Any extra data in BaseB is not contained in instanceAX. This is called "slicing". But, to answer your question, you ...
4,299,314
4,390,537
Member template in local class
Given the following code: void f() { class A { template <typename T> void g() {} }; } g++ 4.4 (and also g++-4.6 -std=gnu++0x) complains: "invalid declaration of member template in local class". Apparently local classes are not allowed to have template members. What is the purpose of this l...
The purpose of this limitation? Just a guess, but: you may use the template class/template member function only within the enclosing function. Therefore you already know all used types within the function and hence can directly specify the used types (for several types, of course, the template variant would have save...
4,299,322
4,299,580
Error related to const
In Visual Studio 2008, the following code will build successfully: void Foo (int x);//Prototype void Foo(const int x)//Implementation { } However, this will generate an error (unresolved external symbol) during linking: void Foo (int x);//Prototype void Foo(const int x)//Implementation { } void Bar() { int x ...
It's because you have a broken compiler. Broken compilers can choose their behavior themselfs. I know some compilers have this broken handling of that case. Look on MSDN about a manual that documents that broken behavior. It works fine with compliant (non-broken in this regard) compilers.
4,299,326
4,299,677
How can I use Boost.Test in a CMake based project?
My project uses CMake as its build system, and I want it to execute my Boost.Test test cases. How can I achieve that? In Boost.Build, I could do it as follows: import testing ; use-project /my_lib : ../src ; unit-test my_test : my_test.cpp /my_lib boost_unit_test_framework ; l...
CMake itself is just a build system; CTest is a just test runner that is integrated with CMake. Neither is a unit test framework; that job can be done by Boost.Test or googletest. To use a Boost.Test-based unit test program in a CMake project, you'd first have CMake build and link your unit test binary, using add_execu...
4,299,376
4,299,479
C++ Singleton Vs static methods
Possible Duplicate: C++ singleton vs completely static object Hi, why should I prefer a singleton over static class methods. MoneyPrinter::addJob(PrinterJob &job); or MoneyPrinter::getInstance().addJob(PrinterJob &job); Is it only a matter of style? What do you use? Why? ps. I know that sigletons are not th...
A singleton gives you control over when the class is instantiated and as DeadMG points out if you want to instantiate it. A static class is less controllable and is instantiated before main is called. The sequence in which classes is instantiated can sometimes be critical when the singleton depends on some other class ...
4,299,405
4,299,450
Access Vector in class with "class[i]" like class would be the vector
Is it possible to implement a function to access a private data vector foo in a class via class[i][j]? This should call the inner function of the vector foo[i][j].
A simple solution is to implement operator[] so it "peels off" only the first dimension: #include <cstdlib> class MyClass { std::vector<std::vector<int> > foo; public: // grant write access std::vector<int>& operator[](size_t index) { return foo[index]; } // grant read access con...
4,299,439
4,419,939
C++11 vector push_back ambiguous
Consider the following code: #include <vector> struct S { int a; double b; }; int main() { std::vector<S> v; v.push_back({3, 4.5}); } g++ 4.4 complains that the call to push_back() is ambiguous: error: call of overloaded ‘push_back(<brace-enclosed initializer list>)’ is ambiguous note: candidates are: void s...
With the most recent draft (n3225), your code is in fact ambiguous. The candidates that are in vector will be void push_back(const S& x); void push_back(S&& x); The question is: Is a list-initialization of a const S& a better/worse conversion sequence than a list-initialization of a S&&? Overload resolution will make ...
4,299,493
4,299,505
Display a QMessageBox from a QThread
I want to display a message box from a separate thread, however, I get this error: QThread: Destroyed while thread is still running Can anyone explain how to display a message box from a thread?
Emit a signal. Since you cannot do UI stuff in a Qthread, instead send your message as an argument of your signal. signal decalaration in your qthread: signals: void write2SysStatus(QString theMessage); emitting the signal from the qthread: emit write2SysStatus("Some status"); slot declaration/definition in QMainW...
4,299,605
4,299,695
Problem with std::string::find()
I'm in trouble using std::string::find(). I read strings from console through the following code: 50 while(command.find(exitString) != 0) { 51 std::cout << "$ "; 52 getline(std::cin, command); 53 54 doSwitch(command); 55 } and then I "switch" on them, through the following function...
You might be expecting that find returns zero when it found the string, kind of like the way strcmp works. But that's not how find works. find returns the first index of the found string, which might be zero, or might be something else if the string you're looking for is prepended with spaces, other strings, etc. If...
4,299,701
4,299,715
C++ Iterator dereference and prefix increment/decrement style? Is *--Iter ok style wise?
In coding with C++ iterators if you wanted to get the previous value to what an iterator points to would you write: *--Iter or would you think it better to add parentheses like so: *(--Iter) ?
It doesn't matter as far as program correctness is concerned. But I always express this as *(--Iter) because this is more self-documenting and easier to understand to human beings than *--Iter.
4,299,729
4,300,065
Why don't people indent C++ access specifiers/case statements?
I often see stuff like this: class SomeClass { public: void someMethod(); private: int someMember; }; This seems totally unnatural to me (the same applies to case-statements when using switch). I expected something like this, when I started using C++ (it's been a long time since then, but I am still wondering)...
Increasing indentation normally reflects entry to a new nested scope, whereas both access specifiers and switch case statements don't vary the scope (the same is true of labels generally). Access specifiers can be optional in that you may start implementing a class or struct and have all members only need the implied ...
4,300,173
4,300,256
reading and writing a vector of structs to file
I've read a few posts on Stack Overflow and a number of other site about writing vectors to files. I've implemented what I feel is working, but I'm having some troubles. One of the data members in the struct is a class string, and when reading the vector back in, that data is lost. Also, after writing the first iter...
In C++, memory can not generally be directly read and written to disk directly like that. In particular, your struct element contains a string, which is a non-POD data type, and therefore cannot be directly accessed. A thought experiment might help clarify this. Your code assumes that all your element values are the sa...
4,300,330
4,300,483
Qmake and Make using separate folders for sources and headers
I'm going mad on this stupid problem. I've a tree like this: src |--- sources |--- one.cpp |--- two.cpp |--- sources.pro |--- headers |--- one.h |--- two.hpp |--- headers.pro |--- src.pro I tried EVERYTHING to make it look in both the folders, but somehow I can't get it ...
It's been awhile since I've had to use qmake (long live CMake!), but can't you just set the INCLUDEPATH variable in your .pro file, i.e., do something like: INCLUDEPATH += ./sources INCLUDEPATH += ./headers INCLUDEPATH += ../utils/include # (etc, etc.) Then just point the entry in your SOURCES var at the sources folde...
4,300,420
4,300,567
recursive definition in CPP
I meet a problem like this: UPDATE class A { public: A(){} int i; B b; }; class B { public: B(){} int j; A a; }; When I define it in one .h file, it would give an error. I think the problem is the recursive definition. But could someone help me how to solve such issue? error C2146: syntax err...
This is not possible verbatim in C++. The explanation is that the compiler needs full, not just forward, declaration of a class to be able to use it as a member of another class. It simply needs the size of a class object. The workaround in C++ (and in C) is to use a pointer or a reference as a member of one of the cla...
4,300,465
4,300,500
C++ How to make a GUI in directx?
I have few questions on this Subjects. I created a class for buttons, the class has problem. Problem is: 1. I wanna create function to be called if button is clicked, the problem is that every single button gonna do different thing if it was clicked. So i don't know how i can create function that will do different th...
Use inheritance/polymorphism: The base class is GUIButtons, and every new individual button derives from that base clase: class MyButton : public GUIButtons { ... } And then the functionality for a click comes in a virtual method onClick() or whatever. More detail: class GUIButtons { ... \\ lots of stuff virtua...
4,300,514
4,300,624
using an istream_iterator to read in a vector of structs from keyboard?
Is it possible to use an istream_iterator<customstruct> to insert into a vector by reading from stdin from a human? The struct has multiple data types contained in it. Does it make any sense to do so or would prompting for each piece of data separately be the better approach? I only ask this because I was asked to d...
Anything can be read by istream_iterator if there is an overload of "operator >>", and it's copyable and assignable. Although it's possible, I don't think it's a good way of reading, since user have to manually type an EOF sequence to make the iterator reach an end. To avoid the use of EOF, you can let the user input a...
4,300,737
4,300,752
Global vs. Member functions
I've been playing around with c++ lately and wondered why there were so many global functions. Then I started thinking about programming in c# and how member functions are stored, so I guess my question is if I have a: public class Foo { public void Bar() { ... } } and then I do something silly like adding 1,000,...
Nope, there is only one instance. All instances of a class point to an object that contains all the instance methods that take an implicit first parameter affectionately called this. When you invoke an instance method on an instance the this pointer for that instance is passed as the first parameter to that method. Tha...
4,300,869
4,300,934
Prevent copying when initializing an non-const object from a const reference
I am a little confused right now regarding C++ reference semantics. Suppose I have a class that returns a const reference: class foo { private: std::map<int, int> stuff; public: const std::map<int, int>& getStuff() { return stuff; } }; And I use it as follows: foo f; const std::map<int, int>& s...
Short answer: no, you can't prevent it. The client can't modify the original, but if you give the client read-access to the map, then the client is responsible for not doing stupid things with the information; the class can't possibly prevent that. Longer answer: maybe, but not really. If you really want to make copyin...
4,300,995
4,304,666
Modify volume gain on audio sample buffer
I want to increase a volume on buffer with voice data. The point is I'm using DirectSound and I have one primary and one secondary buffer - all streams mixing is done by hand. In a voice chat all participants can have independent volume levels. I multiply each stream data by a value (gain) and sum it to one buffer. Eve...
For every sample - convert it to some larger data type - if you have 16 bit signed samples, they originally fit in SHORT - extract it from the stream, then cast to local double, then multiply, then CLIP, then cast back to SHORT. It MUST work that way... I can even provide code sample if needed. EDIT: Your picture is e...
4,301,011
4,302,174
Creating an Xml string in C++
I have an array of strings.I want to make an xml string using the values of the array elements. I will pass this xml string as a parameter to a .net webservice. Can anybody please tell me how do I make an xml string in c++? What library do I have to use and what are the methods? The xml structure: <xml> <DeviceName><...
I use cmarkup, pretty simple to use. http://www.firstobject.com/dn_markup.htm
4,301,259
4,339,438
Differences in length in TagLib# (C#) and TagLib (C++)
I am currently in the process of moving my C# application over to Qt / C++. I'm running into problems with lengths from TagLib. I find it odd that TagLib# returns audio durations in milliseconds, while TagLib returns its (incorrect) durations in seconds. TagLib just returns zero for the length values, while TagLib# rem...
Hi there is a patch to taglib that calculate the length in milliseconds, this guy added a method (lengthMilliseconds()) that return the length in milliseconds, maybe that could be useful for you: http://web.archiveorange.com/archive/v/sF3Pjr01lSQjsqjrAC7L
4,301,375
4,301,448
Not exactly converts from double to int - seems problem is in CPU instructions
I got surprised when I debugged my code. Here I provide example code #include<QMessageBox> #include<iostream> #include<math.h> #include<QApplication> using namespace std; class MyMessageBox: public QMessageBox { public: MyMessageBox(string message,QWidget *parent=0) : QMessageBox( ...
Your problem is that the result of your floating-point operation is 9999.9999999... so int(...) is int(9999.9999999...) which, of course, is 9999. Since floating point operations are rarely exact, you must not write your code to expect them to be. In this case, you could use a rounding function. As was pointed out in t...
4,301,396
4,301,511
OpenMP Thread count question
So Im doing a bit of Parallel Programming of the Trapezoidal Rule for my OS class, this is a homework question but im not looking for source code. after a bit of research I decided to use each thread to compute a subinterval. using: g = (b-a)/n; integral += (func(a) + func(b))/2.0; # pragma omp parallel for sched...
Your professor is correct: OpenMP will choose an optimum number of threads by default, which is usually the number of cores. You don't need to worry about the number of threads being exactly divisible by N: OpenMP will automatically distribute the iterations among the threads, and if they're not evenly divisible, one t...
4,301,457
4,301,823
C++ array of char pass to functions
Hey guys, I need help with this one. I'm writing a really basic program that will generate a character array firstName[amount][size]. using this it will then pass it to the function addPerson and that will modify the value. Here's my current code void deletePerson(int &, int, char[], char[], char[], char[]); int main()...
I think you should really avoid using char arrays and char pointers. Use std::vector and std::string instead, they will save you a lot of trouble. std::vector<std::string> is probably all you need. Or even better, you should bundle firstName, lastName, email and phone together in a structure. struct Person { std::s...