mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

So, there is only a very trivial difference between a struct and a class . And struct was kept for backward compatibility with C, while class was introduced because it is generally more appropriate for Object-Oriented Programming purely on the basis of vocabulary (i.e. in OOP with about "classes" of objects) and on the grounds of default access rights and inheritance (private) which is more in-line with OOP design philosophy. But, in practical terms, the difference between struct and class remains trivial.

What you call "structures" is what experienced programmers colloquially refer to as "POD-types" (Plain-Old-Data types). These are basically simple little bundle of data like:

struct Vector2d {
  double x;
  double y;
};

By convention, in C++, people use the keyword struct when creating such simple classes, and thus, people sometimes call them "structures", but I tend to dislike this awkward, overly general wording.

So, the purpose of POD-types is similar to that of any other class, except that, in this case, you don't have any functionality to associate directly to the class (or very little functionality). In other words, when you just want to bundle a bunch of data elements together, not much more. POD-types are a special kind of "value-objects" (or value-classes).


>>How do they help with coding?

Well POD-types help with coding just because data structures are omni-present in programming tasks and very often all you need is to group a number of variables together as one logical entity, …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The problem stems from the fact that you use a very bad integration method for you acceleration.

Here are some basics about motion:

If p is the position of an object, and that object is travelling at a constant speed v, then, at time t, the object will be at position:
[TEX]$p(t)\, =\, v\, t\, +\, p(t_0)$[/TEX].
This is an exact formula (not an approximation). And thus, how you are computing the constant-speed case is correct, with [TEX]$dp\,=\, v\, dt$[/TEX].

If the object is travelling at constant acceleration a (e.g. gravity), then, at time i, the object will have a speed v which is given by:
[TEX]$v(t)\, =\, a\, t\, +\, v(t_0)$[/TEX]
This is also an exact formula, and thus, it is correct to compute the speed with [TEX]$dv\,=\, a\, dt$[/TEX] as you do.

However, if the object is travelling at constant acceleration, its position is given by this exact formula:
[TEX]$p(t)\, =\,\frac{1}{2}\, a\, t^2\, +\, v(t_0)\, t\, +\, p(t_0)$[/TEX]
And so, you should compute your increment in position using the formula:
[TEX]$p(t_{k+1})\, =\,\frac{1}{2}\, a\, dt^2\, +\, v(t_k)\, dt\, +\, p(t_k)$[/TEX]
and:
[TEX]$v(t_{k+1})\, =\,a\, dt\, +\, v(t_k)$[/TEX]


It might seem to you that such a small change in the formula shouldn't make such a big difference, but it does. The formula you were using is very inaccurate, and its accuracy is largely affected by the sampling rate (or frame-rate). What you saw happening is …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You specified your global variable with the keyword "static" which means that the global variable is local to the compilation unit it which it appears (a compilation unit is one compiled .cpp file). This means that the "global" variable Result that appears in "DisplayResult.cpp" is not the same as the global variable Result that appears in "Static.cpp".

To fix that problem, you would need to make the following code:

// GlobalVariables.h
#pragma once

namespace ProjectVariables
{
	extern int Result;
}
// GlobalVariables.cpp
#include "GlobalVariables.h"

namespace ProjectVariables
{
	int Result = 0;
}

(and add that cpp file to the project).


As per singletons, you are right that singletons are not recommended in general, but that's only because singletons are a form of global variables (albeit safer to use than global variables), and global variables are not recommended in general either. Singletons are better than global variables for sure, but neither are recommended.


>>which is he best way to declare and use global variables/function to share information between few forms, threads etc. The variables can be made up of classes, strucs, string^, int^ etc..

There are various "solutions" to this, most of the good ones involve redesigning your application with a better philosophy to begin with, and amongst the worse ones that are used with redesign fails or is not an option usually fall under two categories, "singletons" and "fly-weights". The former you already know about, that is, a singleton is …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>I know that by default member functions of a class are inlined

If member functions are defined within the class declaration, then yes, it is implicitly assumed to have been declared with the inline keyword. Whether it will be inlined by the compiler is another question that only compiler-vendors can answer.

>>And I also know that it's not allowed to declare functions in headers unless they are inlined.

It is certainly allowed to _define_ the member functions in the headers, but it can generally cause linkage problems when that header is included within different compilation units (e.g. compiled cpp files), because the linker will find multiple definitions of the function in question. In order to solve that problem, you have to change the default linking mechanism of the function, that is, with the inline or static keyword (I always have to repeat to people that the main effect of inline is on the linkage mechanism not on whether or not a function gets inlined by the compiler).

