question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
3,731,831
3,731,838
How do I assign a literal chinese string to a wchar_t* in visual studio(c++)?
I am trying to compile the following code in my test application on windows in visual studio for C++: const wchar_t* chinese = "好久不见"; But I get the following error: error C2440: 'initializing' : cannot convert from 'const char [5]' to 'const wchar_t * I am compiling with unicode, so I am confused about this. The er...
You want a wide string literal, so prefix the string literal with L: const wchar_t* chinese = L"好久不见";
3,732,015
3,732,034
Will using CreateEvent to create/open an even that already exists reset the signal?
If I use CreateEvent to open an event: responseWaitEvent = CreateEvent(NULL, // no security TRUE, // manual-reset event FALSE, // not signaled (LPTSTR)eventName); // event name And this event already exists and has been signaled. Will this call reset the signal (because of setting initial stat...
The second call will open the event, it will not change the event's state. I know this because the documentation says that it opens it but not that it resets it. If it reset it, that would be important enough to mention. HANDLE responseWaitEvent = CreateEvent(NULL, // no security TRUE, // manual-rese...
3,732,226
3,732,259
Bitfields vs. Polymorphism for game map object attributes
This optimzation question has been bugging me for the last day. In my program (a simple roguelike game), I use bitwise flags to store the attributes of map objects, such as if they are solid, or if they are rendered. However, I could accomplish the thing using polymorphism to return the appropriate value. My question ...
A bitwise operation is always faster than a virtual function call.
3,732,242
3,740,622
Application GUI development platform
Coming from C++ & MFC background, is there any better (maintainability/customization) platform in developing application GUI ? We are developing industrial applications (machine vision), where : -Performance-critical (mostly image processing in CPU atm, but GPU is up next) -Low level hardware interfacing (inhouse PC...
What I had did before when developing a C++ scientific application is that, it will develop it completely under console based application. The console based application will able accept various type of command from user keyboard, and perform action accordingly. For example : image_processor > load input.png image_proce...
3,732,395
3,732,406
Implementing atomic<T>::store
I'm attempting to implement the atomic library from the C++0x draft. Specifically, I'm implementing §29.6/8, the store method: template <typename T> void atomic<T>::store(T pDesired, memory_order pOrder = memory_order_seq_cst); The requirement states: The order argument shall not be memory_order_consume, memory_orde...
Do what you want. It doesn't matter. When ISO state that you "shall not do something", doing it is undefined behaviour. If a user does that, they have violated the contract with the implementation, and the implementation is within its rights to do as it pleases. What you decide to do is entirely up to you. I would opt ...
3,732,399
3,732,448
How do I delete a node from linked list?
How can I delete a node (between two nodes) from a single linked list without passing any parameters to the class function? For example, I have a list of 6 nodes with one head node and I want to delete two of them (without prior knowledge of their address or position) from a class function, how would I do that? void ...
Your edit has prior information, the bit that states "counter <= 10" :-) Pseudo-code for deleting elements meeting that criteria in a singly-linked list: def delLessThanTen: # Delete heads meeting criteria, stop when list empty. while head != NULL and head->count <= 10: temp = head->next free h...
3,732,427
3,732,441
C++ or C++0x - Which is a better standard?
So I've been trying to do some research and would like the opinions of other developers on this topic. I am an experienced C++ programmer and have been using the current C++ standard for some time. I have been reading articles that "C++0x will undoubtedly become the new standard." How far off are we does everyone think...
It would be pretty sad if the next version of C++ were quantitatively worse than the current one. The entire point of the new revision is to improve things.
3,732,504
3,748,048
Difference in FMOD between Sound.readData and Sound.lock?
I'm trying to sort the difference between Sound.readData and Sound.lock in the FMOD library (I'm programming in C#/C++ but I'll take the answer in any language!). The end goal is to create a view of the waveform, which I understand cannot be done (easily) with Channel.getWaveData. I have been able to get both the So...
Essentially the difference between the two is what you are accessing. With Sound::lock you are locking the sample buffer of the sound, so when you load with createSound it decompressed the file to PCM and puts it in the sample buffer. You use this function to directly access that buffer (you lock the portion of it you ...
3,732,578
3,732,593
c++ directx gaming: images vs vertices
In video games, do they use images or do they draw everything using vertices?
The answer really is: both. 3D video games use collections of verticies to describe various models that are used in the game (scenery, player characters, etc.). Textures (images) are then applied to the meshes to make the game look realistic. Without the images, everything would look like a wireframe or a single colo...
3,732,580
3,732,610
C++ Bubble sorting a Doubly Linked List
I know bubble sort is probably not the fastest way to do this but its acceptable. i'm just having trouble with adjusting the algorithm to double link lists from arrays. My double linked lists have a type int and a type string to hold a number and a word. My list was sorted with an insertion sort that I wrote to sort al...
My trouble spot is how to run this loop so that it is properly sorted thoroughly and not just one time. If you already have a loop that will successfully do one pass and swap is okay, the usual way to do multiple passes relatively efficiently is: set swapped = true while swapped: set swapped = false do your o...
3,732,626
3,733,023
How to have macros expanded by doxygen, but not documented as a define?
Say I have: #define MY_MACRO(FOO) void FOO(); MY_MACRO(hi); MY_MACRO(hey); MY_MACRO(hello); #undef MY_MACRO I want the macros to be expanded by doxygen, which I am able to do by configuring it the right way: ENABLE_PREPROCESSING = YES MACRO_EXPANSION = YES EXPAND_ONLY_PREDEF = YES EXPAND_AS_DEFINED ...
Supposing that MY_ is the prefix that you are using consistently in your code :) I would use the prefix MY__ (two underscores) for internal macros and then put something like EXCLUDE_SYMBOLS = MY__* in the Doxygen configuration file. Edit: the double underscore inside symbols is reserved for C++ (not for C). So...
3,732,763
3,732,770
Why does compilation of this simple C++ program using 'cpp' fail?
I am a beginner in C++ I am average at C. I have written the following code in C++ (file.cpp) #include <iostream> int main(){ std::cout<<"My name is ANTHONY"; } Then I tried to compile the above code using cpp file.cpp but got some errors. I don't know whats wrong When I tried to compile my C program (changed <io...
Then I tried to compile the above code using cpp file.cpp but got some errors. That is because cpp is C(C++) preprocessor. It is a separate program invoked by the compiler (g++) as the first part of translation. Try compiling your code using g++ file.cpp. :)
3,732,802
3,733,109
Require return type of function template to be specialization of a template
I've poked around on stackoverflow for a while, but either I don't understand templates enough to find a solution, or it simply hasn't been answered before. In this example: template <typename T> T f(); Is it possible to make the function require type T to be a specialization of the std::basic_string template? I could...
Partial specialization allows you to test whether a type is a specialization of a particular template. SFINAE is a trick that can "switch off" a function template declaration. The solution combines these techniques. template< typename T > // by default, struct enable_if_basic_string {}; // a type is not a basic_string ...
3,732,888
3,732,902
C++ Linux TCP sockets fd
how do i change the socket id/FD after i use accept() ? lets say i bind() on sockfd 3 and the accepted client is on sockfd 4, how do i change/move that sockfd to 1000? OS : Ubuntu
Still you didn't specify the OS so I will go with *nix :) http://linux.die.net/man/2/dup2
3,732,946
3,732,989
Templates :Name resolution -->IS this statement is true while inheritance?
This is the statement from ISO C++ Standard 14.6/6: Within the definition of a class template or within the definition of a member of a class template, the keyword typename is not required when referring to the unqualified name of a previously declared member of the class template that declares a type. The keyword typ...
Yes, that is equally true of inherited members. The keyword typename is required for members of base templates, but not base classes in general. The reason it is required for base templates is that their members are not automatically brought into the scope of the class {} block, so the only way to refer to them is with...
3,733,044
3,733,165
Virtual base class constructors are invoked first followed by an orderly invocation of constrctors of other classes
Can somebody explain why it is so ?
The virtual base is initialized first because any subset of base classes might inherit from it. The alternative is to attempt to have them coordinate so the first one to inherit initializes the virtual base. That would be clumsy and unpredictable.
3,733,081
3,733,226
Should we delete before or after erase for an pointer in the vector?
Should we delete before or after erase. My understanding is both are OK. Is it correct? In addition, is there any case we won't want to delete the element while erasing it? I believe there must be , otherwise, the erase will be happy to take the responsibility. std::vector<foo*> bar; ... for (vector<foo*>::iterator i...
"itr" must be used like this; for (vector<foo*>::iterator itr = bar.begin(); itr != bar.end(); ) { delete (*itr); itr = bar.erase(itr); } However, I'd prefer to first delete all elements, and then clear the vector; for (vector<foo*>::iterator itr = bar.begin(); itr != bar.end(); ++itr) delete (*itr); bar.clea...
3,733,164
3,733,174
Trying to make a recursive call in C++
This is my first question here so be kind :-) I'm trying to make a recursive call here, but I get the following compiler error: In file included from hw2.cpp:11: number.h: In member function ‘std::string Number::get_bin()’: number.h:60: error: no matching function for call to ‘Number::get_bin(int&)’ number.h:27: note: ...
In the last line you are calling get_bin() with an integer reference argument, but there are no formal parameters in the function signature.
3,733,169
3,734,916
Programatically unzip an AES encrypted zip file on Windows
I need to be able to unzip some AES (WinZip) encrypted zip files from within some C/C++ code on Windows. Has anybody got a way to do this? I'm hoping for either some appropriate code or a DLL I can use (with an example usage). So far my searches have proved fruitless. The commonly prescribed InfoZip libraries do not s...
Here is the minizip zlib contribution with AES support for both encryption and decryption. https://github.com/nmoinvaz/minizip
3,733,194
3,733,367
Why explicit instantiation of outer class template is required before explicit instantiation of a class template
My question is w.r.t the following thread : specialize a member template without specializing its parent I'm absolutely fine with the standard saying that it is illegal to do so. But i want to understand why is it illegal to do so? What would be impact had it been allowed?
Maybe because of something like this: template <typename T> struct foo { template <typename U> struct bar { typedef U type; }; }; template <typename T> struct foo<T>::bar<int> // imaginary { typedef void type; }; template <> struct foo<float> { template <typename U> struct bar ...
3,733,207
3,801,497
Google Sketchup C++ SDK: SkpWriter usage
I am trying to use Google's Sketchup C++ SDK (latest version) to export a 3D model to a Sketchup file. One of the problems I am facing is that the header files refer to an "sapi" folder which does not exist in the source tree. I need to figure out how I can get a reference to the ISketchUpApplication interface. Can so...
The latest SDK comes with an example showing how the writer is used. The example can be found at "SkpWriter/Examples/skpwriter_example/skpwriter_example" within the Windows SDK download bundle.
3,733,251
3,733,481
Find the subsequence with largest sum of elements in an array
I recently interviewed with a company and they asked me to write an algorithm that finds the subsequence with largest sum of elements in an array. The elements in the array can be negative. Is there a O(n) solution for it? Any good solutions are very much appreciated.
If you want the largest sum of sequential numbers then something like this might work: $cur = $max = 0; foreach ($seq as $n) { $cur += $n; if ($cur < 0) $cur = 0; if ($cur > $max) $max = $cur; } That's just off the top of my head, but it seems right. (Ignoring that it assumes 0 is the answer for empty and all ne...
3,733,508
3,750,117
C++ Nvidia Cg question
I started using Nvidia Cg shaders recently and everything looks and works fine if I'm doing it on the Nvidia GPU (GTS250 in my case). I tried launching the same (my own test application) on ATI HD4650 and saw no output. Right after that I started experimenting with test examples (provided with Nvidia Cg 3.0) and 6/7 wo...
Set Debug DirectX version in the DirectX control panel and see trace output to get the reason of this failure. BTW, I had the same situation with my pixel shader and got help in GameDev.net DirectX forum. I remember that finally I converted the shader to lowest version using SDK conversion tool, and it worked without p...
3,733,582
3,733,597
How to return a char array created in function?
I've been programming badly for quite a while and I only really just realised. I have previously created many functions that return character strings as char arrays (or at least pointers to them). The other day someone pointed out that when my functions return the char arrays pointed to by my functions have gone out of...
The simplest way would be to return a std::string, and if you needed access to the internal char array use std::string::c_str(). #include <iostream> #include <string> using namespace std; string myGoodFunction(){ char charArray[] = "Some string\n"; return string(charArray); } int main(int argc, char** argv)...
3,733,613
3,733,656
Redefinition of pure virtual methods in C++
Do you have to declare methods replacing a pure virtual function in a base class? If so, why? Because the base class has declared the methods as pure virtual, and therefore MUST exist in derived class, then is should not be necessary to redeclare them in the derived class before you can implement them outside of the cl...
Yes you have. The reason for this is to let the compiler know that the virtual method is being implemented by the derived class since a derived class can also be abstract and have virtual methods. Since compilation units are compiled separately, the compiler would otherwise not know whether a virtual method is implem...
3,733,636
3,733,705
C++ instantiate function template as class member and using "this" pointer
I have two classes (ClassA and ClassB) who both have two methods (compare and converge). These methods work exactly the same way, but these classes are not related polymorphically (for good reason). I would like to define a function template that both of these classes can explicitly instantiate as a member but I'm ge...
I believe you can use CRTP here. Here is an example, you can omit the friend declaration in case you can do the compare using only public members: template<class T> class comparer { public: T* compare(const T& t) { //Use this pointer bool b = static_cast<T*>(this)->m_b == t.m_b; retur...
3,733,779
3,733,882
How program and compile "Hello World" code in kernel mode of linux?
Yes, as the title, I don't know how to program and compile "Hello World" code in kernel mode of linux , please help me in the shortest and easy to understand way. Thank you ! (Any related document is welcomed too, I'm just new to this)
You can start Here: /* * hello-1.c - The simplest kernel module. */ #include <linux/module.h> /* Needed by all modules */ #include <linux/kernel.h> /* Needed for KERN_INFO */ int init_module(void) { printk(KERN_INFO "Hello world 1.\n"); /* * A non 0 return means init_module failed; module can't...
3,733,837
3,733,945
Removing duplicates from a QList
For years I have been using the following pattern to remove duplicates from an object of the C++ std::vector type: std::vector<int> cont; std::sort(cont.begin(), cont.end()); cont.erase(std::unique(cont.begin(), cont.end()), cont.end()); Now I am wondering if the same paradigm is the one to be used with the Qt QList<>...
I don't know about performance, but what about converting the QList into a QSet ? QList<int> myQList; //... QSet<int> = QSet::fromList(myQList); // or QSet<int> = myQList.toSet(); (and maybe convert it back to a QList if needed with QList::fromSet())
3,733,933
3,733,950
Infinite loop using static_cast on this pointer
Suppose I have two classed Base and Derived, i.e.: #include <iostream> class Base { public: Base () : m_name("Base") { } virtual ~Base () { } virtual void method (std::ostream & out) const { out << m_name << std::endl; ...
Probably you already guessed: static_cast<const Base * const>(this)->method(out); is a virtual call, which means the function is called within itself. In this case, it would lead to stack overflow. Base::method(out) is not a virtual call.
3,734,102
3,734,113
Why can't I return bigger values from main function?
I am trying to return a bigger value like 1000 from my main function, but when I type echo $? it displays 0. If I return a smaller value like 100 it displays the correct value. My Code: int main(void) { return 1000; } Is there any limitation on the values which we can return?
There are two related concepts here: C exit status, and bash return code. They both cover the range 0-255, but bash uses numbers above 126 for it's own purposes, so it would be confusing to return those from your program. To be safe limit exit status codes to 0-127, as that is most portable, at least that is implied by...
3,734,226
3,736,191
Which sorted STL container to use for fast insert and find with a special key?
I have some data with a key associated with each data item. The key is made of two parts: let's call them color and id. I want to iterate the container by color to speed up rendering and I also want to find items in the container by id alone. I tried using std::map for this with a key class MyKey { public: int color;...
Adapt the example here from Boost.Multi_index based on the following modifications: typedef multi_index_container< MyKey, indexed_by<ordered_unique<identity<MyKey> >, ordered_non_unique<member<MyKey,int,&MyKey::color> > > > DataSet;
3,734,247
3,734,268
What are all the member-functions created by compiler for a class? Does that happen all the time?
What are all the member-functions created by compiler for a class? Does that happen all the time? like destructor. My concern is whether it is created for all the classes, and why is default constructor needed?
C++98/03 If they are needed, the compiler will generate a default constructor for you unless you declare any constructor of your own. the compiler will generate a copy constructor for you unless you declare your own. the compiler will generate a copy assignment operator for you unless you declare your own. the com...
3,734,320
3,735,459
How can I set tens of thousands of tasks to each trigger at a different defined time?
I'm constructing a data visualisation system that visualises over 100,000 data points (visits to a website) across a time period. The time period (say 1 week) is then converted into simulation time (1 week = 2 minutes in simulation), and a task is performed on each and every piece of data at the specific time it happen...
Just make a "timer" mechanism yourself, that's the best, fastest and most flexible way. -> make an array of events (linked to each object event happens to) (std::vector in c++/STL) -> sort the array on time (std::sort in c++/STL) -> then just loop on the array and trigger the object action/method upon time inside a ran...
3,734,341
3,736,958
Extending C++ Win32 application with a C# WPF component
I need to add a new component to a C++ Win32 application (no CLR support) and I would like to implement the new component in C# and use WPF. This new component is basically a window with some controls, which I need to launch quickly from an option in the menu of the Win32 application. The new component and the existing...
If you want to do this without changing your C++ compilation you might look at calling the .NET assembly as via COM. MSDN describes how to expose .NET Framework Components to COM. The way I've done this is basically: Make a COM friendly class and interface in C# Export the TLB from the DLL GAC the DLL Register the DL...
3,734,355
3,761,878
How do I detect plaintext in a MIME file?
I have a large set of MIME files, which contain multiple parts. Many of the files contain parts labelled with the following headers: Content-Type: application/octet stream Content-Transfer-Encoding: Binary However, sometimes the contents of these parts are some form of binary code, and sometimes they are plaintext. ...
The simplest method is to split the file into a set of multiple files each of which contains one of the component parts. We can then use grep and other functions to ascertain the text format.
3,734,399
3,734,875
Error passing custom Object from QtScript to C++
I have written a custom class which is available in QtScript through a Prototype. Also another global class is available which should be used to print the custom class generated in QtScript. This is my custom class (very simple ;) ): class Message { public: int source; int target; }; This is the pr...
Ok. After several attempts I fixed it. I changed the sendMessage function to accept a QScriptValue instead of a Message as parameter. Now I can get the properties out of it without problems. Seems to work fine now :)
3,734,632
3,734,756
Templates :Name resolution -->can any one tell some more examples for this statement?
This is the statement from ISO C++ Standard 14.6/7: Knowing which names are type names allows the syntax of every template definition to be checked. No diagnostic shall be issued for a template definition for which a valid specialization can be generated. If no valid specialization can be generated...
void f<T>() "I am an ill-formed 'template definition' parameterized on T."; An implementation is allowed to accept the above as a syntactically ill-formed template definition and not diagnose it until it's actually instantiated. Hope this explains it. (Of course I'm kidding, but I'm not entirely unserious. It shows a ...
3,734,707
3,734,721
Passing C style string around function
I have a situation as below in which I need to pass a C-style string into a function and stored it into a container that needed to be used later on. The container is storing the char*. I couldn't figure out the efficient way to create the memory and store it into the vector. As in overloadedfunctionA (int), I need to c...
For all that's holy, just use std::string internally. You can assign to a std::string from a const char*, and you can access the std::string's underlying C string through the c_str() method. Otherwise, you'd need to write a wrapper class that handles memory allocation for you, and store instances of that class in your ...
3,734,906
3,736,034
What does a function object look like if it has a number of parameters?
I have created a very simple Tree implementation, and I would like to be able to pass a function object to my traverse() function. e.g. template<class T> class MyTree { public: void traverse(MyFunction f) { traverse(root, f); } private: MyTreeNode<T>* root; void traverse(MyTreeNode<T>*, MyF...
There are different things that you can do at this stage. The old style C type solution: you can pass a function pointer: template <typename T> void MyTree<T>::traverse( void (*function)( MyTreeNode<T>*, int ) ); That will take as argument a function pointer (free function) that takes a pointer to a MyTreeNode<T> obj...
3,734,921
3,734,964
Constructors and inheritance?
Lets say I have a class named Car and another which inherits from Car called SuperCar. How can I ensure that Car's costructor is called in SuperCar's constructor? Do I simply do: Car.Car(//args);? Thanks
In SuperCar constructor add : Car(... your arguments ...) between constructor header and constructor body. Exemple with code: #include <iostream> using namespace std; class Car { public: Car() { } // Oh, there is several constructors... Car(int weight){ cout << "Car weight is " << weight << end...
3,735,022
3,735,051
Error with T::iterator, where template parameter T might be vector<int> or list<int>
I'm trying to write a function to print a representation of common STL containers (vector, list, etc..). I gave the function a template parameter T which, for example, might represent vector. I'm having problems getting an iterator of type T. vector<int> v(10, 0); repr< vector<int> >(v); ... template <typename T> void...
You need typename to tell the compiler that ::iterator is supposed to be a type. The compiler doesn't know that it's a type because it doesn't know what T is until you instantiate the template. It could also refer to some static data member, for example. That's your first error. Your second error is that v is a referen...
3,735,023
3,735,177
execv, select and read
I am creating a child-parent fork() to be able to communicate with a shell(/bin/sh) from the parent through a pipe. The problem is: In a parent I set a select() on a child output, but it unblocks only when the process is finished! So when I run say ps it's okay. but when I run /bin/sh it does not output until shell exi...
A lot of programs change their behavior depending on whether or not they think they're talking to a terminal (tty), and the shell definitely does this this. Also, the default C streams stdout and stderr are probably unbuffered if stdout is a tty, and fully buffered otherwise - that means that they don't flush until the...
3,735,170
3,735,199
Permuting All Possible (0, 1) value arrays
I am having writing an algorithm to generate all possible permutations of an array of this kind: n = length k = number of 1's in array So this means if we have k 1's we will have n-k 0's in the array. For example: n = 5; k = 3; So obviously there are 5 choose 3 possible permutations for this array because n!/(k!(n-k)!...
You can split up the combinations into those starting with 1 (n-1, k-1) and those starting with 0 (n-1, k). This is essentially the recursive formula for the choose function.
3,735,299
3,735,315
Unit separator in C++
How could I include a unit separator (value 31 in ascii table) in a string other than using snprintf()? I want to do like we normally initialize a string. eg char[100] a = "abc"
31 in dec = 0x1f in hex. Therefore, char x[] = "blah\x1f" "blah"; // ^^^^ unit separator. The string is split into two to avoid the compiler reading the escape sequence as 0x1fb (it should be read as 0x1f, which is 31 in decimal). Alternatively you could use octal sequence: char x[] = "blah\037blah"; // ...
3,735,321
3,735,439
Solving cross referencing
I have a problem creating some form of hierarchy with different object types. I have a class which has a member of another class, like this: class A { public: A(){} ~A(){} void addB(B* dep){ child = dep; dep->addOwner(this); } void updateChild(){ child->printOwner(); } ...
You say that you already solved your circular dependency problem by using a forward declaration of A instead of including the header where A is defined, so you already know how to avoid circular includes. However, you should be aware of what is possible and what is not with incomplete types (i.e. types that have been f...
3,735,398
3,735,433
operator as template parameter
Is it possible? template<operator Op> int Calc(int a, b) { return a Op b; } int main() { cout << Calc<+>(5,3); } If not, is way to achieve this without ifs and switches?
You could use functors for this: template<typename Op> int Calc(int a, int b) { Op o; return o(a, b); } Calc<std::plus<int>>(5, 3);
3,735,804
3,735,942
Undefined reference to operator new
I'm trying to build a simple unit test executable, using cpputest. I've built the cpputest framework into a static library, and am now trying to link that into an executable. However, I'm tied into a fairly complicated Makefile setup, because of the related code. This is my command line: /usr/bin/qcc -V4.2.4,gcc_ntoar...
There's very little information in your question to work from, but it looks like some code uses some form of placement new, and while that special operator new is declared (the compiler finds it and compiles the code using it), the linker can't find its definition. (Since this old answer of mine seems to still get atte...
3,735,839
3,735,875
C++ stack variables and heap variables
When you create a new object in C++ that lives on the stack, (the way I've mostly seen it) you do this: CDPlayer player; When you create an object on the heap you call new: CDPlayer* player = new CDPlayer(); But when you do this: CDPlayer player=CDPlayer(); it creates a stack based object, but whats the difference b...
The difference is important with PODs (basically, all built-in types like int, bool, double etc. plus C-like structs and unions built only from other PODs), for which there is a difference between default initialization and value initialization. For PODs, a simple T obj; will leave obj uninitialized, while T() defaul...
3,736,350
3,736,981
how to declare a template class as a friend in c++
I wana know if we can make a partial specialized class as a friend class. template< class A, class B > class AB{}; class C; template < class B > class AB< C, B >{}; class D{ template< class E > friend class AB< D, E >; } How to achieve the above.
This is not allowed by the C++ Standard (§14.5.3/9): Friend declarations shall not declare partial specializations. [Example: template<class T> class A { }; class X { template <class T> friend class A<T*>; //error }; --end example] So basically, you can either make all instantiations of AB friend of D or onl...
3,736,631
3,747,779
Why use FitNesse when the tests are highly technical?
It seems to me FitNesse has the following advantages: Let a non-technical person define sets of test data and expected results (how they define success). A non-technical person could be a user, a product manager, or possibly a software quality professional who does not have access to the source code and/or does not kn...
I completely agree with your assertion, that being difficult to incorporate into the automated build system is a serious flaw (extending the comment above to an answer) and for that reason I chose to go with an alternative implementation of Fit for C++, CeeFit. The original website (ceefit.woldrich.com) that hosted the...
3,736,911
3,736,971
Assigning and Conditional Testing Simultaneously in C++
I have three functions that return integer error codes, e.g. int my_function_1(const int my_int_param); int my_function_2(const int my_int_param); int my_function_3(const int my_int_param); I want to assign and test for error at the same time for brevity. Will the following work and be portable? int error=0; ... if (...
Why not throw an exception? void my_function_1(const int my_int_param); void my_function_2(const int my_int_param); void my_function_3(const int my_int_param); try { my_function_1(...); my_function_2(...); my_function_3(...); } catch(std::exception& e) { std::cout << "An error occurred! It is " << e.wh...
3,736,991
3,737,477
C++ Virtual Destructor Crash
I have the following class hierarchy: class Base { public: virtual ~Base(); }; class Derived : public Base { public: virtual ~Derived(); }; class MoreDerived : public Derived { public: virtual ~MoreDerived(); }; along with an objects Base* base = new Base(); MoreDerived* o...
I think you're thinking of dynamic_cast<void*> which obtains a pointer to a most-derived object. You don't need to go through a void* just to delete an object of polymorphic type. Just take whatever pointer you have and delete it, be it a Base* to a MoreDerived object or a MoreDerived*. There is no need for a Kill meth...
3,736,992
3,737,071
Setprecision() for a float number in C++?
In C++, What are the random digits that are displayed after giving setprecision() for a floating point number? Note: After setting the fixed flag. example: float f1=3.14; cout < < fixed<<setprecision(10)<<f1<<endl; we get random numbers for the remaining 7 digits? But it is not the same case in double.
Two things to be aware of: floats are stored in binary. float has a maximum of 24 significant bits. This is equivalent to 7.22 significant digits. So, to your computer, there's no such number as 3.14. The closest you can get using float is 3.1400001049041748046875. double has 53 significant bits (~15.95 significant...
3,737,096
3,737,125
Why do C/C++static libraries end in '.a'?
I am just doing a little work this morning making some static libraries. Why do static libraries end with '.a'? No one in my office knew, so I thought I would ask around on Stack Overflow. We are writing code in C++, C, and Objective-C.
I think the .a convention comes from using an "archiver" to place the object files into a static library.
3,737,138
3,737,748
How best to store VERY large 2D list of floats in c++? Error-handling?
I'm migrating some code from c to c++. I've changed some malloc calls for structure memory allocation to new calls. Basically before the code I'm porting was malloc'ing arrays that contain multiple sets of frame coords, each a couple hundred thousand floats in length -- so the total array length could be in the tens ...
Answer is std::vector. You don't need that much memory actually (or you have some memory constrained platform, I assume you would have told us in that case). Vector is perfectly fine for this purpose. And you don't have to manage the memory yourself. You can use vectors of vectors if you want to manage several of them ...
3,737,204
3,748,556
NUMA memory regions allocation in Windows 7
Our application is: Hardware configuration is a dual Xeon server running Windows 7/64bit. Each Xeon has it's own 12gb RAM in a [NUMA][1] configuration with a bridge connecting two memory regions together. All software is written using VS2008 in c++ and compiled as 64 bit applications. A Generation app creates a l...
Windows will allocate memory local to the requesting thread; however, local is not specified by Microsoft. Local could be one of three options: the thread's ideal processor, the thread's processor affinity mask, or the thread's current processor (I forget what the current implementation is). In essence, the answer is ...
3,737,286
3,737,524
C++ - call assignment operator at creation instead of copy constructor
I want to enforce explicit conversion between structs kind of like native types: int i1; i1 = some_float; // this generates a warning i1 = int(some_float): // this is OK int i3 = some_float; // this generates a warning I thought to use an assignment operator and copy constructor to do the same thing, but the behavior ...
You can get around this if you overload the type cast operator for other_struct, and edit the original structure accordingly. That said, it's extremely messy and there generally isn't a good reason to do so. #include <iostream> using namespace std; struct bar; struct foo { explicit foo() { cout << "In f...
3,737,516
3,752,393
Release resource on boost::shared_ptr finalization
I do receive a shared_ptr from a library call, and pass it and some resource back into the library. The resource can only be deleted when the shared_ptr deletes its pointer: std::ofstream* out = new std::ofstream(); ... shared_ptr<Lib::SomeClass> writer = Library.createWriter(out); Library.appendWriter(writer); The ...
I don't believe you can do this directly with the shared_ptr API. If Lib::SomeClass is an interface/abstract base class, you might be able to use a Decorator. The idea would be to define a class which subclasses Lib::SomeClass, contains a shared_ptr<Lib::SomeClass> and a std::ofstream*, and whose methods all forward t...
3,737,772
3,886,726
WX: attempting to select value when clicking a text field
We are implementing a text field to do numeric entry. We subclass the standard wxTextCtrl. Behavior is that when user decides to edit the value they get a full precision version and it is selected. First attempt was to override the focus handler so that when the field gets focus the value is shown in full and selecte...
Answer is that it can't be done. The behavior I'm trying to override is implemented by the win32 component itself and wx doesn't provide any method to doing so....short of bypassing WX to get the win32 handle and using win32 api. Would need to write a new component in the WX api to get the desired behavior.
3,737,846
3,737,877
converting String.data() into an array
I want to take a string,and populate an array with its values. I know the length of the string is 16. I have tried char *bit_number[16]; bit_number = bin.data(); and char bit_number[16]; bit_number = bin.data(); I don't understand what String.data() is returning, why can't I assign it directly to an array? I'm gettin...
You can use std::string::c_str() to get access to the char array, and then use strcpy to move it over to the new array. string s = "1234"; char arr[5] = { 0 }; strcpy(arr, s.c_str());
3,738,058
3,738,082
Why are certain bracket style/formats prefered in c/c++?
I've gotten the gist that the following <T> my_function(...) { .... } is preferred by most, compared to: <T> my_function(...) { .... } Likewise for: if (...) { ... } being preferred over if (...) { ... } Is this true and if so, why is the former style preferred over the latter?
The first one is popular mostly, because it is demanded by Sun (Now: Oracle) in Java
3,738,167
3,738,226
multithreading and classes?
Here is the issue that I'm having with multithreading. The proc needs to be static which means the only way I see that 2 threads can communicate and share data is through the global scope. This does not seem very clean nor does it feel very OO. I know I can create a static proc function in a class but that's still stat...
You cannot avoid using a static function if you want to start a thread there. You can however (using Windows) pass the this pointer as a parameter and use it on the other side to enter the class instance. #include <windows.h> class Threaded { static DWORD WINAPI StaticThreadEntry(LPVOID me) { reinterpret_c...
3,738,233
3,738,267
How to copy binary data from one stream to another?
Currently i have a program that loads binary data into a stringstream and then pases the data to a fstream like so: stringstream ss(stringstream::binary | stringstream::in | stringstream::out); ss.write(data, 512); // Loads data into stream // Uses a memory block to pass the data between the streams char* memBlock = ...
Use the streambuf members, that's what they are for: fout << ss.rdbuf();
3,738,248
3,738,326
Should I use an enum or multiple const for non-sequential constants in c++?
I'm writing porting file-io set of functions from c into a c++ class. "Magic numbers" (unnamed constants) abound. The functions read a file header which has a number of specific entries whose locations are currently denoted by magic numbers. I was taught by a veteran programmer a couple years back that using "magic ...
I can see two advantages to using an enum. First, some debuggers can translate constants back into enum variable names (which can make debugging easier in some cases). Also, you can declare a variable of an enumerated type which can only hold a value from that enumeration. This can give you an additional form of typ...
3,738,362
3,738,579
What's generally the size limit to switch from a vector to a deque?
I recent wrote this post: How best to store VERY large 2D list of floats in c++? Error-handling? Some suggested that I implemented my 2D list-like structure of floats as a vector, others said a deque. From what I gather vector requires continuous memory, but is hence more efficient. Obviously this would be desirable i...
There are so many factors to consider that it's impossible to give a clear answer. The amount of memory on the machine, how fragmented it is, how fragmented it may become, etc. My suggestion is to just choose one and use it. If it causes problems switch. Chances are you aren't going to hit those edge cases anyway. ...
3,738,556
3,738,633
how to implement casting to a private base class in C++
How to implement casting to a private base class in C++? I don't want to use hacks such as adding a friend etc. Defining public casting operator does not work. EDIT : For example I have: class A { //base class } class AX : private A { //a child } class AY : private A { //another specialized child } class B { //base ...
If defining a public casting operator does not work, you can try with a regular function: class D: private B { public: B& asB() { return static_cast<B&>(*this); } }; ... D d; d.asB().methodInB(); ... Anyway, what is the point? If D derives privately from B, then you are not supposed to use a D as a B from ...
3,738,752
3,738,977
Opening a terminal from Linux Makefile
Can we open a new terminal tab or window from the existing terminal using a makefile or some c file. If yes how? Thanks in advance for replying. P.S. I want to do this because first in the terminal I want to run the server file then I want to open the new terminal and there run the file for the client. From the second ...
You could try running xterm (the most available terminal window program) with the program to run as the shell argument. xterm ./my_client & For this to work the DISPLAY environmental variable would have to be set to something usable (which it probably will be if you are running X windows locally -- if you are connecti...
3,738,940
3,739,185
Efficient memory storage and retrieval of categorized string literals in C++
Note: This is a follow up to this question. I have a "legacy" program which does hundreds of string matches against big chunks of HTML. For example if the HTML matches 1 of 20+ strings, do something. If it matches 1 of 4 other strings, do something else. There are 50-100 groups of these strings to match against these c...
I'm not sure just how slow the current implementation is. So it's hard to recommend optimizations without knowing what level of optimization is needed. Given that, however, I might suggest a two-stage approach. Take your string list and compile it into a radix tree, and then save this tree to some custom format (XML mi...
3,739,062
3,739,305
C++ pipes in Objective-C
I made the transition from C++ to objective-C a while ago, and am now finding NSLog() tiresome. Instead, still in Objective-C, I would like to be able to write something like stdout << "The answer is " << 42 << "\n"; (I know that NSLog prints to stderr, I could put up with writing stderr << "Hello world";) Basical...
You really should get used to format strings as in NSLog. The C++ style syntax may be easy to write, but it is a nightmare to maintain. Think about internationalization. A format string can easily be loaded at runtime. Cocoa provides the function NSLocalizedString for that. But for C++’s stream operators you probably h...
3,739,617
3,739,620
Suspending system using c++ program
I am trying to suspend my system using a c++ program using SetSuspendState method but I am facing issue during linking. I am using g++-4 (GCC) 4.3.4 20090804 (release) 1 compiler on Windows 7 OS (64bit). The code I have written is #include <iostream> #include "windows.h" #include "powrprof.h" using namespace std; int...
As msdn says you need to link PowrProf.lib.
3,739,905
3,739,960
Runtime error accessing a vector
In my C++ project, I have a class App, and a class Window. Class App has a parameter: vector<Window*>* window;. In App's constructor, it is able to use and push_back a Window* onto this vector fine, but in my onMessage() method, which is called by the WndProc() (I'm using winapi), it gives me an runtime error when I tr...
Either the pointer to the vector is invalid or the pointers in the vector are invalid; probably the former in this case. This happens in many situations, such as using pointers to local objects which have since been destroyed. (Aside: Given that you included a semicolon for window, I bet this is a data member rather t...
3,740,038
3,740,108
What language to use for text editor?
I feel like writing a (rich) text editor mainly to be used for note-taking, in either C or C++, using most probably GTK or Qt for the UI. The problem is that I can't really decide what to use. I know both C and C++, C a little better. I've never used Qt but I'm completely fine with learning, and I have some experience ...
I'm writing an editor myself, and I too have choose C++ and Qt. The reasons for this: C++ is CPU- and memory-efficient. I hate slow text editors with a passion. Supporting libraries are almost always written in C or C++, so I can interface nicely with them (and extend them if needed). Qt is a great, well supported, cr...
3,740,149
3,756,243
Is it normal for WSASend to fail during big file transfers?
I need a little help if someone's got a minute. I've written a web server using IO completion ports, but I am having some trouble sending out large files. Web pages seem to load fine, but during large file transfers, WSASend() fails after a few minutes with error "The specified network name is no longer available." Rig...
Finally figured it out. from Rogers Internet Terms of Service: Without limitation, you may not use (or allow anyone else to use) our Services to: (xvi) operate a server in connection with the Services, including, without limitation, >mail, news, file, gopher, telnet, chat, Web, or host configuration servers, multimedi...
3,740,282
3,740,289
Binary Numbers. Error When Checking to be sure binary input is binary
I'm writing a simple loop to make sure my input is a valid binary. Ex: I want to throw an error when any number higher than one is user input. I know I need to check against the ASCII numbers. What is going on here? I should not be getting an error when I input binary. Any thoughts? for (int i=0;i<size;i++) { print...
You need to use if (int(binary[i]) != 48 && int(binary[i]) != 49) - note && rather than ||. As it stood, the if(...) was effectively if(true) as binary[i] could not be both 48 and 49 simultaneously.
3,740,291
4,390,104
Rebuild without recompiling the precompiled headers
Sometimes I need to perform a rebuild of my project but I don't want the pre-compiled headers to be recompiled every time I do that - sort of defeats the purpose, at least in this case. Is there any way to get Visual Studio to rebuild without recompiling the PCH and compile the PCH as needed (if the rarely changed head...
Write a script for it and add it to the tools menu using 'Tools->External Tools...', giving you a solution 'Within the IDE'. Your delete-exe-files script can include the build step as per: How do I compile a Visual Studio project from the command-line?
3,740,374
3,740,384
Behaviour after using malloc in C++
Does the following code invoke undefined behaviour? As far as I know we should always use new to create user defined objects dynamically because new in addition to malloc calls the constructor too. #include <cstdio> #include <cstdlib> struct om { int a; void fun() { a=10;b=10; } private : i...
malloc isn't guaranteed to initialize the memory it allocates - if you want the memory to be filled with 0's then use calloc.
3,740,471
3,740,585
C++ Copy Constructor + Pointer Object
I'm trying to learn "big three" in C++.. I managed to do very simple program for "big three".. but I'm not sure how to use the object pointer.. The following is my first attempt. I have a doubt when I was writing this... Questions Is this the correct way to implement the default constructor? I'm not sure whether I n...
Am I correct in saying that I need to delete the pointer in destructor? Whenever designing an object like this, you first need to answer the question: Does the object own the memory pointed to by that pointer? If yes, then obviously the object's destructor needs to clean up that memory, so yes it needs to call delet...
3,740,831
3,740,870
Interrupts in C/C++??? How are they implemented / coded?
Having programmed microcontrollers before and being interested in trying my hand at building an NES emulator at some point, I was really wondering how interrupts are implemented in C++? How, for example, does a program know how to react when I speak into my mic or move my mouse? Is it constantly polling these ports? Wh...
This is an implementation-specific question, but broad strokes: direct access to hardware via interrupts is generally limited to the OS (specifically, to the kernel.) Your code will not have such access on any modern system. Rather, you'd use OS-specific APIs to access hardware. In short: desktop operating systems do n...
3,740,876
3,740,892
C++ passing reference to class' private variable - compiler issue?
Is the passing by reference of a private variable in a class to be directly changed outside that class acceptable practice? Or is this something that the compiler 'should' pick up and prevent? Example: //------------------------------------------- class Others { public: Others() {}; void ChangeIt(string &str) { str =...
There is nothing to prevent, you pass your private member by reference. The function you are calling isn't accessing your private member, it is changing it's own argument (that happens to be the member of some class). The code is OK, but the important thing is that the function you called doesn't keep a reference to yo...
3,741,026
3,741,046
What is the difference between function templates and class templates?
I am confused about the strange syntax provided by C++ function templates and class templates. Take a quick look at the code below: #include <iostream> #include <algorithm> #include <functional> #include <iterator> #include <vector> using namespace std; template <class op1,class op2> class compose_fg_x_t : public una...
Template arguments can only be deduced for function templates, not for class templates. The whole point of helper functions such as make_pair (or your compose_fg_x) is to circumvent this limitation. Here is a slightly less complicated example that demonstrates the problem: #include <utility> int main() { auto x = ...
3,741,029
38,130,040
Tool for quickly creating project skeletons
I has been a C++ and Python developer for a looong time, and after this many years the place I feel most comfortable for developing is the old good gvim and the command line. I was wondering if there is some sort of tool for setting up projects quickly. Something like generating a bunch of files where a few things can ...
There are many tools like this. Cookiecutter is written in Python, and it has project templates for many languages and frameworks.
3,741,421
3,741,628
What are the units of winpcap captured packets, Layer 2 frames or layer 3 packets?
Just a wondering while developing a network traffic inspection program, no context is relevant!
It captures the entire Layer 2 frame. The layer 2 frame contains layers 3-7 PDUs assuming the frame is based on some protocol.
3,741,514
3,741,601
Member access in Inheritance Hierarchy - C++
struct A { protected: int y; public: int z; }; struct F : A { public: using A::y; private: using A::z; }; int main() { F obj_F; obj_F.y = 9; obj_F.z = 10; } Source: http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/index.jsp?topic=/com.ibm.vacpp7a.doc/language/ref/clrc14cplr135.htm In the above c...
The code is valid according to the Standard - see this Standard rule, which I did not have in mind when I answered before A member m is accessible when named in class N if [...], or there exists a base class B of N that is accessible at the point of reference, and m is accessible when named in class B. This entir...
3,741,533
3,741,546
calling function in c++ program where function is declared in other c++ program
how can one called function in c++ program where function is declared in other c++ program? how can one do this? can i use extern?
I would suggest the best way is to refactor the first C++ program such that the required function is made part of a library. Then both your programs can link to that library and the function is available to both (and to any other programs requiring it). Take a look at this tutorial. It covers how to create and then use...
3,741,596
3,741,963
Strange behavior of debugger when #line control is used
I used below code and tried to debug in Visual studio 2008 by pressing F10. //test.cpp #include<iostream> using namespace std; int main(void) { #line 100 "test.cpp" cout<<"Inside main()"<<endl; return 0; } Below is the debugger screen shot. #line 100 tells compiler to go to line 100 to get its next line. As 10...
This directive should be used by code generators. Tools that translate from one language to another. So that when you debug that code, the debugger will show the source file of the original language, stepping through the statements of that language. Instead of the (often cryptic) statements in the translated code. W...
3,741,666
3,741,699
Non type template parameters of reference
What is the use of 'non type template' parameters which are of 'reference' type? Why are such parameters also treated as 'rvalues'? template<int &n> void f(){ &n; // error } int main(){ int x = 0; f<x>(); }
f<x> is invalid. My compiler compiles your templated function without the bad call just fine, by the way. template<int &n> void f(){ int* ptr = &n; } int something = 0; int main() { f<something>(); // success int x; f<x>(); // C2971: Cannot pass local var to template function }
3,741,738
3,742,032
Visual C++'s implementation of std::map
How is std::map implemented in Visual C++? I know that some tree data structures just flag nodes as deleted when they are removed, instead of removing them right away. I need to make sure that my elements are never compared to elements which are no longer in the map. EDIT: I know that the implementation is probably cor...
Whether the implementation maintains nodes that have been erased or not, it must call the contained object destructor when the node is erased. After that, it cannot possibly pass the object to a comparison function as that would cause undefined behavior, which would make it a non-conforming implementation.
3,741,983
3,742,185
objectCast Sideways casting
I'm trying to replace all dynamicCasts in my code with QT's objectCast. But I've run into a bit of a snag. Here's the hierarchy of my objects: class ABase : public QObject class IAbility; // Registered as Qt Interface class ISize; // Registered as Qt Interface class Derived : public ABase, public IAbility, public ISi...
As I see it you have three options: You relate the two interfaces to each other by putting them in an inheritance hierarchy, letting one inherit the other. This will let you cast from one to the other, in one direction, but will also be clonky and wonky if there is no real realtion between the two. You create a super ...
3,742,122
3,742,151
Data Types in Accelerate.framework
I'm working on a program that uses the Accelerate framework (for LAPACK) and I have several issues. The code is written in C but needs to include C++ headers. I renamed the file to .cpp but it caused two errors, shown below. So I then realized tried to #include <Accelerate/Accelerate.h> to include the headers, since...
You should use call dgemm_ and dposv_ using the type __CLPK_integer or long instead of int. The error is because a long* cannot be implicitly converted to an int* in C++. typedef long int __CLPK_integer; typedef long int __CLPK_logical; typedef float __CLPK_real; typedef double __CLPK_doublereal; type...
3,742,405
3,742,651
What would be the best way to wrap up this void pointer?
Alright, I have library I wrote in C that reads a file and provides access to its' data. The data is typed, so I'm using void pointer and a few accessor functions: typedef struct nbt_tag { nbt_type type; /* Type of the value */ char *name; /* tag name */ void *value; /* value to be casted to the corre...
This can do the job: template <int> struct TypeTag {}; template <> struct TypeTag<TAG_BYTE> { typedef char type; }; // ... template <> struct TypeTag<TAG_COMPOUND> { typedef vector<Tag> type; }; template <int tag> typename TypeTag<tag>::type getValue(nbt_tab* t) { if (t->type != tag) ... // throw an exception ...
3,742,526
3,742,601
Dynamic matrix with contiguous storage
I want a matrix container class that has similar functionality to vector<vector<type>>, but stores elements in contiguous memory. I bet there is none in the standard library (including C++0x); does Boost provide one?
It looks like you want the misleadingly-named Boost Matrix. The templated class matrix is the base container adaptor for dense matrices. For a (m x n)-dimensional matrix and 0 <= i < m, 0 <= j < n every element mi, j is mapped to the (i x n + j)-th element of the container for row major orientation or th...
3,742,533
3,742,549
static main from static class?
I'm trying to figure out why this is not working. I want to do like in Java where main is a static function in a class but this is producing unresolved external symbol error: static class MainClass { public: static int _tmain(int argc, char* argv[]) { return 0; } }; Why doesn't this work? Tha...
C++ does not work like that. You need main as a function: int main(int argc,char* argv[]) { //STUFF }
3,742,717
3,742,725
Is it always better to use pass by reference in C++?
Possible Duplicates: “const T &arg” vs. “T arg” How to pass objects to functions in C++? I used the following code to ascertain that C++ on passing objects as const reference the compiler does not make a copy of the object and send the copy. The output confirmed that passing object as const reference does not involv...
Look at this link which describes exactly what you want to know. Basically, if you have to do the copy, pass by value.
3,742,740
3,742,818
How to Define or Implement C# Property in ISO C++?
How to Define or Implement C# Property in ISO C++ ? Assume following C# code : int _id; int ID { get { return _id; } set { _id = value; } } I know C# convert the get and set lines to getXXX and setXXX methods in compile time. in C++ , programmers usually define these two function manually like : int _id; in...
As Alexandre C. has already stated, it's very awkward and not really worth it, but to give an example of how you might do it. template <typename TClass, typename TProperty> class Property { private: void (TClass::*m_fp_set)(TProperty value); TProperty (TClass::*m_fp_get)(); TClass * m_class;...
3,742,772
3,743,274
How to convert a binary search tree into a doubly linked list?
Given a binary search tree, i need to convert it into a doubly linked list(by traversing in zig zag order) using only pointers to structures in C++ as follows, Given Tree: 1 | +-------+---------+ | | 2 3 | | ...
This is a Breadth-first search algorithm. Wikipedia has a good explanation on how to implement it. After implementing the algorithm, creating your linked list should be a no-brainer (since it will only be a matter of appending each visited element to the list)
3,742,814
3,742,826
new/delete "override" vs. "overload"
I always thought... overriding means reimplementing a function (same signature) in a base class whereas overloading means implementing a function with same name but different signature ... and got confused because sometimes people just don't care about the difference. Concerning new/delete: Are they overloaded or ove...
For the global operator new and operator delete, it's actually neither overloading nor overriding. A program is permitted to replace the default, implementation-provided definitions with its own definitions. The C++ standard says (§3.7.3/2): The library provides default definitions for the global allocation and deal...
3,743,093
3,743,099
Assign derived class to base class
Is it safe to do the following or is it undefined behaviour: class Base { private: int a; }; class Derived : public Base { private: int b; }; Base x; Derived y; x = y; // safe? Do the extra bits in derived classes just get sliced off?
You are right, the object is sliced. This is a common problem. You shouldn't do it!
3,743,120
3,743,138
A way to read data out of a file at compile time to put it somewhere in application image files to initialize an array
considering visual C++ compiler, Lets say I've got a file with whatever extension and it contains 100 bytes of data which are exactly the data that I want to initialize an array of char data type with a length of 100 characters with, Now apparently one way is to read those data out of file by using I/O file classes or ...
Write a program that reads the 100 byte data file and generates as output, a file, with c++ code/syntax for declaring an array with the 100 bytes in the file. Include this new generated file(inline) in your main c++ file. Call the c++ compiler on the main c++ file.
3,743,122
3,743,702
What is the correct way to implement the comparison for a base class?
I have a base class class Animal with pure virtual functions, and a set of derived classes class Monkey : public Animal class Snake : public Animal I want to implement a comparison operation so that, if I encounter two pointers to Animals in my code Animal* animal1 Animal* animal2 I can compare them to each othe...
Wow, a lot of the other answers were so totally unnecessary. dynamic_cast- it exists, use it. class Animal { public: virtual bool operator==(const Animal& other) = 0; virtual ~Animal() = 0; }; template<class T> class AnimalComp : public Animal { public: virtual bool operator==(const Animal& ref) const { ...
3,743,441
3,743,460
includes inside a namespace
Is the following approach correct? Well i get a compilation error. a.hpp is #include <iostream> class a { public: void classa_f(); }; a.cpp is #include "a.hpp" void a::classa_f() { std::cout<< "a::classa_f\n"; } main.cpp #include <iostream> namespace myname { #include "a.hpp" } int main () { mynam...
namespace myname { #include "a.hpp" } Declares a class method myname::a::classa_f , which obviously doesn't exist in your program. It's not valid.