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 |
|---|---|---|---|---|
5,775,281 | 5,775,303 | c++: what's the difference between new Object() and Object() | so in C++ you can instantiate objects using the new keyword or otherwise...
Object o = new Object();
but you can also just do
Object o = Object();
what exactly is the difference b/w the two and why would I use one over the other?
| You can't do Object o = new Object(); The new operator returns a pointer to the type. It would have to be Object* o = new Object(); The Object instance will be on the heap.
Object o = Object() will create an Object instance on the stack. My C++ is rusty, but I believe even though this naively looks like an creation... |
5,775,339 | 5,775,365 | how to declare variables in class? | I have following code:
class one
{
public:
typedef int (*funPtr) (void);
one()
{
// here I'm using map variable which is private.
}
~one(){}
private:
typedef map<int, funPtr> mMap;
mMap mapVar;
};
In this case class constructor gives that error that map is not declared. Can anyone help me?
| A typedef defines a type...basically an aliasing...if you wish to declare a variable mMap of type map you would just do
map mMap;
|
5,775,376 | 5,776,759 | C++ Abstract Class as std::map key | I have a class hierarchy like this:
struct Vehicle {
virtual string model() = 0; // abstract
...
}
struct Car : public Vehicle {...}
struct Truck : public Vehicle {...}
I need to keep a std::map with some information that I acquire about some Vehicle instances:
std::map<Vehicle, double> prices;
However I get the ... |
You need to use pointers to Vehicle.
operator== is not used by the std::map but a compare functor which is the third parameter of the std::map. By default it is std::less. You need to implement your own compare functor to work with Vehicle:
struct less_vehicle: std::binary_function<const Vehicle *, const Vehicle *,... |
5,775,383 | 5,775,398 | A weird problem with command printf | I am using Simple Scalar toolset to run some simulations on cache associativity. And I am seeing some strangest behavior with printf function. Here is the code snippet:
printf(" Name: %s %d %d %d \n", name, nsets, cp->set_shift, cp->set_mask);
printf(" Name: %s %d %d %d \n", name, cp->set_mask, nsets, cp->set_shift);
... | Go look at the variable declarations. My guess is somebody is a short or long, not an int. Since printf can't check what you pass for validity, it decides how many bites to grab from the stack based on the % signs. If your args don't agree with the format, not a compile error, but garbage can come out.
|
5,775,416 | 5,775,526 | Mystifying For-Loop Error | I am using Ubuntu 10.10, Codeblocks IDE, and gcc compiler. I noticed the program I am writing was creating some odd output. Eventually I narrowed the issue down to a for-loop in the program. I was surprised to discover that the following basic for-loop didn't perform as expected.
#include <iostream>
using namespace s... | maybe the screen just scroll?
try to redirect the output to a text file
|
5,775,743 | 5,775,939 | Can I lock an element in a list to make it threadsafe, instead of locking the whole list? | I would store objects in my std list on thread-safe way. I don't want to block a thread, if it want to access an element that currently not in use.
If I can't lock only one element, there is an other question: If I call a destructor on one of my object in the list, will it remove the element and invalidate it's iterato... | Generally you need to protect the whole list container instance by a lock or mutex in multi threaded environment.
If you are storing new'ed objects in your container, then the destructor will be called only when you are deleting the pointer to the object.
Further answer to your question depends upon:
1. What are yo... |
5,775,785 | 5,775,884 | Accessing variables outside the program in C++ | id.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
static int a;
};
int A::a=20;
class b
{
public:
b()
{
cout<<A::a<<endl;
}
};
int main()
{
b *b1 = new b();
return 0;
}
id1.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class c
{
pu... | Two separate programs as shown (they're separate because they both define main()) cannot share variables in any simple way.
If the two separate files were to be integrated into a single program, so one of the main() programs was replaced, then you would fall back on the standard techniques of declaring the variable A::... |
5,775,790 | 5,775,825 | How do I output a compile-time numeric constant during compilation in Visual C++? | Visual C++ has #pragma message that outputs a string into compiler output. Now I have a factory:
template<class Type>
CComPtr<Type> CreateComObject()
{
CComPtr<Type> newObject( new CComObject<Type> );
//do some tuning to the object
return newObject;
}
and I want to output the size of class that is passed to n... | If I understood your question correctly, then I think you can do this:
template<size_t size>
struct overflow{ operator char() { return size + 256; } }; //always overflow
//if you doubt, you can use UCHAR_MAX +1 instead of 256, to ensure overflow.
template<class Type>
CComPtr<Type> CreateComObject()
{
CComPtr<Type>... |
5,775,920 | 5,776,016 | How to avoid "redefinitions" when using multiple external libraries? | I have two libraries (third-party), and within each of these libs they have defined two classes with same name (in header files).
// Lib A, HeaderA.h
struct mycompare
{
//Some code
};
// Lib B, HeaderB.h
struct mycompare
{
//Same code
};
Please note that, in both libs, mycompare name and the implementation is same. H... | Assuming you can't edit the headers/libraries:
indirection: create your own out-of-line wrapper for the simpler of A and B, which includes HeaderA.h or HeaderB.h only in the implementation.
this is similar to but much less work and coupling than Als's option 2 ;-)
shameless hackery: include HeaderA.h, then #define m... |
5,775,996 | 5,776,030 | read in raster order? | hey guys,
i have a c++ programming assignment that asks me to create a matrix and store its elements (given by the user) as an array, read in raster order. i've looked around for the meaning of "raster order" and i haven't seen anything about it. any help? thanks.
| Raster scan order means "in order of input/output" - in case of matrix it will mean line-by-line (you could of course store column-by-column instead, but that's not what the assignment asks for).
|
5,776,026 | 5,776,162 | Convert C++ code to C# | I have code wrote on C++:
char szTempString[1500];
DWORD dwDataLength = PacketBuffer.m_Length - (sizeof(ether_header) + pIpHeader->ip_hl*4 + pTcpHeader->th_off*4);
PCHAR pData = (PCHAR)pEthHeader + (sizeof(ether_header) + pIpHeader->ip_hl*4 + pTcpHeader->th_off*4);
// If packet contains any data - proc... | .NET's char is actually unicode, not like in c++. You should at least replace char by byte. Then, when you ultimately want a string from bytes, use the Encoding class, like this: Encoding.Default.GetString(bytes)...
|
5,776,206 | 5,776,415 | Dynamically allocated linked list in c++.What to do after exception to prevent memory leak? | I like to implement linked list in c++ ,while adding new node I dynamically allocate it,
if some allocation fails I would like my program to stop the execution.
After the "new Node" fails the exception is thrown so do I have to call the destructor explicitly in the exception handler.
how can I deal with this situation ... |
After the "new Node" fails the exception is thrown.
so do I have to call the destructor explicitly in the exception handler.
No. If the constructor did not finish then you can not call the destructor (the object was never created).
how can I deal with this situation in order to prevent memory leak?
If the exception... |
5,776,514 | 5,777,539 | My explicit instantiation of template class seems doesn't work | I wrote a short program to test the template class's explicit instantiation as follows:
#include <iostream>
template <class T>
struct less_than_comparable {
friend bool operator>=(T const& a, T const& b) {
return !(a < b);
}
};
class Point {
friend bool operator<(Point const& a, Point const& b) {
... | The problem is that friend functions defined inside class-like types are not injected into enclosing namespace.
The principle you are refering to is called "friend name injection", but this has been replaced in current C++ standard by "ADL" (Argument Dependent Lookup, also called Koenig Lookup). ADL examines all namesp... |
5,776,529 | 5,776,541 | int *array = new int[n]; what is this function actually doing? | I am confused about how to create a dynamic defined array:
int *array = new int[n];
I have no idea what this is doing. I can tell it's creating a pointer named array that's pointing to a new object/array int? Would someone care to explain?
| new allocates an amount of memory needed to store the object/array that you request. In this case n numbers of int.
The pointer will then store the address to this block of memory.
But be careful, this allocated block of memory will not be freed until you tell it so by writing
delete [] array;
|
5,776,694 | 5,776,809 | how to create multidimensional, dynamically defined array? | i know how to create a single-dimensional, dynamically defined array
string *names = new string[number]; //number specified by the user
however, when i try to make it multidimensional
string *names = new string[number][number]; //doesn't work
it doesn't work. what gives? i found this http://www.cplusplus.com/foru... | I tried to provide some explanations to example from your link:
// To dynamically allocate two-dimensional array we will allocate array of pointers to int first.
// Each pointer will represent a row in your matrix.
// Next step we allocate enough memory for each row and assign this memory for row pointers.
const int ... |
5,776,777 | 5,776,814 | What is the proper use case for dynamic_cast? | I have been told many times (and seen myself in practice) that the use of dynamic_cast often means bad design, because it can and should be replaced with virtual functions.
For example, consider the following code:
class Base{...};
class Derived:public Base{...};
...
Base* createSomeObject(); // Might create a Derived... |
It can be easily seen that instead of writing dynamic casts we can just add a virtual function doStuff() to Base and re-implement it in Derived.
YES. That is what virtual functions are for.
class Base
{
public:
virtual void doStuff();
};
class Derived: public Base
{
public:
virtual void doStuff(); //o... |
5,776,826 | 5,777,075 | Discrepancy in Snippet | Though the two snippets below have a slight difference in the manipulation of the find variable, still the output seems to be the same. Why so?
First Snippet
#include<iostream>
using namespace std;
int main()
{
int number = 3,find;
find = number << 31;
find *= -1;
cout << find;
ret... | In both your samples, assuming 32bit ints, you're invoking undefined behavior as pointed out in Why does left shift operation invoke Undefined Behaviour when the left side operand has negative value?
Why? Because number is a signed int, with 32bits of storage. (3<<31) is not representable in that type.
Once you're in u... |
5,776,862 | 5,776,896 | Template class - unresolved external symbol(s) | I get this error a LOT, and i never know why. Can someone help me find the cause of it?
Edit:Removed code
| Put the implementation (your method definitions) into the header along with the class declaration (see this in the C++ FAQ). Some compilers have supported an "export" keyword for doing it the way that you did, but that has been nixed in the C++0x.
|
5,776,868 | 5,776,946 | Pointer validity after stack unwinding | In C++ does a pointer remains valid after stack unwinding or not?
| It depends on what your pointer is pointing to. If it points to heap memory, it still remains valid. If it points to stack memory, it becomes invalid.
|
5,776,961 | 5,777,800 | How can I initialize the d (pointer) of the pimple idiom of an static class? | Here is my header code:
#ifndef CLANDTYPES_H
#define CLANDTYPES_H
class CLandTypes
{
public:
CLandTypes();
~CLandTypes();
private:
class Pimple;
static Pimple * d;
};
#endif // CLANDTYPES_H
because it should be a static class I tryed to code in my cpp file:
#include "clandtypes.h"
CLandTypes::Pimple ... | Move this line:
CLandTypes::Pimple * CLandTypes::d = new CLandTypes::Pimple();
to be after the class definition for CLandTypes::Pimple.
It's objecting to your attempt to use new to create an instance of a class it knows nothing about.
If you do this, remove the code that checks to see if d is nullptr (aka !d) in your ... |
5,777,007 | 5,777,184 | Random Number Generation with Well44497a in C++ | Sorry to bother again, but as I am new C++ I am having a lot of weird and silly problems.
I am programing a MCMC method. I read in this forum that the WELL RNG was a good alternative to generate random numbers so I am trying to make it work. So here the questions:
I am compiling the "Well44497a.c" within my c++ projec... | Your function appears to initialise the state array with the same values every time you call your sampler() function. The idea of the state array is that it holds the current state of the random number generator, and that you don't fiddle with the contents of state between calls to the RNG.
Make the state array global ... |
5,777,018 | 5,777,048 | Forward declaration issue | I have a cyclical redundancy circular dependency between two classes in my project, StatusEffect and BaseCharacter.
Both classes need to be aware of each other as the BaseCharacter needs to store a set of StatusEffects and StatusEffect needs to be able to do operations on BaseCharacter. I don't think it's possible to e... | You can't call a method through a pointer to a forward-declared class. You have to move this code somewhere where the class is already defined - for example into a .cpp file that includes both classes definition.
|
5,777,110 | 5,778,442 | Fast implementation of trigonometric functions for c++ | Short version: I'd like to know whether there are implementations of the standard trigonometric functions that are faster than the ones included in math.h.
Long version: I got a program that's quite heavy on numerics (it's a physics simulation) and that needs to call trigonometric functions, mostly sin and cos, a lot. ... | Here are some good slides on how to do power series approximations (NOT Taylor series though) of trig functions: Faster Math Functions.
It's geared towards game programmers, which means accuracy gets sacrificed for performance, but you should be able to add another term or two to the approximations to get some of the a... |
5,777,137 | 5,777,165 | Templates in c++,typename and class | What is the difference between writing a template in c++ in the below both ways
template<typename T> & template<class T>
and when do we prefer them above each other?
If both are same,then why do we have them both if one is enough?
| No difference at all. I prefer first one (mostly), but that is my personal taste. The language doesn't make any difference between them.
For template parameters, the keywords typename and class are equivalent. §14.1.2 says:
There is no semantic difference
between class and typename in a
template-parameter.
If b... |
5,777,146 | 5,777,177 | Problem using templates in C++ | I am using templates for the first time in C++ and running into a problem when I try to compile. Basically trying to create my own basic ArrayList of sorts:
The .hpp:
#ifndef ARRAYLIST_HPP_
#define ARRAYLIST_HPP_
template <class T>
class ArrayList
{
private:
int current, top ;
T * al ;
public... | You need to include the implementation in the .hpp file. The compiler needs to know T at compile time to generate the specialization.
|
5,777,236 | 5,777,270 | GCC error: explicit specialization in non-namespace scope | I am trying to port the following code. I know the standard doesn't allow explicit specialization in non-namescape scope and I should use overloading, but I just can't find a way to apply this technique in this particular case.
class VarData
{
public:
template < typename T > bool IsTypeOf (int index) const
{
... | You just have to move your specializations of the member templates outside of the class body.
class VarData
{
public:
template < typename T > bool IsTypeOf (int index) const
{
return IsTypeOf_f<T>::IsTypeOf(this, index);
}
};
template <> bool VarData::IsTypeOf < int > (int index) const
{
return... |
5,777,409 | 9,858,542 | How to get last prepared and executed query using QsqlQuery ? | I'm doing an insert:
QSqlQuery myQuery(db);
myQuery.prepare("INSERT INTO mytable VALUES (:val1, :val2)");
myQuery.bindValue(":val1", 1);
myQuery.bindValue(":val2", 2);
myQuery.exec();
Then I need to get the executed SQL query for logging purposes.
myQuery.executedQuery() returns "INSERT INTO mytable VALUES (?, ?)".
Ho... | An alternative to what lightstep suggested, is to prepare query strings and then call a function that first writes the query to the log and only then calls real execute(). I personally use QString::arg() and "%number" for arguments to make a query string instead of bindValue().
Let's sum things up:
Solution #1 (lightst... |
5,777,484 | 5,777,610 | How to check if C++ compiler uses IEEE 754 floating point standard | I would like to ask a question that follows this one which is pretty well answered by the define check if the compiler uses the standard. However this woks for C only. Is there a way to do the same in C++?
I do not wish to covert floating point types to text or use some pretty complex conversion functions. I just need... | Actually you have an easier way to achieve this in C++. From the C++ standard 18.2.1.1 the class numeric_limits exists within std. In order to access said static member you simply do this:
std::numeric_limits<double>::is_iec559;
Or:
std::numeric_limits<float>::is_iec559;
Which should return true if IEEE 754 is in use... |
5,777,627 | 5,777,649 | Qt - Why is "&" used? | At the following web page: http://web.mit.edu/qt-dynamic/www/tutorials-tutorial-t2.html
In:
QObject::connect(&quit, SIGNAL(clicked()), &app, SLOT(quit()));
Why is & used with quit and app? Cannot we use quit and app without &?
Thanks.
| QObject::connect needs pointers to two objects. So you have to give it that.
(Since the link you posted is broken, can't be sure of what quit and app are.)
|
5,777,673 | 5,777,685 | Does constructing an iostream (c++) read data from the hard drive into memory? | When I construct an iostream when say opening a file will this always read the entire file from the hard disk and then put it into memory, or is it streamed in and buffered by the OS on demand?
I ask because one way to check if a file exists is to see if opening it fails, but I fear if the files I am opening are very l... | No, it will not read the entire file into memory when you open it. It will read your file in chunks though, but I believe this process will not start until you read the first byte. Also these chunks are relatively small (on the order of 4-128 kibibytes in size), and the fact it does this will speed things up greatly if... |
5,777,733 | 5,777,965 | Mock non-virtual method C++ (gmock) | I have class
class CSumWnd : public CBaseWnd
{
private:
bool MethodA()
}
Please can you help how to mock MethodA() without making virtual,
I didn't understand the concept of hi-perf dependency injection
| It means you will have to templatize your production code. Using your example:
CSumWind class definition:
class CSumWnd : public CBaseWnd
{
private:
bool MethodA()
};
Mocked CSumWnd class definition:
class MockCSumWnd : public CBaseWnd
{
private:
MOCK_METHOD(MethodA, bool());
};
Production class which have to b... |
5,777,955 | 5,778,006 | Sort while reading into a vector | I need to read in a list of 10,000 integers, and place them in a vector in ascending order. Note that I am not reading then sorting, I am sorting while reading.
I am doing this as a learning exercise. I realise that sorting while reading is O(n^2), while reading then sorting could be O(n + (n log(n)) with a quick sort ... | example time:
std::vector<int> target;
// reading
std::ifstream file("integers.txt");
int number;
while (file >> number)
{
target.insert(std::lower_bound(target.begin(), target.end(), number), number);
}
|
5,777,982 | 5,778,276 | doxygen comment multiple variables at once | If I have the following:
/**
* @brief (x,y,z) points for block
*/
int x, y, z;
It will only generate that documentation for x, is it possible in doxygen to get it to comment all x, y and z with one comment?
EDIT
Following the suggestions of envu I now have the following (based off http://www.doxygen.nl/manual/groupi... | I would use member groups http://www.doxygen.nl/manual/grouping.html#memgroup for this. The syntax and output is a little bit different to what you want to achieve, but I think that shouldn't hurt.
|
5,778,062 | 5,778,108 | Dynamic array of strings - C | I have an array of strings defined like this:
char** arrNames;
Now I want to dynamically allocate a size to it.
I have a function that receives the new size and the array above.
It goes like this:
char** AddName(char** arrNames, int nNameCount)
{
char** arrTemp;
arrTemp = new char[nNameCount];
...
// ... | If you want nNameCount strings, you need to allocate an array of arrays of chars (i.e an array of strings):
char** AddName(char** arrNames, int nNameCount)
{
char** arrTemp = new char *[nNameCount];
for (int i = 0; i < nNameCount; ++i) arrTemp[i] = new char[STRING_SIZE];
...
}
After this you can access ea... |
5,778,133 | 5,862,474 | Fetching CUDA texture problems | I am having trouble fetching a texture of floats. The texture is defined as follows:
texture<float, 2, cudaReadModeElementType> cornerTexture;
The binding and parameter settings are:
cornerTexture.addressMode[0] = cudaAddressModeClamp;
cornerTexture.addressMode[1] = cudaAddressModeClamp;
cornerTexture.filterMode... | Nvidia reply to bug report:
"The problem here is that the memory bound to the 2D texture does not have the proper alignment restrictions. Both the base offset of the texture memory, and the pitch, have certain HW dependant alignment restrictions. However, currently in the CUDA API, we only expose the base offset restri... |
5,778,258 | 5,778,291 | Specify N Directories where to look for input files | Just started learning C++ and my knowledge is quite basic on IT. I am using VC 2010.
How can I tell my code where to look for input files? Is there a way to tell the compiler to look for input files into a prespecified list of directories, e.g. M:/Test, M:/Project, etc.
I know I can add the whole path to a file in th... | If you want your program to look for files in different directories, you have to write the code to do so.
Or you need to pass in the full paths to your different data files.
There is no standard C++ function to "find a file in a set of directories".
|
5,778,294 | 5,779,459 | boost::bimap of shared_ptr & boost::transform_iterator | I have a boost::bimap<int, boost::shared_ptr<A>> container and want to return an iterator to the left view ensuring constness of the contents. Returning container.left.begin() returns an iterator that dereferences to std::pair<int const, boost::shared_ptr<A> const>.
Obviously, this is not what I want, since it's possib... | The problem is that your value_type is not actually a std::pair (and is not implicitly convertible to one), and thus cannot be passed to makeIterConst::operator().
Make it take const base_const_iterator::value_type & instead.
#include <iostream>
#include <string>
#include <boost/shared_ptr.hpp>
#include <boost/make_sha... |
5,778,319 | 5,778,806 | loop through a mpl::map | what is the simple way to loop through a mpl::map?
typedef mpl::string<'Curr'> key1;
typedef mpl::string<'Brid'> key2;
typedef mpl::map<pair<key1,int>, pair<key2,char> > m;
How can I loop through m ?
| Why don't you use mpl::for_each ? Something like:
mpl::for_each<
m,
typename mpl::lambda<
mpl::key_type<
m,
mpl::_1
>
>
>( do_some() );
|
5,778,512 | 5,778,542 | How to know value in the std::string/Cstring is number or not | I am getting command line argument when i launch the application.
I am getting four parameter from command line.
after parsing I store them in four std::string/CString(mfc) variable now i need to know whether the value is decimal or not.because these parameter is going to be used in some mathematical calculation.
Can... | here you can find how to determine if a string is a numeric, in 70 languages!
I'm not sure if all the solutions check the same thing. The C++ implementation checks if the input is a positive/negative integer/floating-point for base 10, or if it a is positive/negative integer for base 8/16. Is that what you want? Do you... |
5,778,560 | 5,779,693 | Will multiple calls to typeid(T).name() return the same pointer? | In C++ I can use typeid operator to retrieve the name of any polymorphic class:
const char* name = typeid( CMyClass ).name();
The string pointed to by the returned const char* will be available to my program for as long as the corresponding class exists.
Will multiple calls of typeid(T).name() return the same pointer ... | No they are not required to return the same pointer.
I have also seen in the wild system that do not.
Each DLL had its own copy of the type object that contained the nmae thus calling the typeid(N).name in shared lib A and shared lib B will result in a different pointer (Though the same underlying string).
|
5,778,907 | 5,779,230 | Help with this design | Right now, in my game gui API, I have, for example, a MouseListener.
This is just an abstract class with methods. Right now, the way it is used is as follows:
Lets say I want a Widget to accept mouse listeners:
I create a vector of mouse listeners and provide add and remove functions to remove listeners. Every time an ... | How do the things a listener is listening to (from now on called vocalizers) know about the listener? They store a pointer right?
If so I recommend giving the vocalizers a weak pointer to the listener. Once the listener destructs, the weak pointer will no longer be valid, so when the vocalizer attempts to notify the li... |
5,779,133 | 5,780,110 | Reading bits performance | I'm writing a helper class which I intend to use for reading bits in reverse from a data block.
I tried doing an optimization where I used "rol" instructions for masking the data. However, to my surprise this is actually slower than creating a new bitmask during each access.
class reverse_bit_reader
{
public:
stati... | If you're going to be reading bits sequentially out of longs, starting from the most significant bit, and you want it to be as fast as possible, could you do something along these lines?
#define GETBIT ((theBit = (theLong < 0)), (theLong <<= 1), theBit)
|
5,779,162 | 5,779,225 | Constructing a temp object and calling a method that returns a pointer - is it safe? | My intution says it isn't, but the fact that everything is going on in the same line is a bit confusing. I wonder if the pointer is still valid when cout uses it.
#include <iostream>
#include <string>
struct A {
A() : m_s("test"){ }
const char* c_str() { return m_s.c_str(); }
std::string m_s;
};
int main(... | Yes, it is safe. The temporary A() is destroyed at the end of the statement. That is after cout used the pointer returned.
|
5,779,276 | 5,779,311 | Stack implemented via a linked-list in C | The following code is part of a stack implementation, implemented via a linked-list, in C. Are there problems with the code? Specifically, in the pop() method the caller passes a void** argument so pop() can assign a pointer to the top node's data to it. pop() subsequently calls delete to free the stack's top node, w... | The pop implementation is okay as is. The Element structure and data pointer are two separate chunks of memory. Deleting the list element does not delete the data pointed to by its member. You can see that maybe more clearly in the push function. It creates a new Element and sets its data pointer to the given mem... |
5,779,318 | 5,779,358 | C++ Overloaded Function and Subclasses | Suppose I have:
struct Vehicle {...}
struct Car : public Vehicle {...}
string A(Vehicle *v) { return "vehicle"; }
string A(Car *c) { return "car"; }
And I do this:
Vehicle *v = new Car();
cout << A(v);
Why does the compiler print out "vehicle"? After all, v points to a Car object.
| The overloaded function A(Vehicle*) is a better match for argument of type Vehicle*. So the cout will print:
vehicle
Explanation:
The overloaded function resolution is done based on the static type of argument. And the static type of the argument v is Vehicle*. Therefore, the function A(Vehicle*) will be called.
|
5,779,379 | 5,779,406 | Making a generic function in C++ | I try to make a generic function in C++, that creating an array of a type which depends on usage (when calling it), like array of int or char.
This is the code in my header file:
template<class T>
T** makeArray(...);
This is in the .cpp file:
template<class T>
T** ClassA::makeArray(...){
//...
}
And this is how I... | In general, you cannot have template definitions in a source file; they should be in the header file so that the compiler can see them.
This comes up over and over again here, so I can't be bothered to give the full explanation again; I recommend you read this from the C++ FAQ: Why can't I separate the definition of my... |
5,779,390 | 5,924,184 | OllyDbg can't debug visual studio exe | I've just created a new vc++ exe with this simple code:
#include<stdio.h>
#include<string.h>
#include<windows.h>
int ExceptionHandler(void);
int main(int argc,char *argv[]){
char temp[512];
printf("Application launched");
try
{
throw "error";
}
catch (... )
{
ExceptionHandler();
}
return 0;
}
int Exceptio... | Compiler exceptions taken from olly as critical (wrong settings)
|
5,779,618 | 5,779,733 | Patterns for unit testing a C++ method that makes a standard library call | I'm writing a C++ class to wrap sockets (I know that there are good libraries for this--I'm rolling my own for practise):
class Socket {
public:
int init(void); // calls socket(2)
// other stuff we don't care about for the sake of this code sample
};
This class is in turn used by several others, which I know I can... | I would probably mock it by working through a socket interface (ie base class) and implementing a test version of that base class.
You can do this a couple of ways, for example the simplest thing is to specify the entire socket API in terms of a C++ interface.
class ISocket
{
public:
virtual int socke... |
5,779,624 | 5,779,694 | How to check if a window button is pressed C++ | How can I test if a button is being pressed ?
I am using EnumChildWindows() to enumerate the child windows of a given window, and one of the child window is a button, I want to test if that specific button is being pressed.
My code until know is:
BOOL CALLBACK MyEnumProc(HWND hwnd, LPARAM lParam)
{
char buffer[256]... | You can send the BM_GETSTATE message to the button control, if it is pressed the result will be
BST_PUSHED.
|
5,779,659 | 5,779,687 | Writing a cross-platform program | How could I write a program which runs on both Windows 7, Mac OS X (and maybe linux too)?
I heard Qt are a great framework to build cross-platform GUIs, but I think every program version need a recompile, isn't that right? And should I compile the win version under windows, the mac version under mac os x, the linux ver... | The underlying binary format is different on each platform, so unless you're using a virtual machine (like Java or Flash does) you will have to recompile your program on each platform.
Some compilers (like GCC) allow cross-compiling, but it is not trivial to set up. Probably the easiest system to cross-compile on is Li... |
5,779,703 | 5,788,415 | Automatic copy files to output during application building | There is Copy to Output Directory property for files in C# projects. But in VC++ projects it is absent. I know, that I can use Build events in VC++ and write there something like
xcopy /y /d %(FullPath) $(OutDir)
Is there a way to avoid the use of CMD (and other scripting methods)? Can msbuild do something to help in ... | It depends on what version of Visual Studio you are using. Format of VC++ project file in Visual Studio 2008 is not MSBuild and so using xcopy in PostBuildStep is a good choice.
VC++ project in Visual Studio 2010 has MSBuild format. Thus, there is functionality of MSBuild Copy task.
Below is a sample:
<Copy
SourceF... |
5,779,709 | 5,779,801 | C++: Makefile: object files not compiling? make then says objects not found | So, client.o and server.o are not being compiled... but the make file doesn't error...
I've checked the directory where all the code is and the sub folders. but client and server .o just aren't there... =\
here is my make file:
main_objects = src/main.o src/fann_utils.o src/Config.o
network_objects = src/neural_netwo... | g++ -c src/cloud/chat_client.cpp will build an object file called chat_client.o, not client.o. Either add -o $@ to the rule to create an object file with the same name as the target, or rename the file to chat_client.o everywhere it's mentioned in the makefile.
|
5,780,068 | 5,780,098 | Allocate CFString in subfunction | I want to allocate space for CFString in a subfunction. Something like this:
void fun(CFStringRef *ref)
{
ref = CFStringCreateWithCString(NULL, "hi", kCFStringEncodingUTF8);
}
int main(void)
{
CFStringRef ref;
fun(&ref);
CFShow(ref);
if(ref) CFRelease(ref);
return 0;
}
It does compile with a... | CFStringCreateWithCString() returns a CFStringRef, not a CFStringRef *. You have to dereference the pointer in the assignment:
*ref = CFStringCreateWithCString(NULL, "hi", kCFStringEncodingUTF8);
Edit: for your next question, please don't just say "it compiles with a warning". Tell us the actual warning message. It ma... |
5,780,083 | 5,780,123 | Header File Content Puzzle [Interview Question] | What should be the content of the header file Fill.hpp such that the following code works i.e both asserts work?
#include <iostream>
#include <string>
#include <cassert>
#include "Fill.hpp"
int main()
{
std::string s = multiply(7,6);
int i = multiply(7,6);
assert(s == "42");
assert(i == 42);
}
TIA
| Define conversion functions for converting a type multiply into int and std::string as shown in Method 1 or use Method 2 (similar to 1)
Method 1
struct multiply
{
int t1,t2;
operator std::string()
{
std::stringstream k;
k<<(t1*t2);
return k.str();
}
operator int()
{
... |
5,780,093 | 5,780,104 | Should I call the base class default constructor in the initialization list? | class A : public B
{
...
}
// case I : explicitly call the base class default constructor
A::A() : B()
{
...
}
// case II : don't call the base class default constructor
A::A() // : B()
{
...
}
Is the case II equal to case I?
To me, I assume that the default constructor of base class B is NOT called in case II... | The base class constructor is called in both cases.
Here is a link to an article with more info.
|
5,780,112 | 5,780,140 | Define a large bitset in C++ | In my program I need to check if I have already generated a value in a set of 2.5*10^9. I expect to generate about the half of the set and need to have a fast way to check and update it. The bitset seemed to me as a good idea as it takes not too much memory (1 bit per value) and is fast.
The problem is that when I defi... | This may not be your problem, but try to allocate the bitset on the heap with new, instead of using the stack.
Some systems limit the size of the stack, which might be what causes problems for you.
|
5,780,124 | 5,780,178 | Netbeans 7 and C/C++ blocks | Apple's non-standard language extension, "blocks" (like closures) isn't supported by the parser in Netbeans 7.
I'm a bit unsure as to why this is, since I thought the parser just relied on the compiler.
Is it possible to get Netbeans to recognize the block syntax in any way?
Xcode 4:
Netbeans 7:
| Most syntax highlighters do not depend on the compiler in that they do not use compiler outputs. In the general case, most have some type of logic or rule that does the syntax highlighting at runtime.
Otherwise you would have to wait to compile the program to have highlighting.
|
5,780,131 | 5,780,188 | Possible to write C# DLL (plugin) for a C++ application? | I'd like to write a plugin (DLL) for a C++ application but I'd like to use C#. Is this possible? I don't have access to the C++ code so I can't modify it.
From what I've gathered, the C++ (host) application just makes calls to different functions.
Here's a C++ sample plugin function:
void On_Start(HINSTANCE hInstance... | Not directly, but you could write a shim in C++/CLI that exports the native function then delegates the actual implementation to a C# assembly.
Keep in mind, however, that this is probably a bad idea -- only one version of the CLR may run in a given process, so if someone else writes a managed plugin for the C++ applic... |
5,780,251 | 5,780,324 | How to draw tiled image with QT | I'm writing interface with C++/Qt in QtCreator's designer. What element to chose to make as a rect with some background image?
And the second question: how to draw tiled image? I have and image with size (1×50) and I want to render it for the parent width. Any ideas?
mTopMenuBg = QPixmap("images/top_menu_bg.png");
mTo... | If you just want to show an image you can use QImage. To make a background with the image tiled construct a QBrush with the QImage. Then, if you were using QGraphicsScene for example, you could set the bursh as the background brush.
Here is an example which fills the entire main window with the tiled image "document.... |
5,780,284 | 5,780,323 | Best practice to use bitwise parameter combinations using enums? | I am implementing a view that lives on a screen. Based on the following configuration parameters the view will be positioned and resized whenever the screen size changes.
enum DLViewLayout
{
DLViewLayoutSolo = 1,
DLViewLayoutDual = 2
};
enum DLViewFixedHorizontalProperty
{
DLViewFixedHorizontalPropertyWidth... | You want to combine flags using values from differing enumerations?
This is never going to be best practice, in fact, I've never seen it in any practice, good or bad. This way, among other issues, any element utilising an instance which exposes a property of these flags must know, or be expected to know, that it's an ... |
5,780,368 | 5,780,429 | Calling a C# function from unmanaged c++ (via a managed wrapper) | I have C++ source & headers for a set of libraries which I need to call from a C# application. I've created a managed C++ wrapper around the functions I need and am able to call them from C# marshalling the data backwards and forwards.
Now the hard part..
My unmanaged C++ library generates status messages as it runs a... | You can pass a .NET delegate to a C++/CLI function that takes a pointer to a function with "matching" arguments.
Caveats
The pointer-to-function must be STDCALL calling conventions
If the delegate is a member of an object, this pointer to function will not count as a reference to keep the object alive. You have to m... |
5,780,399 | 5,782,452 | OpenAL: How to use linear attenuation? | I want to control the way how the sound source volume fades out by distance, how can i do this?
Edit: I would also like to know how to scale the sound coordinate system accordingly: i dont want to hear some sound VERY far away from the source: now i would have to change my rendering code to scale coordinates to make it... | That'll be alDistanceModel(AL_LINEAR_DISTANCE) or better alDistanceModel(AL_LINEAR_DISTANCE_CLAMPED), which will turn distant sources off entirely.
Read chapters 3.4.3 and 3.4.4 here. You also have to set the parameters in the formulas listed there (AL_MAX_DISTANCE and AL_REFERENCE_DISTANCE) for each source (alSourcef)... |
5,780,469 | 5,780,510 | How can text in my main C++ file (in code that hasn't executed yet) show up in a string? | I'm new to C++ so there's a lot I don't really understand, I'm trying to narrow down how I'm getting exc_bad_access but my attempts to print out values seems to be aggravating (or causing) the problem!
#include <iostream>
#include "SI_Term.h"
#include "LoadPrefabs.h"
int main() {
SI_Term * velocity = new SI_Term(1... | I'm tempted to say that SI_Term is messing with the stack (or maybe trashing the heap). Here's a great way to do that:
char buffer[16];
strcpy(buffer, "I'm writing too much into a buffer");
Your function will probably finish, but then wreak havoc. Check all arrays you have on the stack and make sure you don't write ou... |
5,780,578 | 5,780,629 | C++ -- type of the division? | I want to make sure that my understanding of the return type of C++ division,
int / int => return is int?
float / float => return is which type? float?
double /double => return is double?
int / double => return is double?
int / float => return is float?
Please correct me if I am wrong.
| All of those are correct. Here's what the C++03 standard says (§5/9):
Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual ari... |
5,780,620 | 5,782,013 | VA and memory addresses | This should be a simple question: I know that VA = RVA + imagebase for a PE, now I'm trying to locate in a disassembler a string and happens to be located at 0042720E in the .text section.
The imagebase is 400000 and 2720E is the RVA, it is okay till now.
But why when I load the exe in a debugger the memory where the i... | There are really only two possibilities: a reallocation occured or you got the RVA wrong. The more likely is its a reallocation, especially if your running on windows vista or windows 7 due to ASLR. Depending on how you attached and what debugger your using, its possible to get the debugger to adjust the reported addre... |
5,780,646 | 5,781,223 | Variadic functions on Arduino | I am programming in Arduino 022 for the Arduino Mini Pro. I have the following function:
String join(const String str, ...) {
Serial.println("join");
va_list args;
va_start(args, str);
Serial.println("result init");
String result = "";
for (String strArg = str; strArg != NULL; strArg = va_ar... | You can't pass most class types to a variadic function - only POD types (5.2.2 para 7 in the standard); if you do the behaviour is undefined - which could cause the problems you're getting. I'm pretty sure the Arduino String class is not a POD, so this isn't going to work.
You might be better off using char arrays (at ... |
5,780,745 | 5,781,103 | Using Clang -fsyntax-only mode with static libraries? | I am using libclang library to build autocomplete feature. libclang automatically -fsyntax-only flag internally. libclang seems to require entire source code tree available in order to work (or .pch files). What I want is to just pass single source file and a precompiled library (.a or .so) containing all the code it ... | If you use -fsyntax-only you are asking clang to only examine the contents of the source file and the files which it includes. It doesn't even generate an object file, let alone require and libraries (static or shared).
You'll need at least the source file in question and all the header files that it includes (or a pre... |
5,780,747 | 5,785,926 | What is wrong with my attempts to mock a simple C++ method with googlemock? | As per Patterns for unit testing a C++ method that makes a standard library call, I'm test-driving development of a network-abstracting class. In order to unit test code that makes standard C library calls (which I can't mock) to handle BSD sockets, I've defined an interface ISocket from which both my real implementati... | I finally got it sorted. What was tripping me up is that I wanted to use a pointer, but googlemock works with classes. Here's what works:
#include "gmock/gmock.h"
#include "gtest/gtest.h"
// C standard library includes omitted
#include "MockSocket.h"
#include "Network.h"
using ::testing::Return;
namespace JrStream {
... |
5,780,796 | 5,818,643 | Natural sort order in C++ using StrCmpLogicalW function in this library shlwapi.dll | I try to learn how to use the StrCmpLogicalW function. There is a post in C# Natural Sort Order in C#. But I am looking for syntax in C++.
Thank you.
| I finally got it figured out. Here is the function. It is critical that you put the shlwapi.h and vcclr.h header files before any of your own header files if you have any. That was the issue I have been struggled with. Don't fully understand why it is. If anyone have an good explanation, welcome to make comment. Also, ... |
5,780,918 | 5,780,941 | Hiding a C++ class in a header without using the unnamed namespace | I am writing a C++ header in which I define a
class A {
// ...
};
that I would like to hide from the outside world (because it may change or even be removed in future versions of this header).
There is also a class B in the same header that has an object of class A as a member:
class B {
public:
// ...
private... | You could do an inner class:
class B
{
class A { /* ... */ };
A a_;
}
|
5,781,026 | 5,781,045 | Why am I disallowed from calling methods on an object I've returned by const reference? | This is a follow up question to my earlier question concerning returning references in C++: Best way to return an object in c++?
I can successfully return a reference, however, I am unable to prevent an observer to completely overwrite the variable in question. I have used const references, but I want an observer to b... | Mark all methods that should be callable on const objects as const:
class Layer
{
// ...
public:
void someMethod() const;
};
void Layer::someMethod() const
{
// ...
}
Note that you cannot mutate the object inside a const method, except for data members declared as mutable (which are quite rare; lazily i... |
5,781,132 | 5,781,146 | std has no member 'getline'? | I'm trying to use std::getline, but my compiler is telling me that getline isn't identified?
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <fstream>
#include <cstdlib>
int main(){
using namespace std;
string line;
ifstream ifile("test.in");
if(ifile.is_open()){
... | std::getline is defined in the string header.
#include <string>
Also, your code isn't using anything from cstring, cstdio, cmath, or cstdlib; why bother including these?
EDIT: To clarify the confusion regarding the cstring and string headers, cstring pulls the contents of the C runtime library's string.h into the std ... |
5,781,198 | 5,781,262 | Compiling OpenCV code on a 64-bit mac | I recently inherited some OpenCV code. I installed openCV on my mac, built in in XCode, and then compiled and successfully ran my first openCV "hello world"-ish program.
Now I'm trying to run the code I was given, but I get errors that lead me to believe it's an issue with the original code being run on a 32-bit Window... | Add opencv_imgprocto your LDFLAGS:
LDFLAGS = -I/usr/local/include/opencv -lm -lopencv_core -lopencv_highgui -lopencv_video -lopencv_imgproc
|
5,781,222 | 5,781,283 | Duplicate const qualifier allowed in C but not in C++? | Sample code snippet
const const const int x = 10;
int main()
{}
gets compiled in C but not in C++. Why does it get compiled in C? I thought this would fail in C as well. Never mind.
Which part of the C++ Standard forbids the use of duplicate const and which part of the C standard allows this?
| C99 §6.7.3/4:
If the same qualifier appears more than once in the same specifier-qualifier-list, either directly or via one or more typedef s, the behavior is the same as if it appeared only once.
Yes, that is valid C99, and your discovery is correct.
|
5,781,320 | 5,781,515 | Is it possible to give a top-level function access to an object's members in C++? | So I'm writing some wrapper classes for GUI programming in Win32. I'm starting with a Window class, and so far it contains a MainLoop method that is basically a clone of the standard Win32 WinMain function. That way, one can do something like this:
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, i... | You need to create window map and when you create new window just add it to this global map. You can use simple linked list instead of course.
map<HWND, Window *> wndmap;
LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wparam, LPARAM lparam)
{
Window *pWnd = wndmap [hwnd];
....
}
|
5,781,356 | 5,781,484 | Disabling C++ code without macros | I hate macros. I'm trying to avoid using them as much as I can, but I occasionally need them to enable / disable features in my code. Typically:
#ifdef THREAD_SAFE
typedef boost::mutex Mutex;
typedef boost::mutex::scoped_lock ScopedLock;
#else
typedef struct M { } Mutex;
typedef struct S { S(M m) { }... | Macros are the only good way to get information from the build system into the program. The other alternative is writing your own code-generation scripts, or tools like SWIG.
The problem I see here is the unnecessary use of typedef. I think this is better because it limits the introduction of new symbols (single-letter... |
5,781,591 | 5,781,964 | Class template function signature syntax | I have a class defined like this:
template< class TBoundingBox >
class BoundingBoxPlaneCalculator
{
typedef PlaneSpatialObject< TBoundingBox::PointDimension > PlaneSpatialObjectType;
typedef typename PlaneSpatialObjectType::Pointer PlaneSpatialObjectPointer;
std::vector<PlaneSpatialObjectPointer> GetPlanes()... | It looks like I just had to add typename in the calling function:
std::vector<typename PlaneCalculatorType::PlaneSpatialObjectPointer> planes = planeCalculator->GetPlanes();
I'm confused why it worked without it when the function was defined inside the class??
|
5,781,597 | 5,781,667 | Incomplete type is not allowed: stringstream | Why does this line give the error Error: incomplete type is not allowed?
stringstream ss;
| #include <sstream> and use the fully qualified name i.e. std::stringstream ss;
|
5,781,644 | 5,781,805 | Rails WebService and C++ application to expose | (Sorry for my english)
First: I have an application created using C++ (this is for performance needs), this application uses an image to make some processing and returns a simple answer (1 or 0 ).
Now I need to expose this application from a webservice.
I think to create a webservice using Rails, but I don't know if it... | I have never done that before, but I think you should take a look at Thrift which was initially developed by Facebook and allows you to make multiple languages work together via RPC calls.
Thrift allows you to define data types
and service interfaces in a simple
definition file. Taking that file as
input, the co... |
5,781,823 | 5,781,906 | Singly linked list C++ ostream and istream -- outputs memory addresses | Im really new to this and am now learning singly linked lists. I am writing some code but I am really confused. I am trying to write a read method and a write method. I have a test harness I cant change though. I just want to be able to read to the stream and output the stream so it doesnt come back with the memory add... | Your write method seems a bit messed up.
You want to write the elements, not create new ones. Something like this should work better:
void SLLIntStorage::Write(ostream& w)
{
Node *node = head;
for(int i = 0; i < NumberOfInts; i++)
{
w << node->data << endl;
node = node->next;
//cout... |
5,781,911 | 5,840,197 | C++ apt-get working on stdout of popen | This might sound like a stupid question, I am new to C++.
On debian I try to invoke apt-get install with popen. I need to parse the output of this programm. Unfortunately I am not able to read the full output of apt-get.
At some point apt-get might ask for user input (asking if dependencies should be installed). My p... | The problem was not actually input buffering but output buffering of cout. Manual flushes solved the problem:
while (fread(buffer, 1, 1, fp) != EOF) {
cout << buffer << flush;
}
|
5,781,976 | 5,782,086 | Is it possible to build an enterprise application with C/C++? | So, I heard that facebook used C for their underlying business logic, with PHP as the front end. Now I'm learning C++, and my assignment in 2 weeks is to develop a crossword puzzle game for people to play. I finish the program to produce a crossword puzzle with possibility of highest combination between words. The inpu... | As we are sharing ideas:
Let's not forget about Google's Native Client project which -frankly- rocks. It will allow you to run any about any native code in the browser, by compiling it into verifiable object format (much like say verifyable managed code that is the basis for Silverlight, but not tied to any VM).
Video ... |
5,782,047 | 5,818,597 | linking shlwapi.h for to StrCmpLogicalW function | Any idea how to port this code from C# to C++?
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);
If I tried this line in my header file in C++, the compiler generated a bunch of error.
#include <Shlwapi.h>
| I finally got it figured out. Here is the function. It is critical that you put the shlwapi.h and vcclr.h header files before any of your own header files if you have any. That was the issue I have been struggled with. Don't fully understand why it is. If anyone have an good explanation, welcome to make comment. ... |
5,782,150 | 5,783,670 | OpenGL texturing Triangles | I have a varray full of triangles that make a large square. I'm trying to texture this large square and all i'm getting (it seems) is a one pixel column that is then stretched across the primitive.
I'm texturing each right angled triangle with UV coords (0,1), (0,0), (1,0) and (0,1), (1,1), (1,0) depending on which way... | Looks like you're associating the UV data with the indices, not with the vertices. UV data is part of the vertex data, so you should probably pack it in the VertexData object, rather than keeping it separate. You can keep it separate, but you need one per vertex, not one per index.
|
5,782,225 | 5,782,510 | efficiently passing and returning objects in c++ | I have a Visual Studio 2008 C++ application where a function Foo::CreateBar uses an internal function to populate a buffer with some data as below. I understand that VS2008 will use return value optimization (RVO) to ensure the Foo::GetData() call will not incur a copy, but will I incur copies for the Bar constructor? ... | You should make a couple of different tests and see what your compiler does with it. In the code above there are as many as 4 copies of the buffer:
Inside GetData
Return value of GetData
Argument of constructor
Member
The compiler by doing RVO/NRVO can merge 1 and 2 into a single object. Moreover it can merge those... |
5,782,413 | 5,782,606 | C++ popen not getting all of stdout | Basically I want to read all data from stdout when running a program with popen. However, the program I run will not return the last output line into my buffer and I do not understand why (my understanding: I would get any output sent to stdout {unbuffered?} from popen).
// $Id: popen.cpp 126 2011-04-25 18:48:02Z wus $... | The problem isn't that you aren't reading the last line, the problem is that you aren't displaying it due to cout being line buffered.
cout << buffer << flush;
should work.
|
5,782,457 | 5,782,588 | background colour of popup info box in eclipse | I am using eclipse CDT on xubuntu. It works perfectly. The only problem is that the background colour of the pop up box that appears when you put the mouse over a variable for instance will have a background colour of black.
Sometimes some of the text in this box will be black as well. I then have to select all text i... | Go to Window > Preferences and then open C/C++ > Editor and play with Source hover background. Don't forget to uncheck the System Default box to be able to change the colour.
|
5,782,548 | 5,782,594 | C++ double iterator loop for collision detection | First things first, I'm very new to C++! So I've got a standard list of objects representing elements in 2d space, and I want to do some basic collision detection. My first idea (coming from a mostly Java background...) is to compare each object with each other object, calling an function to check for intersection on e... | EDIT: Responding to multiple comments.
for (list<Box>::iterator p = mBoxes.begin(); p != mBoxes.end(); ++p) {
for (list<Box>::iterator q = p); q != mBoxes.end(); ++q) {
if (p==q) continue;
if (p->isIntersecting(*q)) {
p->changeDirection();
q->changeDirection();
}
... |
5,782,780 | 5,782,874 | ADO _ConnectionPtr parameters | I'm trying to connect to my SQL server from a c++ console app. and
this line of code drives me insane:
pConnection->Open("Server=PETERPAN\SQLEXPRESS;Database=WAWI;User ID=Test; Password=Test;Trusted_Connection=False;","Test","Test",-1);
According to VS I'm supposed to provide the follwing information : (connections... | Yes, you can pass empty strings as the 2nd and 3rd parameters if you provide this information in the connection string.
pConnection->Open("Server=PETERPAN\SQLEXPRESS;Database=WAWI;User ID=Test; Password=Test;Trusted_Connection=False;","","",-1);
Here is a how to tutorial on ado with c++.
|
5,782,785 | 5,782,802 | Program crashes while using struct tm unless time_t declared first | I am trying to prevent recreating the wheel. I am parsing an input file that has time as one of the values. I need a data structure to hold all of the values of the input file, and instead of creating a custom structure for the time field I want to just use struct tm from ctime.
I'm running into a strange error tho... | You need to allocate the structure either on the stack or on the heap with malloc. Specifically, you're declaring a pointer to the struct without allocating any storage for it.
Try this:
#include <ctime>
#include <cstdio>
int main()
{
int Oldhour = 16;
int OldSecond = 25;
int OldMinute = 20;
time_t seconds;
stru... |
5,782,786 | 5,782,878 | Help with a BST insert function | Hey so I am attempting to write a BST but I am having a lot of errors and I am pretty overwhelmed and lost on what to do. Can you guys take a look and point out anything that is off. The teacher wasn't very useful at all at explaining anything.
header in the .h file
class Tree
{
public:
bool insert(int k, string s... | It appears that you have a lot of untested code. You will have to get the features working one at a time.
Furthermore, I see at least one instance of duplicated effort already. The preOrder and postOrder methods should be slight variations of the same algorithm, yet one is loop-based and the other works by function rec... |
5,782,837 | 5,783,358 | Read on-screen text from external app. API Hooking? | I have a Java background so have limited knowledge when it comes to C# and C++. Basically I am trying to "read" text from another application which is displayed on screen...
To be specific, I want to read the dealer chat message from Pokerstars... on the fly...
What is the best way to read this text into a Java progra... | One way to do it, which works as long as text is not anti-aliased, like in your image:
From your application, take a screenshot of the other application's window. Search the screenshot for all non-white pixels. Make a list of all the non-white pixels. For each pair of non-white pixels in the list, if the pair touches e... |
5,783,139 | 5,783,309 | Programatically capture prints from child process at parent so they don't go to stdout | I do have a C++ program that runs on HPUX and Linux. My program creates 2 child process, parent waits for both child process to finish. When I execute my program form run directory as follows,
run> myProgram
I get prints from both child process + parent process displayed. So I need to way to stop my child process to pr... | Taking inspiration from this answer:
#include <stdio.h>
main()
{
int fd;
fpos_t pos;
printf("printing to stdout enabled\n");
fflush(stdout);
fgetpos(stdout, &pos);
fd = dup(fileno(stdout));
// Standard output redirected to the null device
freopen("/dev/null", "w", stdout);
f(... |
5,783,214 | 5,783,275 | C++ clarification of "return" | Homework, just advise please
Apparently my idea of what returning something in a method does is wrong. I'm trying to write methods for getting derivatives of numbers and operations. So far I just wanted to get the derivative of a non-negative number that isn't accompanied with an "x" (result should be zero no matter ... | I have to say that I don't understand what it is that you're trying to do.
Nevertheless, to achieve your goal of modifying tempInt inside getDerivatives(), you can either do:
tempInt = noXDerivative(tempInt, tempX);
Or, you can modify the noXDerivative() function to take its argument by reference, rather than by value... |
5,783,518 | 5,783,590 | C/C++ PLSA libraries | I need a library that implements PLSA algorithm.
Possibly I'm looking for a C/C++ implementation, but other language will be good anyway.
Can someone help me?
| I have not used the algorithm, but googling for it let me to this implementation in python and this one in Matlab.
|
5,783,582 | 5,783,583 | cin gets a number and convert it. How to not close console after hitting enter? | I've started learning C++. Here's my simple problem. I have a code:
int main() {
int number;
cout << "Input number: ";
cin >> number;
cout << "here is hex = 0x"
<< hex << number << endl;
}
I'm using Visual C++. I think the point of this program is easy, user enters some number and program converts it t... | Try to include cstdlib and add system("PAUSE"); to your main:
#include <cstdlib>
int main()
{
int number;
cout << "Input number: ";
cin >> number;
cout << "here is hex = 0x"
<< hex << number << endl;
system("PAUSE");
return 0;
}
That's it, happy programming ;-)
Instead of pausing you could also us... |
5,783,691 | 5,783,906 | reading in strings and doubles | I'm having an issue reading in a string from a file and then a double from a file afterwards. My professor advised me to put a special getline after each input line, but it hasn't worked and I've deduced that this is the issue with the program. Is there a simpler way to take in doubles?
example of the input file is:
... | EDIT: Updated in response to OP's clarification.
Based on the sample you provided, this should work:
while(1) {
std::string s1;
if(!std::getline(infile, s1))
break;
std::string s2;
if(!std::getline(infile, s2))
break;
double d1, d2;
if(!(infile >> d1 >> d2))
break;
ac... |
5,784,847 | 5,784,855 | C++ escape character difference in osx and windows? | I'm playing around with C++ in xcode and well i'm having an issue with
char array[] = "Apple";
Technically a null escape '\0' is automatically added. I'm just writing a basic function to add the number of letters in the c-string but i go into a forever loop because it can't find the '\0'. Why is that? I'm using g++.... | You forgot to dereference.
while ( *temp != '\0' )
|
5,784,914 | 5,785,799 | Does glGenTexture only work in the main? | I have loaded textures into openGL before, worked fine. But this time I wanted to load a texture within a constructor of my rendering class. (im using MVC with abstract base classes as interfaces). I was originally trying to load a png file rather than a bmp as I did before so i assumed it was something to do with that... | When is the constructor being called? You need a valid OpenGL context to make any GL call. A usual error is to create objects at the global scope, and that means the object is constructed at program start, before main() is called, and at that point there is no OpenGL context created yet.
|
5,784,969 | 5,784,995 | When did C++ compilers start considering more than two hex digits in string literal character escapes? | I've got a (generated) literal string in C++ that may contain characters that need to be escaped using the \x notation. For example:
char foo[] = "\xABEcho";
However, g++ (version 4.1.2 if it matters) throws an error:
test.cpp:1: error: hex escape sequence out of range
The compiler appears to be considering the Ec ch... | GCC is only following the standard. #877: "Each [...] hexadecimal escape sequence is the longest sequence of characters that can constitute the escape sequence."
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.