>>Is there a way to declare a function in a header's class that is not inlined?

Yes. If you want the function to be defined in the header file, you can specify it with the static keyword giving it static-linkage. This means that the function definition will not be published on the symbol tables that are used by the linker, effectively making it invisible to any code outside the current compilation unit (i.e. formally "static-linkage" means that its …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster
#include <iostream>

int main() {
  for(int i = 0; i < 3; ++i)
    std::cout << "Ho! ";
  return 0;
};
Clinton Portis commented: lol +10
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You can check explore things on gamedev.net, like the game programming wiki and NeHe's opengl tutorials. For more scientific graphics, you can check out VTK. For more simple graphics, you can check out SDL. And for GUI, you can check out Qt.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Here are some good suggestions of algorithms to implement for practice that are a bit more substantive than those suggested already, grouped by topics of scientific computing, most of which are fundamental algorithms that are very relevant in practice too. I also noted rough line-of-code counts (assuming you don't implement each algorithm from scratch) and difficulty level, these estimates are based on my own experience implementing them in C++ (your mileage might differ).

Simple numerical methods (assuming some basic calculus knowledge):
- Golden-section search algorithm (easy, ~10-15 LOCs)
- Secant root-finding methods (Illinois, Ford, or Brent's methods) (easy, ~30 LOCs)
- Runge-Kutta numerical integration (easy, ~25 LOCs)
- Runge-Kutta-Fehlberg numerical integration (bit harder than RK, ~50 LOCs)

Simple matrix decompositions (assuming some knowledge of linear algebra):
- PLU decomposition (easy, ~15 LOCs)
- Cholesky decomposition (easy, ~15 LOCs)
- QR decomposition (medium, ~50 LOCs)
- QR Algorithm (hard, ~200 LOCs)

Optimization algorithms (assuming some knowledge of vector calculus):
- Nelder-Mead's Simplex method (medium, ~150 LOCs)
- Simplex method (medium, ~250-500 LOCs)
- Mehrotra's method for Quadratic programming (hard, ~300 LOCs)
- Gauss-Newton method (easy, ~100 LOCs)
- Quasi-Newton BFGS method (medium, ~300 LOCs)

Multi-body dynamics (assuming some knowledge of mechanics and dynamics):

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

1) If you are not going to put anything in DllMain than you might as well remove it.

2) It seems you have made your DLL compatible with C, or at least, tried. If you really want compatibility with C, you cannot use references. If you will always compile the DLL with a C++ compiler, then it is OK to use references. However, if you want to make the DLL compilable with a C compiler, you need to use a pointer instead. Then, for using the DLL, the header file will have to be changed if you want it to be usable by C code, as so for example:

#ifndef DONT_FORGET_YOUR_HEADER_GUARDS_H
#define DONT_FORGET_YOUR_HEADER_GUARDS_H

#include <windows.h>
#ifdef BUILD_DLL
    #define DLL_EXPORT __declspec(dllexport)
#else
    #define DLL_EXPORT __declspec(dllimport)
#endif

struct myIntStruct
{
int val;
int mul;
};

#ifdef __cplusplus
extern "C"
{
void DLL_EXPORT ConstructMyInt(myIntStruct &);
void DLL_EXPORT DoSomething(myIntStruct &);
}
#include "myInt.h"
#else 
// This makes this DLL usable from C code.
void DLL_EXPORT ConstructMyInt(myIntStruct *);
void DLL_EXPORT DoSomething(myIntStruct *);
#endif

#endif

3) Generally, for wider compatibility it is often good to use the stdcall convention which you can lump into the DLLEXPORT symbol as so:

#ifdef BUILD_DLL
    #define DLL_EXPORT __declspec(dllexport) __stdcall
#else
    #define DLL_EXPORT __declspec(dllimport) __stdcall
#endif

4) Of course, if you don't actually want compatibility with any other language besides C++, then forget about points 2-3, except that you should still use extern "C" if you plan to make the DLL usable by a wider set of compilers …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>By the way, I'm using dark gdk which has some simple collision detection tools by itself. though when i use the code to detect collision for objects, the program just skips over it without doing any thing. it doesn't even any errors.

