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
6,354,951
6,355,113
Is Display unique for every window in X11?
I'm a beginner to X11, i created a class just to create,show and destroy the window. In the Constructor i create variables for Window,Display etc, But do i need to create Display for every Window o create or shall i use the same Display for all windows? class Widget { public: Widget(); void createWidget(int x,int y,i...
That depends on where you want to create the window. If it is on the same system - same GPU, then yes, you can use the same Display.
6,355,028
6,366,872
C++ Java wrapper construction with JNI
I am currently writting a JNI wrapper for a C++ class and I'm not sure if what I have done so far is the most correct way. As I understand it, it is not possible to declare a Java constructor native, so I ended up writing something like: package log; public class Logger { private long internalPtr = 0; private...
That is the way I have always implemented native classes which wrap arround a C/C++ object. I think writing a native constructor could be a bit of a pain, so have never tried. For de-allocation, you do a simolar thing. Write a C/C++ function which de-allocates the memory for your C/C++ object, and then call this from t...
6,355,029
6,355,043
Arrays/pointers in C: copying without knowing underlying type
Let's say I've got a unsigned char pointer (uchar* from now on) to the beginning of an array of type T different from uchar. Knowing the size of this array and that it is continuous (created using malloc), is it possible to copy it to another array without knowing the type T? How can I access it byte per byte? Thanks
You can make a shallow copy of everything with a simple memcpy or memmove, but you better be sure that the array elements are no class objects that contain any pointers. Or more precisely, make sure they are PODs.
6,355,196
6,480,056
Use gdb to call a printDebug method
I have a class with a printDebug method. Its not used anywhere in the code but I would like to use it when I am debugging with gdb (using call). This is basically to print the contents of the object in a nicely formatted way, for instance I may have a vector of sets. What is the g++ option to use for this? I have trie...
If you have a method that is not used anywhere on the code gcc smart features can identify this and ignore it while compiling your application. That's why when you display the symbols (using nm) of the application that method doesn't show on the results. However, if you want to force that method to be compiled anyway y...
6,355,330
6,355,581
C++ code translation and explanation
I have the following c++ code snippet. I have a basic understanding of c++ code.Please correct my explanation of the following code where ever necessary: for (p = q->prnmsk, s = savedx->msk, j = sizeof(q->prnmsk); j && !(*p & *s); j--, p++, s++); What does it contain: q is char *q(as declared) is type ...
Some (like me) might think that following is more readable int j; for (j = 0; j < sizeof(q->prnmsk); ++j) { if ((q->prnmsk[j] & savedx->msk[j]) != 0) break; } which would mean that q->prnmsk and savedx->msk are iterated to find the first occurence of where bit-anding both is not zero. if j equals sizeof(q->prnmsk),...
6,355,334
6,355,714
Implementing General Tree
I came across the following code and despite some help from others, I am still having trouble understanding it. This code is supposed to implement a General Tree. Single_List and Single_Node classes are also available for use in implementation. template <class Object> class General_tree { ...
The tree object is really a node in the tree, where children points to the nodes at the next level, which will have pointers to their children, etc. Together they form a subtree (or the whole tree, if it is the root node).
6,355,438
6,356,071
Overloading operator delete in a base class
From the C++ standard (ISO/IEC 14882:2003(E)), §12.5.4, about overloading operator delete: If a delete-expression begins with a unary :: operator, the deallocation function's name is looked up in global scope. Otherwise, if the delete-expression is used to deallocate a class object whose static type has a virtual dest...
I don't know much about VC++ ABI, but the Itanium ABI is well documented. Looking up at the name mangling scheme, one see: <ctor-dtor-name> ::= C1 # complete object constructor ::= C2 # base object constructor ::= C3 # complete object allocating constructor ...
6,355,774
6,356,129
Where should I be putting my function code
I am writing a RPG game and am finding there is far more background functionality that the user ever sees. I have a battle class. this holds instances of the enemies the background picture and deals with choosing which enemies are in the battle. I have developed several global functions to calculate and display gauges...
I think you should have a look on the finite state machines which usually the base mechanism for games. That would give you a broad idea how your code should be organized in order to keep everything easily editable and easy to browse. I think your choice of class extraction is kind of weird. The "battle" in it self doe...
6,355,816
6,356,051
Understand Crash Dump from Visual C++ App
UPDATE Thanks to feedback below I was able to home in on ADPlus.vbs, which is part of the debugging tools for Windows. Don't forget to set up _NT_SYMBOL_PATH before you run it. Using this we've been able to see much more clearly in to the application with far greater clarity than we ever have using the regular dumps pr...
DbgBreakPoint -- Looks to me like you broke execution using a remote debugger. If you didn't then I have seen DbgBreakPoint show up when you have code pages (Edit: I meant page heap) turned on (you should know if you did this) and there was a detection of invalid memory access.
6,355,942
6,355,997
How can I insert a multidimensional array in another array(int not char)
I want an example showing how I can insert an 2D int array in another 1D int array? I am in a dead end here.
// 2D int array typedef std::vector<std::vector<int> > twoDarray; // 1D array **of 2D arrays, not ints ** std::vector<twoDarray> oneDarray; // Instance of 2D array oneDarray myOneDArray; // Instance of 2D array twoDarray myTwoDArray; // Add this in. myOneDArray.push_back(myTwoDArray);
6,356,222
6,356,623
How big is a heap frame in Visual C++
In Visual C++, if I use new to create an object on the heap, how much extra space is taken for the heap frame header and padding, specifically in release code? I'd expect an int to say how much space was available in the block, and another perhaps to say how much of that space was currently in use, and that frame size...
Hackety-hack: int* p = new int; int* q = new int; std::cout << (char*)q - (char*)p << std::endl; Yes I know, technically undefined behavior, but I think it should answer the question :)
6,356,303
6,356,509
Passing Function name as arguments to a function
Is it possible to pass the name of a function(say A) as an argument to another function (say B), and then call function A from function B. That is the function name will be stored in a variable in B, and using it call the function whose name is in the variable. For Example in C++ sort function the first and second argu...
You can introduce a template parameter (here Pred) for "anything that is callable with two parameters": template <typename Iter, typename Pred> void mysort(Iter begin, Iter end, Pred predicate) { --end; // ... if (predicate(*begin, *end)) { // ... } // ... } Then you can...
6,356,334
6,356,663
OpenGL - problem in rotating - Qt
I am trying to learn||Code openGL in Qt. I made one application which shows two figures. One is a triangle "A", and the other triangle "B" is just the same as "A" except it got rotated -90 degree about the z-Axis(z axis is perpendicular to the computer screen). Now, the problem is rotation makes the change in the dimen...
I can't say for certain what is going on, but I do see that there may be some problems. gluPerspective(45.0f,width()/height(),10.0f,100.0f); If width and height both return integers (and they probably do), then dividing one by the other will result in an integer. That's not going to give you a proper aspect ratio. Cas...
6,356,632
6,356,709
Why do i get this message in Microsoft Visual C++ 2010 Express
#include <iostream> using namespace std; int main() { bool x = true; bool y = false; if(x) { cout << "if works"; } if(y==false) { cout << "else works"; } int z; cin >> z; } This is a small code that I compiled using Microsoft Visual C++ 2010 Express Edition. When I compile I get a messa...
You probably hit F5. Which is: run in debug, NOT compile (at least not in C++/VS terms). It detects that your code is different from the one used to compile your binaries. If you have this code: int main() { cout << "test"; return 0; } And you compile, that's version 1 of your exe. Then you change the code...
6,356,941
6,357,018
How to enable a specific gcc warnings for a specific directory or file?
Possible Duplicate: Selectively disable GCC warnings for only part of a translation unit? How to enable a specific gcc warnings for a specific directory or file ? I want to enable -Wsign-conversion for my own files not for any other system headers
This line should do it: (see here) #pragma GCC diagnostic warning "-Wsign-conversion" Put it in the affected files or in a header that is included in all you files
6,356,994
6,357,240
namelookup with Unqualified name : C++0x draft n3290
A point from the ISO C++ Draft n3290 : 3.4.0 2nd point A name “looked up in the context of an expression” is looked up as an unqualified name in the scope where the expression is found. Would someone please explain this statement with an example?
It says that the scope which contains the expression will be searched for the name. i.e. namespace foo { struct bar { void foobar() { do_something(); } }; } if you have this code the name do_something will be searched in the scope of foobar, bar, foo and in the global scope (and not in other namesp...
6,357,038
6,357,114
Is multiplication and division using shift operators in C actually faster?
Multiplication and division can be achieved using bit operators, for example i*2 = i<<1 i*3 = (i<<1) + i; i*10 = (i<<3) + (i<<1) and so on. Is it actually faster to use say (i<<3)+(i<<1) to multiply with 10 than using i*10 directly? Is there any sort of input that can't be multiplied or divided in this way?
Short answer: Not likely. Long answer: Your compiler has an optimizer in it that knows how to multiply as quickly as your target processor architecture is capable. Your best bet is to tell the compiler your intent clearly (i.e. i*2 rather than i << 1) and let it decide what the fastest assembly/machine code sequence ...
6,357,154
6,357,265
Destruction order of the main thread and the use of pthread_key_create
I was wondering about the use of pthread_key_create while passing in a destructor function. I wanted to have something like this: static ComplexObject foo; void workoncomplex(void *) { foo.dosomestuff(); } static pthread_key_t pthreadkey; void function_called_by_threads() { pthread_key_create(&pthreadkey, wo...
The destructor function is not called on application exit. It is only called when a thread exits. If you exit the main thread with pthread_exit() then the destructor function will be called, but the application is not yet being shut down so it is safe to use the static variables. If you call exit() or return from main...
6,357,394
6,387,783
c++ call specific template constructor of template class
Is it possible to call a constructor with template arguments if the class is a template too? #include <stdio.h> #include <iostream> template <class A> struct Class { template <class B> Class(B arg) { std::cout << arg << std::endl; } }; int main() { Class<int> c<float>(1.0f); Class<int>* ptr = new Class<int><f...
edit2: but what happens to constructor template arguments that are not part of the constructor arguments itself ? Then you can pass-in an argument that has it encoded template<typename T> struct encodeType { }; struct A { template<typename T, typename U> A(T t, encodeType<U>) { } }; A a(1, encodeType<float>());...
6,357,900
6,369,779
Utility for analysing symbols in a library file
I'm having some problems with a large static library (.lib) file, and am suspecting code bloat from indiscriminate use of template classes. I want to analyse the symbols in the library to confirm which are making up the bulk of the file size. When I link my executable against this library, the resulting output is much ...
I found one (SymbolSort) that works really well, gives me exactly what I need:
6,357,903
6,358,193
History of support for default first parameter in C++ function
As this question reiterates, a default parameter can be provided for the first argument in a C++ function. So the following void foo(int a, int b=5); // good void foo(int a=5, int b=5); // used to be an error void foo(int a=5); // used to be an error However, I remember learning early on in my programming education ...
The only official c++ standard of 1998 has them, so technically speaking the standard has always had them. Before this, even the often considered first quasi-standard for C++, the Bjarne Stroustrup book The C++ Programming Language mentions them. It was one of the first things Strousrup added to ANSI C when developing ...
6,358,054
6,358,471
How do C++ programs work?
To make my question more clear, I'd like to mention the reason for the question:- I want to know if my program will be OS-dependent. For example, I thought C++ was OS-independent; Now I know if I program in Visual C++, my programs will be Windows dependent. So, I would like to know how to make sure my program isn't O...
C++, the language is OS and architecture independent. The compiled executable file, however, is OS dependent. If you don't use Visual C++ specific features or any "syntax bugs" associated with it, I am pretty sure your program can run on other platforms once you compile it there. As to your question how C++ works, I wo...
6,358,068
6,358,120
Can you use a function local class as predicate to find_if?
Is it possible to use a local class as a predicate to std::find_if? #include <algorithm> struct Cont { char* foo() { struct Query { Query(unsigned column) : m_column(column) {} bool operator()(char c) { return ...; ...
In C++03 this is not allowed. Local(not nested) classes cannot be template parameters. In C++11 it is allowed. Some terminology tip: A nested class is a class that is defined withing the scope of another class, e.g. class A {class B{};}; A local class is class defined in function scope(as in your example)
6,358,073
6,358,511
Which compiler between Visual Studio 10 and GCC 4.5 is correct regarding operator overloading and argument-dependendent lookup?
I have the following code: class Foo; class Bar; class Bar { public: Bar() { } Bar(Foo &foo) { } }; class Foo { public: Foo() { } Foo(Foo &foo) { } Foo(const Bar &bar) { } }; Bar operator >> (const Bar &left, const Bar &right) { return Bar(); } Foo a; Foo b; Foo c = a >> b; ...
This should work: Foo c(a >> b); This initialization syntax: Foo c = a >> b; Is interpreted as Foo c(Foo(a >> b)); is copy-initialization and requires an accessible copy-constructor which accepts const Foo&. From section [dcl.init] of the standard (wording from C++0x): The form of initialization (using parentheses...
6,358,104
6,358,163
How fast are lambda functions in GCC
Having toyed around a bit with C++0x Lambda Expression in G++, I was wondering as to how well the performance will be in general/specific situations compared to alternative ways without using lambda functions. Does anybody know a more or less comprehensive discussion of lambda expression performance or situations in w...
If you consider the old-school way of defining a struct with operator () as an alternative way then there isn't gonna be any difference because lambdas are pretty much equivalent to that. Just syntactically more convenient. Let's wait for a more complete answer...
6,358,153
6,358,189
Simple C++ string formatting under GCC
I am converting someone else's C++ library to work under GCC (Xcode). What is the basic method for string formatting? EDIT: I see the original phrasing of my question caused a lot of confusion, not to mention some amusement. What I need to do is replace certain string formatting functions in their library. They have ...
You can use streams: std::stringstream ss; ss << somedouble << someint;
6,358,184
6,396,924
Do some VTK Library files contain errors?
I managed to install vtk on my ubuntu. I'm using code::Blocks as compiler, working in c++. I also compiled and ran some of the examples given in the vtk examples web page. But at some examples, for example when vtkChart.h is involved, my compiler gives errors which refer to the content of the file. These header files ...
First, Code::Blocks is not a compiler, it's an IDE that uses GCC or MSVC as a compiler. So, this should be more generic to GCC itself (since you appear to be using Ubuntu). Your problem looks like a configuration error. ../VTK-build/VTK-5.6/VTK/Charts/vtkChart.h|40|error: ‘vtkContextItem’ does not name a type| is the k...
6,358,478
6,364,266
Nesting unnamed namespaces
Is there a functional difference between these two nested usages of unnamed namespaces: namespace A { namespace { void foo() {/*...*/} }} and namespace { namespace A { void foo() {/*...*/} }} As far as I see it, both foos will get an internal unique identifier per compilation unit and can be accessed with A::foo ...
Exactly as you typed, there is no difference. You can, of course, add declarations in the first level of namespace to booth examples and then it will be a difference. namespace A { int i; // Accessed globally in this file as "A::i". namespace { void foo() {/*...*/} }} namespace { int i; // A...
6,358,546
6,358,603
What MSVC++ 2008 Express Editon compiler does and doesn't
I've been wondering if the msvc++ 2008 compiler takes care of multiple header includes of the same file, considering this example: main.cpp #include "header.h" #include "header.h" Will the compiler include this file multiple times or just one? (I'm aware I can use the #ifndef "trick" to prevent this from happening) Al...
No, the compiler (or, more accurately, the pre-processor) doesn't take care of this "automatically". Not in Visual C++ 2008, or in any other version. And you really wouldn't want it to. There are two standard ways of going about this. You should choose one of them. The first is known as include guards. That's the "#ifn...
6,358,783
6,358,820
Calling pthread_create inside a member function?
I created a widget.h file containing the declartions of pthread_function and I wanted to call it in a member function destroyWidget of that class Widget in widget.cpp. but always shows an error. I'll show the .cpp and .h file. widget.h file class Widget { public: Widget(); void createWidget(int x,int y,int w,int h); v...
The problem is that pthread_create is a C-style function; you need to give it a pointer-to-function. Widget::destroyWidget() is a pointer-to-member-function. (Remember that non-static member functions always have an implied this argument, which pthread_create doesn't know how to provide.) See the answers to this ques...
6,358,882
6,359,067
Template constructor weirdness
Possible Duplicate: Can the template parameters of a constructor be explicitly specified? following up on my previous question, (I found this situation in edit 2) Laid out simple in code: #include <iostream> struct Printer { Printer() { std::cout << "secret code" << std::endl; } }; template <class A> struct Clas...
No, it's not possible. There is no syntax with which you can provide explicit template parameters to a constructor template. You can only provide explicit template parameters for the class template as a whole. The following text from [temp.arg.explicit] (2003 wording, 14.8.1/5) covers the scenario. Though the clause is...
6,359,184
6,360,234
Qt QDockWidget(floating) minimizes when my MainWindow minimizes
How can I minimize my QMainWindow without also minimizing my QDockWidget that I have undocked and is floating? What I want to do, is take a small window of my GUI to monitor the rest of the MainWindow. The MainWindow does not to be on the screen, all I want to see is the DockWidget while it is floating.
A floating QDockWidget is automatically minimized when its parent QMainWindow is minimized. There is nothing you can do about that. You may have to change your QDockWidget into a QDialog (or some other QWidget) with parent = 0.
6,359,278
6,359,754
VS2010SP1: Project always out of date when debugging
I experienced this problem in VS2010 before, and solved it looking at this SO question. However, now that I upgraded my VS to SP1, it appeared again. I tried to solve it the same way, enabling C++ projects logging and using DebugView. But I can't get to see any output in DebugView, no matter what I do. I also tried rai...
Is it possible you were testing with the date in the future and saved a source file in the future? While clean/rebuild all should fix this, VS seems to go batty and stay there until I resave the file in the present. Another last-ditch thing that sometimes solves these problems that works 'like a reboot' if you have ju...
6,359,418
6,359,452
Why is initializing an integer in C++ to 010 different from initializing it to 10?
When an integer is initialized as int a = 010, a is actually set to 8, but for int a = 10, a is set to 10. Can anyone tell me why a is not set to 10 for int a = 010?
Because it's interpreting 010 as a number in octal format. And in a base-8 system, the number 10 is equal to the number 8 in base-10 (our standard counting system). More generally, in the world of C++, prefixing an integer literal with 0 specifies an octal literal, so the compiler is behaving exactly as expected.
6,359,505
6,434,146
Qt and Multipart HTTP
I have a Qt app that needs to use a multi-part http request. From looking around on the net I see that multi part requests are being added to Qt4.8 but that is of no use to me now. I really need the functionality now. I don't really know how HTTP works so rolling my own solution is beyond me. If anyone could point m...
Tuck Design has published a class for handling multipart file uploads that only needs Qt 4.5.
6,359,584
6,359,626
Is there a way to call automatically function when class created by new
I need to call function whenever class is created using new. Currently I need to write something like this: MyClass *myClassPointer = new MyClass(...); myFunction(myClassPointer); When MyClass is created as local object myFunction cannot be called. MyClass have at lest 2 constructors with different arguments. Is there...
Use a class factory rather than calling new directly. The factory can call myFunction before returning the pointer.
6,359,592
6,359,642
C++ auto detection of template arguments?
I am trying to define a recursive construct like a task farming. Here, I am trying for two operands which recursively can work for any number of operands as it can nest itself. template <typename T1, typename T2> class Farm { private: T1 *task1; T2 *task2; public: // save them so that I can use them whe...
Before C++17, classes/constructors didn't autodetect types like functions do. You need to write a wrapper function to create your class. This is done as follows and called the Object Generator pattern. (thanks @Itjax!) template <typename T1, typename T2> Farm<T1, T2> makeFarm(T1* a, T2* b) { return Farm<T1,T2>(a,...
6,359,629
6,359,836
Union hack for endian testing and byte swapping
For a union, writing to one member and reading from other member (except for char array) is UB. //snippet 1(testing for endianess): union { int i; char c[sizeof(int)]; } x; x.i = 1; // writing to i if(x.c[0] == 1) // reading from c[0] { printf("little-endian\n"); } else...
I believe it (snippet 1) is technically not allowed, but most compilers allow it anyway because people use this kind of code. GCC even documents that it is supported. You will have problems on some machines where sizeof(int) == 1, and possibly on some that are neither big endian nor little endian. Either use available ...
6,359,649
6,360,861
The cost of forking threads: How do I determine the minimum vector size to justify multithreading
I am attempting to calculate dot products of many vector pairs. Each dot product can use multiple threads, but no two or more dot products should be done concurrently due to data dependance. What is the minimum vector size here that might justify multithreading? I realize that no one is going to be able to give me an e...
The only real way to know is to try it out (and remember that the results may vary depending on what hardware you are running on). You could write a profiling routine to automate the test, and (if you find it's worth it to do so) even have that routine run briefly at your program's startup, to find out what the optimu...
6,359,661
6,359,919
OCCI - Connecting to a remote database
I'm fairly new to Oracle. I'm trying to connect to a remote Oracle database using OCCI. All the examples i've found up this point have been for connecting to a local database. Could someone please point me in the right direction and let me know where i can find an example connection to get me past this point? Thanks, M...
createConnection( "name", "passwrd", "string") "string" stands either for the connection name that is resolved with the Oracle "tnsnames.ora" file which should be located in your ORACLE_HOME(Oracle install dir)\NETWORK\ADMIN directory or for a connection string like below Code: connection_name = (DESCRIPTION = ...
6,360,163
6,360,501
Inline ASM jmp to new memory
So I would like to load a set of assembly instructions from a file, and execute those instructions. OR I would like to load already compiled machine code again from a file (non-exe) My Thoughts: So far I've learned enough inline asm to work with c/c++ variables easily. asm volatile ( "mov %1, %%ecx;" // ye...
This sounds like you kind of want some JIT compiling of some x86 assembly in a separate file? I might have misunderstood, when you say 'memory space', your encapsulating a very broad term. I assume you don't mean that you want to compile it with a specific set of assembly but be able to interchange the assembly instru...
6,360,221
6,380,039
How to compile QtDeclarative without QtXmlPatterns, QtSvg and QtSql
I want to slim my application down (again). QtDeclarative depends on QtXmlPatterns, QtSvg and QtSql which I don’t use at all, so I’d like to compile the library without them. Has someone altered source-file for QtDeclarative (or a clue how to do this) ?
You should be able to configure Qt as follows: ./configure -no-xmlpatterns -no-svg The parts in QtDeclarative that depend on these modules will be automatically disabled. Removal of QtXmlPatterns will for example just result in the unavailability of XmlListModel, since that is based on XQuery. This would not be a modi...
6,360,411
6,376,895
Why does OpenCV emit "Bad flag in unknown function" for this code?
I have been trying to get a real basic video player working using the Open CV API. Everything seems to run smoothly until the end of a video clip, then i get this error: OpenCV Error: Bad flag in unknown function, file ........\ocv\opencv\modules\core\src\array.cpp This creates a break in the code at imshow("video", ...
VideoCapture video("test.MOV"); // open the video file int main(int, char**) { if(!video.isOpened()) // check if we succeeded { return -1; } } Try put the VideoCapture instantiation inside main. int main(){ VideoCapture video("test.MOV"); // open the video file ... }
6,361,094
6,361,128
C++ Compilation Error Non Class Type
In below I am getting error as error: request for member 'get_id' in '* it', which is of non-class type 'const Param* const'. What is the problem with below piece of code bool SomeParams::is_default(int _id) const { vector<const Param*> param_list; bool is_default = false; if( get_default_param...
Enclose *it in parenthesis: (*it)->get_id().
6,361,104
6,361,990
Obtain Regular Expressions from file
I would like to be able to obtain a list of regular expressions from a file. I have tried reading the regexes into a char * or a std::string which works without a problem. However, converting them/using them as regexes proves to be fruitless, since there is a mismatch of data types. Most online resources I have found ...
Simply load file to some char* (I assume that you can do this) and pass it to regex.
6,361,257
7,919,818
Design: Separating Data and its view
There's some legacy code that I would like to refactor. There is some data obtained through reading some registers. This data is represented in csv and xml files. The current way is dirty. There's no separation between data and the view (XML, CSV). So actually, for each format, the collection of data is done each time....
I recommend using the Strategy Pattern for this. The TimeStamp and PreTimeStamp declarations would be pure virtual (ie. virtual void Timestamp() =0) in the 'Dumper' interface and the Dumper_A and Dumper_B implementations would be declared virtual. The class loading the data would then be assigned the appropriate implem...
6,361,342
6,366,125
Objective-C++ / Cocoa attempt to create a window with button, not working?
I'm supposed to create a c++ class with c++ methods, that are made of objective-c and use cocoa, but now I've ran into a problem, and simply can't figure it out, cause I'm pretty new at objective-c. Also the point is that I should be able to create windows and buttons from c++. So when ever I build and run this program...
[[this contentView] addSubView: button]; As you suspect, that is causing your problem. "This" is not referring to the window; it refers to the class itself. (Remember, your class is not a subclass of an NSWindow) One option is to declare your NSWindow in the header so it can be used globally. So make your header: #ifnd...
6,361,553
6,362,057
How to implement own function to std::vector?
I would like to add a function that returns the .size() value as an integer, instead of unsigned integer. Edit: Due to comments, i explain more detailed: I have code: int something = 3; if(arr.size() > something) Which will produce compiler warning, and i dislike adding (int) to every place where i have this. So, a s...
As a rule, in C and C++ you should never use an unsigned type such as size_t to restrict the domain. That's because (1) these languages provide no range checking, and (2) they do provide unreasonable implicit promotions. No range checking means (1) no advantage, and unreasonable implicit promotions means (2) very undes...
6,361,574
6,361,619
C++0x variadic template pass by reference
I want to use variadic template feature for my application but I don't want the objects to be passed by value (as objects are quite complex in my case). I want to pass them by reference (not as pointers). void func() { } template<typename Function1, typename... FurtherFunctions> void func(Function1 f1, FurtherFunctio...
Just say: template <typename ...Args> int myfunction(Args & ... args) { /* ... */ } Same for const Args & ... args, Args && ... args etc.
6,362,043
6,362,936
Reverse map a functional relation(c++)
I am using a simple function (y(x)), and I want to generate an x value from a certain y value. While typically reverse mapping does not give a single x value, I am using the maximum from my y values. This means that there will be a unique x value for the y value I input(the maximum). I don't understand how to code t...
If you don't need interpolation, only exact reverse lookup, then it's relatively straighforward: std::map<YType, XType> lookup; // (code to read the file goes here) // for each x { YType y = f(x); if ((lookup.count(y) == 0) || (lookup[y] < x)) { lookup[y] = x; } // } Then your reverse lookup is jus...
6,362,206
6,362,251
What's the smart way to use C++ new operator with a function?
This is a long one. I have a function that loads some image data from disk. I've tried this with three different methods, one of which doesn't work, and I'm wondering what the smartest method is. Method 1: I used to have it set up so that the loaded data was an argument to the function, which seemed to require allocati...
Answer to question 2 In order to make it work you must pass a reference to the pointer unsigned char * & image Otherwise you allocate memory and the COPY of the passed pointer points to it. The original pointer object doesn't change. Answer to question 1 Ever heard of smart pointers? Smart pointers can be used to mani...
6,362,324
6,362,830
Can a static member of a class as the same type as the class it is member of in C++
lets say I have class : foo { public: static const foo Invalidfoo; foo(); foo(int, string); private: int number; std::string name; }; Is it safe or prone to any problem? EDIT : I want to use this to have an invalid object to return as a reference to launch errors.
It is perfectly legal, but the following is better: class foo: { public: static const& foo Invalidfoo() { static foo Invalidfoo_; return Invalidfoo_; } private: foo(); }; This way you are guaranteed that the object is initialized the first time it is used. Edit: But no matter how you...
6,362,517
6,363,095
How to disable drag/drop when a dialog box is open
I am working on a large application and am adding some drag/drop functionality to it. Specifically, I am allowing the user to drag and drop a file into the main window to open the file. The problem is that the drag/drop operation is still allowed to happen when the main window is displaying a dialog box (for example, ...
I'm not sure how things work in C#, so let me know if this answer is incorrect. In C++ MFC, the main window is disabled when a dialog is displayed. You can test to see if the main window is disabled and ignore the drop if so. private void MyDragDrop(object sender, DragEventArgs e) { if (CanFocus) MessageBox...
6,362,653
7,408,965
Mass storage device removal policy
I'm working on a hardware device that exposes itself as a Mass Storage device over USB. When I plug in a typical USB key it gets attached in device manager as a Mass Storage device with the corresponding disk's removal policy set to Quick Removal. When I plug in my device the removal policy however is set to "Better Pe...
Sorry for answering my own question but upon furthur investigation these are the result: Linux USB storage gadget driver does not support MODE_SELECT: http://lxr.free-electrons.com/source/drivers/usb/gadget/file_storage.c?v=2.6.35 (Lines 1881 to 1889) This causes Windows to behave as described above. Returning without ...
6,362,719
6,362,799
Pointing to static arrays, but dereferencing without the use of *
I have a series of NX objects (e.g., a static bool array of dimension [NX][N1][N2] in the example below). I would like to loop over these objects. At each iteration, an object called 'A' is to function as a surrogate for the corresponding element 'B[x]' in the series. However, the code inside the loop is legacy code, s...
You can define a reference to a two-dimensional array inside the for loop: bool (&A)[N1][N2] = B[x]; Now A[i][j] is equivalent to B[x][i][j]. Note that you cannot move the definition of A outside the for loop, because references have to be initialized when they are defined, and they cannot be rebound later. If you nee...
6,362,956
6,363,034
Filter UDP packets from a particular IP
I have a program which transmits(broadcasts) and receives UDP packets simultaneously using pthreads. What I want to do is to remove packets which have been sent by me. How do I do that? My receive code currently looks as follows: void *receive_thread_body(void *arg) { long msg = 0; while(msg<500) { fd_set so...
You need to fill the last two parameters of the recvfrom call - that will be the sender's address. Then compare it to the list of your own addresses for matches (see here for example for relevant info). This method is agnostic to the way of sending - you can use it on connection or connection-less sockets, and of cours...
6,362,995
6,363,042
C++ Refactoring - Move method to implementation file
I have lots of header files with long method implementation inside. Is there An automatic way of doing that? One-by-one can take a lot of time... Thanks.
If you are using Visual Studio, there's an add-in called Visual Assist that can help you to do this. I'm using it at work and it is really helpful. Unfortunately this add-in is not free but you can install the trial to do your stuff and test it.
6,363,088
6,363,805
How to manually place data in a boost::asio::streambuf to later read it with a std::istream?
I am trying to use a std::istream as data source. I want to place custom binary data in the istream's stream buffer so it can later be retrieved from the istream. I have read about boost::asio::streambuf and how it is used to do exactly what I want but using a socket as data source instead of an in-memory buffer, which...
You can easily send any std stream, so you can also you a stringstream. You can write binary data to your stringstream (it is just a byte array, effectively). A few samples: boost::asio::streambuf request; std::ostream request_stream(&request); request_stream.write(&binarydata_buf, sizeof(binarydata_buf)); // or use s...
6,363,156
6,363,219
Developing mixed C++ and C++/CLI for CGI and WPF
This is related to this question, but given the direction of the answers, I figured it would be better to ask this question separately. I need to develop a class library that can be both used in CGI (long story, sigh) and referenced by c#. Since both deployments must be able to be updated simultaneously, I'm having a l...
You could use swig to generate c# wrappers to the library then it can then be referenced from c# without any problems.
6,363,209
6,363,363
Is there a better/more efficient way to store then large arrays
I'm opening a text file which can hold anywhere between 100 and 50,000 dataFrames, and assigning each line of the txt file to a dataFrame, where a dataFrame is defined as follows: typedef struct { double x; double y; double z; double azimuth; double elevation; double roll; } dataFrame; I need the data to b...
If you only need fast indexing and you know the number of elements (lineCount) up front, nothing beats a good old array.* If you also want fast appending, use a dynamic array such as std::vector or QVector. If you want fast searching for an item by key, check out std::set, std::map, QSet, QHash. [*] Almost nothing. Pos...
6,363,247
6,363,467
What is a complex data type and an Imaginary data type in C++?
I know what imaginary and complex numbers are in the math world but what about in C++, what are data types of complex and imaginary. In addition, I see data types such as _Imaginary and _Complex. What is the difference and what are complex and imaginary data types?
_Imaginary and _Complex are keywords in the C99 language standard used for defining imaginary and complex floating-point variable types; they are not part of the C++ language. They are not data types in and of themselves -- they modify the float, double and long double types. For example: float _Imaginary x; // ...
6,363,437
6,364,312
Is it possible to use OpenCV to accurately detect water in a sewage pipe?
I'm looking into image-recognition of water in sewage pipes for a future project. I have been looking into OpenCV, and it looks like it is very good at recognizing where objects start, and stop. However, is there anything in OpenCV that would not only allow for separating water from pipe, but also identifying which is ...
Since you say you have video that may help you define what is "water" and what is "pipe". The "pipe" is the part of the image stream that doesn't move (as seen from a fixed camera), while the "water" part is the one with larger differences in successive frames (due to illumination and flow). BTW, must your sensor reall...
6,363,439
6,363,496
Weird error casting an LPVOID to an int pointer
I get this weird error: MyView:OnInitialUpdate() { int* my_int; *(my_int) = 1; AfxBeginThread(MyThread,my_int); } UINT MyThread(LPVOID param) { int* my_int = reinterpret_cast<int*>(param); message(*(my_int)); return 0; } void message(int value) { CString txt; txt.Format(_T("%d"),...
int* my_int; *(my_int) = 1; This is undefined behavior. You didn't initialize my_int, so you're dereferencing an invalid pointer. Instead, create a member x in your MyView class, and change to: int* my_int = &x;
6,363,719
6,363,962
RapidXML reading from file - what is wrong here?
What's the difference between these two methods of reading an input file? 1) Using 'ifstream.get()' and 2) Using a vector<char> with ifstreambuf_iterator<char> (less understood by me!) (other than the obvious answer of having nifty vector methods to work with) The input file is XML, and as you see below, immediately ...
The only difference between the two is that the vector version works correctly and the char array version causes undefined behavior when the file is longer than 65535 characters (it writes the \0 to the 65535th or 65536th position, which are out-of-bounds). Another problem that is common to both versions, is that you r...
6,364,233
6,364,340
c++ hashtable where keys are strings and values are vectors of strings
I have a large collection of unique strings (about 500k). Each string is associated with a vector of strings. I'm currently storing this data in a map<string, vector<string> > and it's working fine. However I'd like the look-up into the map to be faster than log(n). Under these constrained circumstances how can I...
You can create a hashtable with boost::unordered_map, std::tr1::unordered_map or (on C++0x compilers) std::unordered_map. That takes almost zero effort. Google sparsehash may be faster still and tends to take less memory. (Deletion can be a pain, but it seems you won't need that.) If the code is still not fast enough, ...
6,364,365
6,364,568
Can different optimization levels lead to functionally different code?
I am curious about the liberties that a compiler has when optimizing. Let's limit this question to GCC and C/C++ (any version, any flavour of standard): Is it possible to write code which behaves differently depending on which optimization level it was compiled with? The example I have in mind is printing different bit...
The portion of the C++ standard that applies is §1.9 "Program execution". It reads, in part: conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below. ... A conforming implementation executing a well-formed program shall produce the same observable be...
6,364,852
6,365,003
C++, xcode and terminal, absolute basics
I have an Xcode project, just the standard hello world app that comes with xcode for c++. I hit build and run, it runs, it completes, I see nothing. How do I get this to open up in terminal?
shift+cmd+Y brings up the debugger and console. You can see all the output there. Alternatively, you can choose View from the menu bar and click 'Show Debug Area'. This debug area shows the output of your program just like Terminal.
6,364,886
6,364,949
error: expected ‘}’ at end of input
I have the following code: #include <libubuntuone-1.0/u1-music-store.h> #include <libsyncdaemon-1.0/libsyncdaemon/syncdaemon-authentication.h> #include <libsyncdaemon-1.0/libsyncdaemon/syncdaemon-credentials.h> #include <libsyncdaemon-1.0/libsyncdaemon/syncdaemon-daemon.h> static void get_credentials (U1MusicStore *mu...
In case of such errors it is good idea to localize error. You can do it simply, by commenting blocks of code. In this example you can comment body get_credentials function and check what will happen. Also good idea to paste empty line at the end of source code file.
6,365,014
6,365,131
Fixing #includes <> for GCC (Code::Blocks)
I am working with some code that was written for a different compiler/linker, and it is including files like this: #include <Engine/Graphics/Sprite.h> from anywhere in the project. The project contains such a file at that path (from the root of the project), but when I build I get the file not found error. How can I f...
I'm not quite sure if I understand your explanation, what do you mean with "from the root of the project". But well... When you use the #include directive with <> what your are telling the compiler is to look for the the file on the Directories you include with -I option. In code blocks go to Project->Build Options->S...
6,365,342
6,665,959
QtCreator debugger only shows assembler
I am using linux, and I am using QTCreator. For some reason, when I run a program in debug mode, when it faults, I get an assembler dump. There is no stack trace or anything Legibile. I think my debugger used to show me this stuff, but somehow has gotten switched off. What can I do to get it back? Thanks
The real problem is that my make and qmake commands were swapped, so the make file was getting built with -O3 instead of -g, even when the program was compiled in debug mode from Qt.
6,365,347
6,365,660
Quaternion rotation not working
I'm just starting to work with Quaternions, but I'm having some annoying difficulties getting a simple FPS camera to work properly using Quaternions. Basically, whenever I try to move the mouse, a triangle I draw on the screen goes crazy and moves off and on the screen faster than I can see. The movement keys (wsad) ar...
From the looks of it, you're progressively accumulating your rotation every tick (rotation_ = quatRotation * rotation_;), which makes sense at first because all you're doing is adjusting the rotation slightly and so it should be safe to tack on another degree or two of rotation to what's already there, right? However, ...
6,365,414
6,365,540
Using sessions with fastcgi++
I am having problems using sessions with fastcgi++ 2 beta. Here is my code : #include <fastcgi++/http.hpp> #include <fastcgi++/request.hpp> #include <fastcgi++/manager.hpp> #include <string> using namespace std; using namespace Fastcgipp::Http; class SessionsPage : public Fastcgipp::Request<char> { static Session...
static Sessions<string> sessions; is only declared in the class; you need to create a definition for it. In this case I believe sticking Sessions<string> SessionsPage::sessions; after your class is fine, given that the class is used in only one translation unit. (If you use it in multiple translation units the static v...
6,365,472
6,365,496
C++: Using typeid in production code
Is it generally considered bad practice to use typeid in production code? Also, I noticed typeid returns type_info, which includes some metadata (such as a string with the type's name); is there a way to deactivate this?
It's hard to say whether the use of a particular language feature is "bad" or "good." It really depends on how you use it. There's nothing inherently wrong with using typeid if it's the right tool for the job, but if there's a better solution to whatever problem you're solving, then you should avoid using typeid in f...
6,365,477
6,366,251
Constructor execution order in C++
#include <cstdio> struct A { int a; A() { a = 2; printf("Default\n"); } A(int b_) { a = 1; if(b_ == 10) { A(); } } }; int main(int argc, char **argv) { A a(10); printf("a=%d\n", a.a); A b(11); printf("b=%d\n", b.a); return 0; } This prints: Default a=1 b=1 That is, it e...
Most answers so far say that you're not calling a constructor. You're seeing the output of the constructor call. So just disregard those answers that are denying reality by over-simplifying. The code snippet if(b_ == 10) { A(); } creates and destroys a temporary object of class A. As part of the creation the A defa...
6,365,565
6,365,577
What does it mean when a numeric constant in C/C++ is prefixed with a 0?
Ok... So I had a silly idea and tried putting the value 0123 into an int, just curious to see what would happen, I assumed that when I printed the value I'd get 123, but instead I got 83... Any ideas why? what happens inside the compiler/memory that makes this value become 83? I tried this in C++ and C with GCC compile...
In C/C++ a numeric literal prefixed with a '0' is octal (base 8). See http://www.cplusplus.com/doc/tutorial/constants/
6,365,727
6,365,927
How do you allocate memory for an linked list when passing its reference instead of its pointer?
How do you allocate memory for an link list when passing its reference instead of its pointer? For example: struct node { string info; node *next; }; void add(node &aNode){ //if I use node *newNode; newNode = new node; aNode.next = newNode; //aNode.next = newNode; doesn't work either //allocating on heap seems...
In your second variant of main(), you are calling add(aNode) twice. But you're providing it the same parameter each time. So although you're creating two new node objects, one of them is lost forever (a memory leak). And aNode.next ends up pointing to the other one. aNode.next->next is not a valid pointer, hence th...
6,365,893
6,366,001
How can I tell if the user tries to close the window in C++?
I need to break a while loop when the use clicks the close button on the window, but I don't know what to check for. I'm using allegro to run the GUI.
If using Allegro 4: set_close_button_callback() volatile int hit_closed = 0; void close_button_proc() { hit_closed = 1; } // later after creating the display: set_close_button_callback(close_button_proc); while (!hit_closed) { } With Allegro 5, it's more like: al_register_event_source(queue, al_get_display_event...
6,366,139
6,739,230
Trying to implement an iterator without an explicit container
After my recent question, I am trying to implement my own contrived example. I have a basic structure in place but even after reading this, which is probably the best tutorial I've seen, I'm still very confused. I think I should probably convert the Chapter._text into a stream and for the increment operator do somethin...
As you weren't planning on a chapter loading at a time (merely a paragraph), and your paragraph is empty, I think this might be best done with a single paragraph_iterator class class paragraph_iterator : public std::iterator<std::input_iterator_tag, std::string> { std::shared_ptr<std::ifstream> _infile; //current ...
6,366,165
6,366,196
Queried class member returns wrong value
I have created a simple RAII class in one of my DLLs (let's call it the exporting DLL) which monitors for configuration restore in my application: Header file class __declspec(dllexport) CEmuConfigurationRestoreMonitor { public: CEmuConfigurationRestoreMonitor() { m_restoreInProgress = true; } ...
You've given each DLL its own copy of m_restoreInProgress. You could fix this by: Not using an inline function. Using a file-scoped variable for m_resotreInProgress, in a source file included in only the exporting DLL.
6,366,231
6,366,374
Why not overload operator+=() for std::vector?
I've started learning C++, so I don't know in my lack of knowledge/experience why something so seemingly simple to a rookie as what I'm about to describe isn't already in the STL. To add a vector to another vector you have to type this: v1.insert(v1.end(), v2.begin(), v2.end()); I'm wondering whether in the real world...
This is actually a case where I would like to see this functionality in the form of an overload of append(). operator+= is kinda ambiguous, do you mean to add the elements of each vector to each other? Or you mean to append? However, like I said, I would have welcomed: v1.append(v2); It is clear and simple, I don't kno...
6,366,284
6,366,545
Dynamic typedef of a primitive in C++
I am making a toy physics engine which works with floating point numbers which I call reals. At present, I am using a typedef; typedef float real; This is so I can change the precision of the floating point values to doubles or long doubles, but obviously I have to recompile. I would like to be able to cleanly define ...
A float uses less memory than a double and is less precise. BUT, there is only one set of math libraries and it is double based. All floats get converted to double for calculations and then must be cast back to float. Just use doubles.
6,366,354
12,686,863
How to use the Poco C++ HTTPSessionFactory
How is the best, simplest way to set up the HTTPSessionFactory to handle both HTTP and HTTPS? I know that I need to use HTTPSessionInstantiators, but I could really use a short and sweet example. Thanks.
You need to register the 'http' and 'https' protocols. And for handling 'https', you also need to configure your SSLManager with cert and context, here is a piece of example code: //register http and https HTTPSessionFactory::defaultFactory().registerProtocol("http", new HTTPSessionInstantiator); HTTPSessionFactory::d...
6,366,447
6,366,460
Setting Two Functions Equal
I am trying to make a C++ Button class in which the user inputs a function to execute when the button is pressed. So far, this is my code: class Button { public: char* text; void* buttonclick(); Button (char* constext, void* consbuttonclick()) { text = constext; //What do I do here? } }...
What you've declared is a function returning a void *. You want a pointer to function returning void. So to start with you need to change the prototype: In place of void * foo() you want void (*foo)(). (You'll have to sort out exactly what you want, but that's the idea.) Once you have it, you call it simply by usin...
6,366,684
6,368,109
C++, Implementing a custom iterator for binary trees (long)
Please be nice- this is my first question. =P Basically as a summer project I've been going through the list of Data Structures on the wikipedia page and trying to implement them. I took a C++ course last semester and found it to be great fun, as a final project I implemented a Binomial Heap- this was also very fun. Ma...
1. Fat Iterators vs Lean Iterators There are two possible ways to implement the traversal of a tree. You may either: have nodes that simply points to their "children", and iterators that keep a stack (thus, fat iterators) have nodes that have a parent pointer (like yours), and iterators that are just pointers to a giv...
6,366,930
6,367,270
How many mutex and cond variable?
I am wokring on pthread pool and there will be five separate thread and one queue. All the five threads are competing to get a job from the queue and I know the basic idea that I need to do lock/unlock and wait/signal. But I am not sure how many mutex and cond variable I should have. Right now I have only one mutex and...
To elaborate on @Ivan's solution... Instead of a mutex + condition variable, you can use a counting semaphore + atomic operations to create a very efficient queue. semaphore dequeue_sem = 0; semaphore enqueue_sem = 37; // or however large you want to bound your queue Enqueue operation is just: wait_for(enqueue_sem) at...
6,367,274
6,367,480
What are some good reference materials in getting started with Visual Studio 2010 C++ for a mid-advanced C# dev?
I am a reasonably competent C# developer who has experience in threading, web development, windows client development, and basic (recent) experience in multi-platform C. I realize that there are questions out there that cover the insanely wide spectrum of C++. Given that the C++ and Windows C++ realm is vast with a lot...
My list: MSDN - source of all dev information Windows via C/C++ Microsoft Visual C++ Windows Applications by Example: Code and explanation for real-world MFC C++ Applications (will at least cover you e.g. question)
6,367,379
6,367,395
Why hasn't my variable changed after applying a bit-shift operator to it?
int main() { int i=3; (i << 1); cout << i; //Prints 3 } I expected to get 6 because of shifting left one bit. Why does it not work?
Because the bit shift operators return a value. You want this: #include <iostream> int main() { int i = 3; i = i << 1; std::cout << i; } The shift operators don't shift "in place". You might be thinking of the other version. If they did, like a lot of other C++ binary operators, then we'd have very bad...
6,367,717
6,371,904
Convert from String to Unsigned Long and back
How do you convert a string to an unsigned long so that the unsigned long represents the characters in the string as 8bit numbers? Thanks in advance. EDIT: What I want to do is turn a string of 4 characters into a long of the same four characters in ASCII code format.
largely the same solution, making less assumptions on integral types sizes and checking the maximum string size that can be translated this way: #include <string> #include <algorithm> #include <iostream> #include <climits> int main() { const size_t MAX = sizeof(unsigned long); std::string s("abcd"); unsigned lo...
6,367,735
6,367,776
qt error: undefined reference to `vtable for Thread'
I have the code: #include <iostream> #include <QThread> #include <unistd.h> #include <stdlib.h> #include <QApplication> using std::cerr; using std::endl; class Thread : public QThread { Q_OBJECT public: Thread(); ~Thread(); void setMessage(const QString &_message); void stop(); protected: voi...
You must generate a header with moc. This can be done automatically with the Qt build system. Instead of using gcc directly, you should use a qmake file. Also you should probably separate the declaration and code into header file and cpp file. Here is a description of what moc does: http://doc.qt.nokia.com/latest/moc.h...
6,367,813
6,385,308
Get relative position of mouse in a window in x11
I need to get the relative position of mouse pointer in the window in which it is clicked, i've coded to capture the click event, but when i use this code result = XQueryPointer(disp, XRootWindow(disp,0),&win, &win, &root_x, &root_y, &win_x, &win_y, &mask_return); it shows the global position of mouse when printing w...
Found out evt.xbutton.x and evt.xbutton.y returns window relative mouse co ordinates
6,367,943
6,371,037
dll Export/init problem (static vars init?) Visual Studio C++
I want to run an example plugin for CLANG/LLVM. Specifically llvm\tools\clang\examples\PrintFunctionNames. I managed to build it and i see an PrintFunctionNames.exports but i dont think visual studios supports it. The file is simply _ZN4llvm8Registry*. I have no idea what that is but i suspect its namespace llvm, class...
Ok, becoming slightly more clear. To summarize: Visual Studio has nothing to do with it, really. This is a plugin for the clang executable. Therefore, there must be a method to communicate between them (the plugin interface). This appears to be an undocumented interface, so it's taking a bit off guesswork. Troubleshoot...
6,367,961
6,367,989
calculating constant library functions at compile time
I want to use boltzmann constant in my functions. I am using the following code to declare the boltzmann constant const double boltzmann_constant = 1.3806503 * pow (10,-23); Will this get calculated at the compile time itself? If now, how should i ensure that it does get calculated at compile time? Any other method to...
The pow() function is very unlikely to be calculated at compile time. However, the operation requested is directly expressible in scientific notation, a standard aspect of floating point numbers: const double boltzmann_constant = 1.3806503e-23; For a more complex situation, like sin(M_PI / 3), it can be useful to wri...
6,367,995
6,368,118
Order of Class Definitions in C++
I've got a bit of a problem here. I'm trying to define several classes, of which some are Players and some are Pawns belonging to the players. Coming from Python, I'm used to being able to conveniently access a Pawn's owning Player through the Pawn, as well as accessing a Player's Pawns through the Player. Correct m...
If the class Player is coming first and class Pawn coming later then you can only declare pointer or reference to the later class (here Pawn). You cannot have objects of later class, e.g. class Player { Pawn* p; // allowed Pawn& r; // allowed vector<Pawn*> p; // allowed vector<Pawn&> vr; // not allowed (referen...
6,368,005
6,368,158
Why static method overrides base class non-static method?
struct B { void foo () {} }; struct D : B { using B::foo; static void foo () {} }; int main () { D obj; obj.foo(); // calls D::foo() !? } Member method and static member method are entirely different for 2 reasons: static method doesn't override the virtual functions in base class Function pointer signat...
The rule that you are seeing is described in ISO/IEC 14882:2003 7.3.3 [namespace.udecl] / 12 : When a using-declaration brings names from a base class into a derived class scope, member functions in the derived class override and/or hide member functions with the same name and parameter types in a base class (rather t...
6,368,013
6,368,070
Is it possible declare a variable with different types in c++?
I'm trying to declare a variable like this: switch(foo){ case 1: MyClass myObject(); break; case 2: MyClass2 myObject(); break; case 3: MyClass3 myObject(); break; } but at moment to compile this, compiler returns these errors: crosses initialization of 'MyC...
No, you cannot do something like that. Besides the naming conflict inside the switch, you also have the problem that the variable goes out of scope when you leave the switch. On top of that, MyClass myObject(); declares a function returning a MyClass. You would declare a variable as just MyClass myObject;. If you need ...
6,368,055
6,368,072
problems with cMath and the sin function
Hey so i'm doing some graphics math and inserting what i believe to be a float (i'm pretty sure the ways i manipulate the float beforehand is messing something up somehow...) into the function and getting strange, negative results back. for instance when doing the following opperations when Angle initially equals 350....
That's because the C/C++ runtime function sin() expects the argument in radians, not degrees. Convert to radians with: float test= sin(Angle / 180 * M_PI); etc.
6,368,127
6,368,268
Segfault in Cygwin but not VS, any ideas?
It works with Visual Studio, but segfaults in Cygwin, which is weird because I'm compiling the same source, and both generate a Windows executable. GDB doesn't work very well for me in Cygwin for some reason, and the error doesn't appear in VS so I can't really debug it there. Any ideas? int main(void) { Pair ***oc...
You marked this line as the critical point: occurences[word.size()-1][i][word[i] - 97].occurs++; All three array accesses might go wrong here, and you would have to check them all: It seems like the first dimension of the array has the length 20, so the valid values for the index are [0..19]. word.size()-1 will be les...
6,368,141
6,368,155
c++ continue versus break
Which statement will be executed after "continue" or "break" ? for(int i = 0; i < count; ++i) { // statement1 ...
continue: ++j and then if j < count then statement2 otherwise statement3 break: statement3
6,368,332
6,368,362
Test conditions in C++
Possible Duplicate: What is the difference between these (bCondition == NULL) and (NULL==bCondition)? Why do some people write instead of: if(someVar == 0) {} this: if(0 == someVar) {} What is the difference ? Thanks.
Just a good practice. If by mistake, you use single = instead of ==, finding the bug in the first one is very difficult but the second one would fail to compile clearly showing the line of error.
6,368,432
6,380,430
Objects vs instance in python
In C++ there are just objects and classes, where objects are instances of classes. In Python, a class definition (i.e., the body of a class) is called an object. And, the object in C++ is called instance in python. Check this Am I wrong? EDIT : Actually can someone explain with example difference of object vs instanc...
In Python, a class definition (i.e., the body of a class) is called an object Actually, this is still called a class in Python. That's why you define it like this: class Foo(object): pass The class keyword is used because the result is still called a class. The word object is in parentheses to show that Foo is ...