I suggest you review the documentation on dark gdk because either you are not using the collision checker correctly, or it is not a working feature of the library.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It all depends on what kind of image processing tasks you need to do. The best place to start is probably OpenCV. I'm sure it's possible to at least try to get it working on a DSP (with uCLinux for example). Otherwise, you can at least have access to the source of the algorithms you need and copy them into your DSP code. I recommend you try to get a micro-linux distro running on your DSP that's going to be the easiest when trying to port or use any 3rd party library.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>I guess I just thought that using c-strings would be faster since I don't need all the functionality of an std::string. I guess I was wrong. Thanks!

In C++, the default choice should always be std::string , it will always be easier than C-style strings and usually faster in execution time too (or the same, depending on your skill at writing the C-style version of the code). C-style strings only appear in special circumstances (like interfacing with a C library). Then there are more advanced applications where std::string isn't sufficient and where more feature-rich tools are required (anything from std::stringstream , to boost::tokenizer , to boost::spirit ). But, the default is always std::string , because if you don't need all its features, the compiler won't make you pay a performance penalty (or additional code) for the features you don't use, so don't be afraid to use it even in the simplest use-cases.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The code that you posted should cause an access violation at line 5. That code is erroneous, either find the errata of the book you have or skip this exercise.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>> newNode->next = intNode->next After that statement, the following would evaluate to true: newNode == newNode->next . That's as far as it goes. And it would certainly require special attention down the line to avoid problems when trying to delete the linked list (and traversing it in general).

>> intNode->next->prev = newNode After this line, the following would evaluate to true: newNode->prev == newNode , because intNode->next == newNode and thus, intNode->next->prev = newNode <===> newNode->prev = newNode .

So, at the end of both statements, both the newNode->next and newNode->prev would pointing to newNode itself.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

std::set is a standard container that doesn't allow for duplicates. So, you can just do this:

#include <set>
#include <cstdlib>
#include <ctime>

int main() {
  srand((unsigned)time(0));
  std::set<int> numbers;
  while( numbers.size() < 4 )
    numbers.insert( rand() % 10 );
  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I smell a homework problem....

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It seems to me that this piece of code is suspicious, in the "highlight" function, towards the end, you have:

char *temp=new char[len(text)+108];
    sprintf(temp,"<table width=\"100%%\" border=\"0\" cellspacing=\"0\">\n<tr>\n<td>1.</td>\n<td bgcolor=\"#FFFFFF\">%s</span></td>\n</tr>\n</table>",text);

I counted 116 additional characters (considering the newlines to be one character, which is not the case on all OSes). You should be using strcat instead.

I highly, highly recommend that you use std::string instead of C-style strings. I mean, all the code you have would be a heck of a lot more robust, faster and simpler if you used std::string instead.

Usually when you have code that works fine in debug mode and crashes or misbehaves in normal or release mode, it usually means that you have a memory corruption problem. Usually, debug-runs have additional code that fills any uninitialized memory with dummy values (like 0 or some hex pattern like 0xBAADF00D ). So, if your code happens to work fine in debug mode it is usually due to accessing memory that is either uninitialized or unused or used by something else and happens to have been zeroed, when in release mode that is no longer the case and your program crashes. In other words, the main thing that changes between debug and release execution modes is the resulting memory pattern and "empty" values, which should not have any effect on your code as long as you are not accessing memory that you shouldn't access and that you are not using uninitialized memory. In your case, and by …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You should just run your program in Valgrind and see the report afterwards about if there are any memory leaks. Or, use any other memory debugging tool.

Basically, memory leaks are a consequence of heap-allocated memory (or freestore in general) that is not freed (and is then forgotten, made unreachable), put simply, not all new-calls are matched with a delete-call. Other forms of memory cannot cause leaks (e.g. the stack or global variables) simply because the compiler generates automatic code to free stack memory, and the OS does the rest.

Surely, not using the heap at all is pretty much guaranteed not to allow for memory leaks. But that is a high price to pay. All you need to do to avoid memory leaks is a little discipline at doing two things: create RAII classes, and use smart-pointers. My tutorials might be of interest in that regard (RAII and Ownership).

Btw, memory leaks aren't the only thing to worry about if you want your program to be able to run forever. You also need to make sure that your stack is not growing indefinitely. In other words, you cannot base your main loops on recursion.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Did you put the glut.h in the "GL" sub-folder of the "include" folder?

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

In a similar fashion as gusano79 has suggested, you can use a templated wrapper to reduce the amount of coding necessary for the different wrappers.

Here is what I mean:

class Airplane {
  public:
    virtual void fly() = 0;
    virtual void speed_up() = 0;
};

template <typename AirplaneType, 
          void (AirplaneType::*FlyFunction)(),
          void (AirplaneType::*SpeedUpFunction)()>
class AirplaneWrapper : public Airplane {
  public:
    virtual void fly() {
      plane.*FlyFunction();
    };
    virtual void speed_up() {
      plane.*SpeedUpFunction();
    };
  private:
    AirplaneType plane;
};


typedef AirplaneWrapper<AirplaneA,&AirplaneA::fly_A,&AirplaneA::speed_up_A> IAirplaneA;

typedef AirplaneWrapper<AirplaneB,&AirplaneB::fly_B,&AirplaneB::speed_up_B> IAirplaneB;

//... you can even generate this with a MACRO if feasible.
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You should remove the Shape:: in front of each function name within the declaration of the Circle or Triangle classes, you don't need that and should have it there (and that's the error your compiler reports).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>> Would the last line work?

No.

>> Or do I have to declare a vareable to do any math/calculations?

Yes, you can do computations to obtain the initialization value of a global variable, but you cannot do general statements.

>> Does it execute in a top down fashion?

Yes, but not really, at least, you shouldn't depend on it, it could be a subtle way to crash your program. Read this.

>> Or would I have to declare a function to execute that last line?

Yes and no. If you do as Narue suggested, then you don't need a function to execute that code at the initialization of sasd. However, any other more general set of statements (e.g. an algorithm of some kind) would require a function. But note that this function can be called in order to initialize one of the global variables, for example, you can do:

int var = 6;
int exponent = 4;

inline
int compute_var_exponent() {
  int result = 1;
  for(int i = 0; i < exponent; ++i)
    result *= var;
  return result;
};

int var_pow = compute_var_exponent();

On a final note, global variables are not recommended for anything beyond a simple test program, and experts generally only make use of them in very specific cases (often implemented as a Singleton). One of the reason they are generally undesirable is that they introduce a global state to the program which is hard to predict …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Where do you actually drawn the background? All I see in your rendering code is the drawing of the face components (which are lines). Where do you draw a large rectangle with the texture object binded and mapped to it?

For example, you should have something like this in your render code (just after the glRotatef call):

glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
     glBindTexture(GL_TEXTURE_2D, texture[0]);

     glBegin(GL_QUADS);
       glVertex3f(0,0,0.99);                 glTexCoord2f(0,0);
       glVertex3f(winWidth,0,0.99);          glTexCoord2f(1.0,0);
       glVertex3f(winWidth,winHeight,0.99);  glTexCoord2f(1.0,1.0);
       glVertex3f(0,winHeight,0.99);         glTexCoord2f(0,1.0);
     glEnd(GL_QUADS);
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Quick answer: remove the template <class T> on lines 59 and 67.

Long answer: The problem here is that you are defining, in the general class template, two function template (operators << and >>). Then, in the specialization, you define a friend function. For a moment, forget the whole business about them being friend functions and that they are defined in the class declaration. The situation basically boils down to this:

//first, you have a function template coming from your general class template:
template <class T>
std::ostream& operator >>(std::ostream& out, MyData<T>& obj) {
  //..
};

//then, you have this normal function coming from your specialized class template:
std::ostream& operator >>(std::ostream& out, MyData<std::string>& obj) {
  //..
};

The problem with the above is basically that your compiler decides that the second function looks too much like a specialization or an implementation of the first function template, and thus, tells you "Error function template has already been defined". This is somewhat compiler-specific, GCC accepts your code (at least my version of it), I would suspect some compilers don't (working out correctly the rules related to function templates and function overloads, especially if friendship is involved, has been notoriously difficult for some compilers).

In any case, it doesn't really matter since your code is somewhat wrong whether the compiler accepts it or not. The thing is, your general template doesn't need to declare a templated friend function, you only need an ordinary friend function. And thus, if you follow my …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, of course, AD and firstPerson's answers clearly doesn't do what you want.

vijayan121's answer is probably as much as you'll be able to do, that is, make the return type into whatever type that is common to both operand types. Which, again, isn't exactly what you want. And, in fact, it boils down to being equivalent to the std::max function because that too will deduce the single type "T" to be the common type that both operands can be promoted to. So, don't be fooled, vijayan121's solution is just a mirage (except for the slight benefit that only the result is converted to the destination type).

The fact is, you cannot make the result type depend on which value will be chosen at run-time. This is why C++ is called a "statically typed" language, types cannot change at run-time. So, there is no nice way to achieve what you want.

However, there is a reasonable way to do what you want, and it is using Boost.Variant, as so:

#include <utility>
#include <iostream>
#include <type_traits>
#include <typeinfo>

#include <boost/variant.hpp>

template <typename A, typename B> 
inline
boost::variant<A,B> max_of( const A& a, const B& b)
{ 
  std::cout << typeid(A).name() << " " << typeid(B).name() << std::endl;
  if(a < b)
    return b;
  else
    return a; 
};  //Notice here that I have not used the ( ? : ) operator because its return type
    // is fixed at compile-time, so, a regular if-statement has to be used.

int main() { …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Try:

$ sudo apt-get install libqt4-dev

You might just not have the development files for Qt (I thought they were installed along with Qt Creator, but maybe not).

Basically, you can also go into your Synaptic application (in system menus somewhere), and search for libqt and install pretty much all that seems relevant, especially those marked with "-dev".

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Hi woody363,

To install Qt, you can simply install qt-creator (the main IDE for Qt). Here are the detailed instruction to install that:

1) Go to a terminal window.
2) Type this (the dollar sign not included):

$ sudo apt-get install qtcreator qtcreator-doc

3) Enjoy (the Qt Creator should appear in your applications menus, follow online tutorials on how to create Qt applications with Qt Creator).

PS: Notice how simple the instructions are, that's probably why few people would have given them to you, they are so trivial (like anything else in linux).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You weirdly seem to be comparing apples and oranges.

If you need to do serialization (or marschalling), then Boost.Serialization is a great tool (not necessarily the most appropriate at all times, but a very good one). And, of course, one of the main, universal, file-format used by boost-serialization is XML, but I doubt that you can easily use it to load XML data that wasn't originally generated by the Boost.Serialization library in the first place (i.e. it is not a generic parser of XML).

If you need to do parsing, then Boost.Spirit is quite an awesome library for that (and the DSEL is wonderful). Btw, parsing XML (or at least, a basic form of it) is the main tutorial on the official site of Boost.Spirit.

If you need to manipulate files and directories, then Boost.File-System is a great tool.

These three tasks are completely different and orthogonal to each other. The choice depends on the task at hand, period.

As for boost filesystem3, I am not familiar with it too much (I never needed to do much file system operations in C++, at least, recently).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Boost.Spirit should be used. Boost.Spirit is the library that allows you to create a grammar and do parsing / generation of XML data.

The purpose of Boost.Serialization is very different, it is true that it can interact with XML to do the serialiation / unserialization, but it isn't a parsing library, rather a library that uses some XML generation / parsing. I don't know if it uses Boost.Spirit for generating / parsing its XML data.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>> Do you agree this would work?

It would certainly help. It wouldn't completely solve the problem, RAM is also variable in access time, but certainly not as much as the HD.

Anyways, what is wrong with variability? What is wrong with taking statistics on the performance of your algorithm? You run it multiple times and take the average running time as the performance value you are looking for. What's wrong with that?

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>The compiler plainly doesn't allow this.

Basically, the restriction that is imposed on the default arguments (for function parameters) is that they cannot be derived from or referring to the other function parameters. And because the "this" pointer is a hidden first argument to any class member function, any non-static data member cannot be used as a default argument since it is contingent on the first "hidden" parameter of the function.

I don't know exactly why it was not allowed to create default arguments from the other function parameters (personally, I don't see any technical reason why this wouldn't be possible, but maybe there is one).

The work around is to use overloading (which is what default arguments do in effect, they result in different (implicit) overloads with fewer arguments). As in:

class testdf
{// testdf
private:
  const int _defaultVal;

public:
  testdf() : _defaultVal(1) {}
  int testMF(int arg) { return arg; }
  int testMF() { return testMF(_defaultVal); }

  ~testdf();
}; // testdf
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>> The above code (on the GCC compiler) creates the problem where TestB doesn't actually call TestB's constructor,

I does call the TestB constructor, just not the one you defined but the default, compiler-generated copy-constructor.

If you don't provide a constructor of the form TestB(const TextB&) , the compiler will generate a default one (a copy-constructor) and that default version of it will call the copy-constructor of the base-class (either default or user-defined), this is why your TestA(const TestA&) constructor gets called.

>> I say stupid because if TestA's was intended it could be called from within TestB's constructor

One TestA constructor or another will always be called by the derived class constructor (whether you specify it or not) because C++ doesn't allow objects to be only partly constructed.

>> and completely bypasses TestB's constructor in the process

It doesn't, it uses the compiler-generated default version of the copy-constructor, simply because if you don't provide a copy-constructor (or disable it), the compiler will generate one for you. The constructor of TestB is not by-passed, it never will be in C++, that's a guarantee that C++ standard (and any decent compiler) gives you.

>> given constructors can't be made virtual,

Obviously. By definition, when you construct an object, you know its final type, and the concept of virtual dispatching is meaningless.

>> defining either or both of the constructors as explicit is redundant (as it's called explicitly)

Explicit is only meaningful …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you use the clock() function, it will return the clock ticks elapsed by your process only. My guess is that you have been using a general local-time function like "time()" to measure your elapsed times. The time() function and the clock() function are fundamentally different in the sense that clock() return the number of clock-ticks since the start of the calling process and only the clock-ticks consumed by the calling process are counted. In other words, if you use the clock function, there should be no variability introduced by having other processes running on the computer.

N.B. When measuring performance of algorithms that do file I/O, always expect variability just from the fact that file I/O is usually the main bottleneck operation and it is not very steady.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Calm down people. Don't antagonize yourselves over such a trivial issue.

@vijayan121: I think all WaltP is saying is that a technically correct answer isn't always the best answer to a question. That doesn't warrant any attacks on his technical knowledge.

@WaltP: You assume that there is no reason whatsoever to want to have time represented as the number of seconds since the unix-epoch, as opposed to just having some representation of time (translatable to calender time). I think that assumption is wrong. I can easily think of a few reasons (some better some not so good) for wanting or needing that.


At this point, I think it's the OP's turn to give his input on what he needs posix-time for (if he stills needs that) and if any of the suggested solutions solve his problem (if not, why?).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>> What are ostream & istream and what do they do?

ostream stands for output stream, and istream stands for input stream. They are base classes that define the interface for any input/output stream. All the stream objects in the C++ standard library derive from one of these base classes or both. The reason they are used in this context (operator overloading) is because it allows the input/output operators (<< and >>) to be used for any actual type of stream object (this is called substitutability, an essential concept in polymorphism). This way, the same operator overload can be used for any type of streams (file streams, console streams (like cin / cout / cerr) and string streams). I suggest you read and explore this reference site, and this tutorial.

>> Why output or input Been used. what do they do here?

These are just the names that was chosen for the parameters to the operator overload.

>> why not use cout??

Because the output operator overload should work for any other output stream, not just cout.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Keep the image a the 256x256 dimension, and make sure that is the dimension you get when your program loads it. Otherwise, it means your loading method is corrupt.

BTW, if you think that this line:

fread(data, width * height * 4, 1, file);

correctly reads the pixels of the image in the file, you are greatly mistaken. An image file is not just a dump of pixel values, it contains a header (information at the beginning of the file) with information about the format of the pixels, the size of the image, compression method, palettes, etc.. Just reading in the raw bytes into an array of unsigned char is very wrong. This is not to mention that you load the image with a pixel-width of 4 bytes and then you send it to OpenGL with a pixel-width of 3 bytes (RGB, not RGBA). Get your image-loading code straight. For example, you should maybe use an image-loading library like FreeImage or SOIL, don't rely or try to load the image with your own hand-crafted code, and make sure that the image loading works before you move on to trying to apply it to an OpenGL object (I didn't mention this earlier because I assumed that you had done due diligence on making sure the image got loaded correctly, but now I see that you didn't).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

To add to vijayan121's great explanation.

Although nice, the <chrono> header doesn't solve the problem of the epoch of reference, it is still implementation-defined, which is a good thing in general, but a problem, of course, if you want some type of absolute reference.

The Boost.Date-Time library is a good place to go for pretty feature-rich facilities to manipulate time, and it does include all the necessary conversions. For instance, you can use the posix-time for any system (the library handles the required epoch and duration conversion if any).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First of all, the loading of the texture and the registering of it to OpenGL only has to occur once. So, you should move the call to LoadGLTextures() to the init function. All that you need to do before you render the polygons on which the texture is applied is to call the glBindTexture() function with the correct parameters.

Second, I would guess that calling glBindTexture() at line 111 with the variable "texture" which is not initialized could possibly cause problems as well, if anything, you need to move that line at least beyond the LoadGLTextures() call if you decide to leave it there (which you shouldn't).

Line 109 and 110 can also be moved to the init function.

Line 119 is misplaced and useless. The purpose of push-pop matrix calls is to preserve the previous matrix (modelview or projection, or other) in order to be able to retrieve it later. Usually it is used for drawing an object (or mesh) by first pushing the current modelview matrix, then applying some local transformation (translation, rotation, scaling) to render the model, and finally popping the modelview matrix to come back to the previous one (the "global" frame transformation). So, having a single push call, before you actually set the matrix is pretty much useless, push and pop always should come in pair and they are useless before you actually gave a value to the matrix (e.g. with glLoadIdentity() for instance).

Then, I think you should enable Depth-test …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well. Maybe WaltP has 1 in 50 chance of finding the error, but I have an eagle eye and a compiler built into my brain, which means I have a 100% chance of finding the error. And the error is at this line in your loop:

sum1++=p;

You have one too many + signs. The above line translates into:

sum1++ = p;

Which means that the variable sum1 is incremented by 1 and then, its old value is returned as a temporary value (formally, an "rvalue") which you then attempt to assign a value too (the value of p). Because of the nature of an rvalue (a temporary value) there is no way that you can assign another value to it, i.e., you can only assign a value to a non-temporary variable (formally, an "lvalue"). And thus, you get a compilation error like "lvalue required on the left side of the assignment".

I believe you meant to write:

sum1 += p;
WaltP commented: Good for you. Although my mini-teaching-session is now for naught. There's actually a reason I posted as I did. +17
PrimePackster commented: Thanks Man, You saved my day +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

What you are describing is a build script, that is what you need. Personally, I am not familiar with Visual C++'s build system and the possibilities it offers to write build scripts. The main reason I'm not familiar with it is because it generally sucks and most large cross-platform projects use another build system which is independent of a particular IDE, compiler or OS.

I highly recommend that you take a look at Cmake. This build system will allow you to create very fancy build scripts (like automatically updating time-stamps on files, generating and applyling version numbers, creating custom build-targets such as doxygen documentation, etc. etc.). And, btw, your problem of updating the directory is basically a non-issue when using Cmake, it will take care of all that, including scanning the computer to find include directories and import libraries for external packages and stuff like that.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>what else could we learn from TMP?

TMP is a form of pure functional programming (no mutable data, no side-effects). So, in some sense you learn, from TMP, a very fundamental form of programming. But, academics aside, what's more important with TMP is what you can learn to use it for. Expression templates come to mind, among other things like concept-maps or all sorts of applications of tuples (or typelists).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Sure. The important thing is that you make sure that both have the same calling convention. If your DLL function was compiled with another calling convention, then that's the calling convention that you should have for your function-pointer type "pICFUNC". BTW, the default calling convention in C/C++ is "__cdecl" on most compilers.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>> I've been Programming in C++ for a year. I am done with Basics and all other OOP concepts(like inheritance,polymorphism and STL)

That's funny. I've probably said that (i.e. "I am done with ... ") every year since I started programming (13 years ago or so), but it was always preceded with "Last year as was such a noob, but now I am done with ...". The C++ learning curve is an endless recursion of "last year I sucked, now I'm awesome".


>> I want to be a game programmer, but i don't know what to study now?

Game programming is a huge topic in its own right. You should probably figure out more specifically what interests you.

As a starter, you should just start trying to render some basic stuff in 3D and move on from there. Either learn to use OpenGL, or take a head-start and grab an off-the-shelf rendering engine like Ogre3D. Later, you can figure out what is more interesting to you (e.g. rendering effects, particle systems, physic realism engines, game logic, animation (skinning), artificial intelligence, etc.). As soon as you are a bit comfortable with rendering basic stuff, then you can start thinking about some good idea for a computer game (of manageable complexity). That should keep you busy for a few years (it did for me).


>> Should I go for OpenGL or DirectX or GUI libraries or maybe something else.

awesome_cool commented: Thanks mike +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Or maybe this:

template <class Tuple, class T, std::size_t Index = 0>
struct find_first;

template <class T, std::size_t Index>
struct find_first< std::tuple<>, T, Index>
{
  static_assert(false, "Type not found in find_first");
};

template <class Head, class... Rest, class T, std::size_t Index>
struct find_first< std::tuple<Head, Rest...>, T, Index> : 
  public find_first< std::tuple<Rest...>, T, Index + 1> { };

template <class Head, class... Rest, std::size_t Index>
struct find_first< std::tuple<Head, Rest...>, Head, Index>
: public boost::mpl::size_t<Index> { };

void test_variadic_IndexOf()
{
  typedef std::tuple<char, int, short> T;
  std::cout << find_first<T, short>::value << '\n';
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you want to stick to C++, and remain cross-platform, I would just suggest you use Qwt (add-on to Qt). The image on their home-page is a Bode plot, so I'm pretty sure you can use that library for your purpose.

If you don't absolutely need C++, then Matlab or Octave is probably the way to go.

All of the above are entirely cross-platform, of course. It just depends on whether you need C++ or not (e.g. if the way you compute your system response is a piece of complicated C++ code, then the effort to move it into Matlab/Octave would be greater than the effort to learn and use Qt/Qwt, but otherwise, Matlab/Octave would be simpler and quicker).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>I'm a little surprised that your compiler didn't furnish you with a default constructor; I thought that was part of the language.

The compiler will only furnish a default constructor if there are no user-defined constructors. As soon as a class has at least one constructor defined by the user, the compiler will not generate a default constructor.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Whenever you provide default parameters for a function (whether a constructor or otherwise) they should appear in the declaration of the function, not in its definition. In other words, your constructor declaration (in header file) should be:

public:
	Person(string first = "", string second = "");

And your definition should start with:

Person::Person(string first, string second)
{

This should work. The error is explained by the fact that your class doesn't have a declared default constructor (a constructor that takes no parameter, or that has a default value for all parameters).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It is quite intriguing indeed. Maybe you should try to also print out the counts on the allocate calls.

So far, I don't know what would cause the double allocate, especially since it doesn't match the number of deallocate calls, that is even more disturbing in my opinion (I say the number of Delete and Allocate doesn't match, but I'm assuming that the code you posted corresponds to the output you got, because the explicit call of the destructor in addition to the automatic destruction of the vector explains the double Delete at the end, but that's an error, it is actually just one delete and then a memory corruption).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>what is an idiom in this context

A programming idiom is essentially a code structure (or sub-structure, or pattern) that is often used by programmers. Because there are recurrent problems in programming (like iterating through an array, controlling the creation method of objects, performing conversions, encapsulating resources, etc.), there are recurring code structures that solve those problems, and we call those idioms or design patterns. You can check out the wiki on Programming Idioms and here is a pretty complete list for C++. You can also check the wiki on design patterns.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>What is the point of a static method?

The point of a static method is that it can access all the private members of the class but isn't tied to an object (instance of the class). I would agree that it isn't the most useful thing in the world. One typical use is the factory function pattern:

class Foo {
  private:
    Foo();  //private constructor.
  public:
    static Foo* Create() {
      return new Foo();  //can access the private constructor.
    };
};

The above idiom is useful if you want to enforce a certain means of creating the objects of a class, or if you want to inject some post-construction code, or furthermore, this idiom can be used to give names to the different constructors (e.g. "FromString()"). This factory function idiom is very wide-spread, and the syntax resulting from using a static function is very neat too, e.g., Foo* pobj = Foo::Create(); (but note also that "factory patterns" can refer to many variations that may or may not involve a static function). The singleton design pattern is another idiom that usually involves a static method for the same reason as above, to make the constructor private.

Another general purpose for static functions is to provide functions that are related to the class but don't need to manipulate an object of that class. However, do not confuse static methods with friend functions, which are typically more useful than static methods to add related functionality to a class.

Static functions also …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First of all, I don't know if the implementation of "Matrix" class is special, but normally, in C/C++, the indices (i,j) go from 0 to N-1, not from 1 to N (like in Matlab or Fortran). If this Matrix class is implemented to handled 1-based indices, then I highly recommend that it be changed because you should stick with the established convention of the language you are using, which is 0-based indices.

Second, this inner loop:

for(j = 1; j <= rows; j++){
			if(i != j) {
				ratio = T1.el[j][i]/T1.el[i][i];
				for(k = 1; k <= 2*rows; k++) {
					T1.el[j][k] -= ratio * T1.el[i][k];
				}
			}
		}

Should be replaced by this (because you only need to obtain a triangular form for the back-substitution, meaning you only need to eliminate the rows below the diagonal):

for(j = i+1; j <= rows; j++){
			ratio = T1.el[j][i]/T1.el[i][i];
			for(k = 1; k <= 2*rows; k++) {
				T1.el[j][k] -= ratio * T1.el[i][k];
			}
		}

Finally, Gaussian elimination without a pivot is really unstable, doing the pivoting is not optional and cannot just be "the next row if the pivot element is 0". First, a floating-point number is rarely if ever exactly zero. Then, just picking the first row that meets some minimal requirement (absolute value greater than some tolerance) is not good enough in general. The standard thing is to always select the row with the largest pivot element (largest in absolute-value terms). Then, you swap the current row with the selected …