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

>>Do I need to protect the variable?
No. I'm guessing your sensitivity values are of a primitive type like double or int. All read-only operations are thread-safe, period (that is also valid for a non-primitive POD types). As for writing, storing a double or int value is essentially a single operation, I mean, at one clock cycle the value stored will be the previous value, and at the next clock cycle the value will have changed. Where can there be a thread-switch between the two that would cause the reading of an invalid value? That's why primitives are considered "lock-free thread-safe", because they are thread-safe without requiring a mutex lock (as far as I know, only primitives are like that, or near-primitives like smart-pointers).

The only case where it would matter is if you have a function that reads the value multiple times and expects it to be the same every time. In that case, just read it once into a local variable at the start of the function (or loop).

Mutex locking in multi-threaded software is only really needed when you have some data structure that has to go in a momentarily invalid state and might remain so for a little while. For example, resizing an array would usually involve resetting the "size" variable, then allocating a new array, copying the content, deleting the old array, and resetting pointer to its new location. The problem with this is that as soon as the size variable is …

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

The win32 API requires wide-char strings. You need to add a leading L in front of the literal string to tell the compiler to create a wide-char literal string:

windowClass.lpszClassName = L"WindowClass"; //notice the L in front.

And similarly for the other place where the error occurs.

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

aPtr is a pointer to an array of "double" variables. When you want to copy one NumberArray object into another, the new object has to allocate a new array of doubles which can contain as many elements as the other object, and then copy all the elements from one array (the one in "obj") to the other (the one that just got created).

So, line-by-line:

NumberArray::NumberArray(const NumberArray& obj) //note: this is the proper way.
{
  arraySize = obj.arraySize;    //reads in the size of the array in obj
  aPtr = new double[arraySize]; //creates an array of the same size
  for(int index = 0; index < arraySize; index++) //iterates through both arrays.
    aPtr[index] = obj.aPtr[index]; //copies the content from obj.aPtr to aPtr.
}  

NumberArray::NumberArray(int size, double value)  //takes in the size of the array and the initial value for all the elements
{
  arraySize = size;             //reads in the size of the array.
  aPtr = new double[arraySize]; //creates an array of that size.
  setValue(value);              //sets all the elements of the array to "value".
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, primitives are generally thread-safe just by the virtue of value-semantics and their primitive nature (as in, any read/write operation on them is atomic, i.e. it's extremely unlikely that a thread switch would occur in the middle of the operation, which is really where mutexes are required).

For larger classes, the thread-safety should really be implemented as part of the particular class. boost::shared_ptr are lock-free and thread-safe, like a primitive type, and dereferencing the underlying pointer is as thread-safe as the class of the object it's pointing to.

If you do want to implement this template you posted, may I suggest that you use more natural semantics instead of this ugly get/set:

template<typename var_type>
class ThreadSafeVariable {
  mutable boost::mutex mut;
  var_type value;
public:
  operator var_type() const {
    boost::mutex::scoped_lock(mut);
    return value;
  }
  ThreadSafeVariable<var_type>& operator =(const var_type& newValue){
    boost::mutex::scoped_lock(mut);
    value = newValue;
    return *this;
  }
};

This should allow you to basically substitute an object of type double for an object of type ThreadSafeVariable<double> without changing anything on the user-side (all arithmetic operations and what-not will be unchanged by trigger an implicit, thread-safe local copy of value to be used). Obviously, this will have a lot of overhead because lock and unlock mutexes is an expensive operation, so you will almost always be better off locking a mutex externally to avoid any repetitive locking and unlocking. To solve this, you can also use a mechanism similar to the weak_ptr/shared_ptr relationship. With weak_ptr/shared_ptr, the weak_ptr can only lock a shared_ptr …

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

>>Do I need to pass it as arguments if I want to implement it by std::tr1::bind?

If the AnyFunctor needs arguments when called, you need to get those arguments from somewhere. So the idea, like in your last piece of code, to create some temporary variable with some arbitrary value and passing them to the function is kind of ridiculous (unless this is a concept-check, in which case, there are far better ways to do this). So, yes, you will need to pass those parameters to the testFunctor() function and then forward them to the functor call.

1 : if type anyFunctor need 3 arguments to initialize it, what should I do?
Do I have another way to make this become more adaptable except
of passing strategies like parameter(the way of stl did)

The way STL does it is pretty much the only scalable way to do this. You can also use the Boost.Lambda constructor/destructor templates to bind the constructor call with some parameters, but I doubt it will help much.


2 : if type anyFunctor need to accept different number of variables, how could I make it adaptable?

Just like std::tr1::bind did it (or as I would refer to it as Boost.Bind). With C++0x, the coming standard, the support for variadic templates will allow you to do this in one shot:

template <typename anyFunctor, typename... Args>
void testFunctor(Args... args) {
  anyFunctor f;
  f(args...);
}; //all of this …
StuXYZ commented: I learnt stuff, thanks +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This, to my knowledge, is not a particularly common pattern, especially in OOP. It is, however, somewhat ubiquitous in Generic Programming (which can be used alongside OOP).

In OOP, I think they are mostly referred to as mixins (as in, mixing in different classes to make a sort-of bast_ard superclass). Read more.

As for the term collaborations, I think it is not very much used (I had never heard it, as an OOP design pattern, at least). And googling for it yields too much lexical pollution problem with other more common use of the word "collaboration" in OOP and C++ programming, for example, Collaboration Diagrams (as pointed out by rubberman) or just general non-technical use of the word "collaboration". But I did find this little article that seem to refer to it as a technical term and provides a basic explanation of it (and it basically equates it to the concept of mixins).

To explain it, the basic idea is to create some classes that are not really fully function or useful by themselves but implement just one particular feature. Then, by assembling a set of such simple, "incomplete" classes together, you can make a complete one. The simplest example I can think of is the non_copyable class (part of Boost for example). Say I have this simple class:

class non_copyable {
  private:
    non_copyable(const non_copyable&);
    non_copyable& operator=(const non_copyable&);
};

Because both the copy-constructor and assignment operator are private and are not supplied …

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

To find a bottleneck in an application, you need to use a profiler. It will tell you how much processing time is needed by each function in your code. I have rarely done profiling, so I can't really recommend any good tools (google is your friend).

Anytime a software involves inverting large matrices, it is almost certainly the most expensive operation in all the code. Make sure that you are using a good matrix inversion method for the particular matrix you have. What method are you using?

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

There are a few options. But this is a classic problem with templated code. For instance, the STL libraries are not compiled (so basically, standard C++ libraries are open-source).

The first option is to put all the definitions of the member functions inside a .cpp file and #include the cpp file at the bottom of the header file (within the header guards). Also, you will have to put the "inline" keyword in front of the function definitions to avoid some potential multiple definition problems. Still, this method just hides the code in a separate file, but that cpp file will have to be distributed with the library as source (you cannot precompile it).

The second option is, if you know for sure all the types with which this class template can be instantiated, then you can precompile the cpp file with all the source by doing explicit instantiations in the cpp file. But, then, if anyone tries to use that library with a type that you didn't intend, it won't work (they will get an unresolved external symbol error).

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

GNU C allows for a -1 return value if the implementation does not provide a way to obtain a system time.

POSIX allows for time_t to be a floating-point value.

QNX gives the same specification as GNU C, because it is intended for embedded systems which often have very different methods to access the system time (if it has it at all).

Similarly, many embedded systems' standard libraries / compilers / OS do not provide time functions at all. For example, Windows CE's CRT.

You may say that using embedded systems to provide examples of implementations that won't behave "normally" is a bit of a cheat since very few embedded systems are even remotely standard compliant, well, you asked for examples, you got some.

It probably wouldn't be all that surprising either if older Windows or DOS implementations (still post-ANSI-C) would use the MS DOS epoch of Jan 1st 1980.

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

This is the usual loop to use:

#include <fstream>
#include <iostream>
#include <vector>
using namespace std;

//define your SalesRecord.

int main() {
  vector<SalesRecord> data; //storage for all the SalesRecords.
  
  ifstream CheckFileStream;
  CheckFileStream.open("SalesRecord.txt",ios::binary);

  if(CheckFileStream.is_open()) {
    SalesRecord tmp; //temporary storage for the one element to be read.
    while(CheckFileStream.read((char*)&tmp, sizeof(SalesRecord))
      data.push_back(tmp); //adds the element to the data.
    CheckFileStream.close();
  } else {
    cout << "File not found, exiting..." << endl;
    return 1;
  };

  return 0; //all went well.
};

The above works because the read function returns a reference to the ifstream which will evaluate to false if it has reached the end of the file. So, as long as the end is not reached, add the last read element to the dynamic array of SalesRecords (the standard C++ thing for a dynamic array is std::vector, as shown).

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

@AD
The phrase "the types declared are" comes in many places. There is a semi-colon after size_t at 7.23 also. I understand that English might not be your primary language, so let me clarify. The phrase "the types declared are" starts an enumeration of types that should be declared within the header file to which the section of the standard pertains. The enumerated elements are separated by semi-colons. If you notice, size_t appears under the headers stdlib.h, stdio.h and time.h. It simply means that the size_t type should be declared in all these headers, such that if one includes at least one of these three headers, the type size_t will be defined. It has absolutely nothing to do with time_t which is just another, separate element of the enumeration under 7.23. If you thought that section 7.23 somehow implied that time_t must be declared as a size_t alias, you misunderstood the phrasing used (I admit it's not the clearest sentence, but the context makes it clear when you take a closer look at it).

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

>>I am not clear as to what a seed is
I think the easiest way to think about it, from a beginner's perspective, is that, since a computer is deterministic (it can't actually produce truly random numbers), the best it can do is use a formula that produces "very wacky" results. In other words, the numbers generated by the formula make a very jumpy sequence of numbers where each number doesn't really seem (to the naked eye) as having anything to do with the previous one. But this is still a deterministic sequence, because if you start at the same place in the sequence, you will always get the same sequence of following numbers. The seed is, simply put, where you start in that sequence. And to get "random" number sequences, you need to start with a "random" seed. Since the exact time at which a program is started is pretty unpredictable and arbitrary, it's a fairly good "random" number to start with.

@AD:>>Its up to you to disprove it.
No. You are claiming that all implementations of time() are the same, you have the burden of proof (a pretty heavy one too).

@Narue:>>I wouldn't recommend putting the ball in my court.
Well said!

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

First of all, keeping a sorted linked-list is never useful, because it requires linear time for a look-up and linear time for insertion. Keeping it unsorted requires linear time for look-up and constant time for insertion, tha's much better. But I guess you are doing this as an exercise.

The algorithm you posted is very weird. Where is the logic in it? The variables names are incorrect (what is head, tail, count, and p, these are all undefined variables).

The pseudo-code for this algorithm is pretty simple and should be followed closely:
1) Create a new node X and store the string in it.
2) If the list is empty (head pointer == NULL),
then set the head node to X, and exit.
3) Find the node A in the list whose name is smaller than X->name, but whose next node is either NULL or with name larger than X->name.
4) If A->next == NULL ,
then A is the last node in the list and X simply is appended at the end of the list, by setting A->next = X; .
5) If A->next != NULL ,
then insert X between A and A->next, i.e. set X->next = A->next; and set A->next = X; .
6) If you are keeping track of the tail node, then, if tail->next != NULL , set tail = tail->next; .

That's all. Your algorithm looks nothing like the above. Also, you …

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

>>I am not clear as to what a seed is
I think the easiest way to think about it, from a beginner's perspective, is that, since a computer is deterministic (it can't actually produce truly random numbers), the best it can do is use a formula that produces "very wacky" results. In other words, the numbers generated by the formula make a very jumpy sequence of numbers where each number doesn't really seem (to the naked eye) as having anything to do with the previous one. But this is still a deterministic sequence, because if you start at the same place in the sequence, you will always get the same sequence of following numbers. The seed is, simply put, where you start in that sequence. And to get "random" number sequences, you need to start with a "random" seed. Since the exact time at which a program is started is pretty unpredictable and arbitrary, it's a fairly good "random" number to start with.


[edit]
for any comments that seem to be made without a previous post in this thread, see this discussion
[/edit]

@AD:>>Its up to you to disprove it.
No. You are claiming that all implementations of time() are the same, you have the burden of proof (a pretty heavy one too).

@Narue:>>I wouldn't recommend putting the ball in my court.
Well said!

Smartflight commented: Well explained! +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First of all, the second case will not compile, because the compiler will say "invalid use of incomplete type 'Point'". When you forward declare a class, you just tell the compiler that there is a class called Point, defined later. Since it is not yet defined (thus, incomplete), the compiler can only accept that you declare variables or data members that are references or pointers to objects of that class, not direct objects of that class. So, I guess the intended example was:

// myclass.h
#ifndef MYCLASS_H
#define MYCLASS_H

class Point;

class MyClass
{
private:
Point* m_Point; //notice the pointer to Point, not Point directly.

//...
};
#endif

// myclass.cpp

#include "myclass.h"
#include "point.h"
//...

>>difference in performance
Absolutely none. At least, not at run-time, and not in this simple example. The second case can reduce compilation times (i.e. fewer header dependencies lead to less code to compile in general, which reduces the overall compilation time). It can also lead to some increase in performance if several other measures are taken, which is beyond what I could explain here. In the basic cases, as shown above, it leads to no performance increase whatsoever.

However, since the second case forces you to hold the object m_Point by reference or pointer, there will be an extra level of indirection (i.e. you have to dereference the pointer to get to the object). That will be slightly slower than being able to store m_Point by value (as in the first case). …

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

AD is right, because of name-mangling in C++ (and ABI), you have to wrap all your C++ code into a C API (C functions). For example, say I wanted to "export" the following class from a DLL:

class Foo {
  private:
    double value;
  public:
    double GetValue() const { return value; };
    void SetValue(double NewValue) const { value = NewValue; };
};

My exported DLL functions could look like this:

typedef Foo* FOO_HDL;

extern "C" { 

__declspec(dllexport) FOO_HDL __stdcall FooCreate() {
  return new Foo();
};

__declspec(dllexport) void __stdcall FooDestroy(FOO_HDL obj) {
  delete obj;
};

__declspec(dllexport) double __stdcall FooGetValue(FOO_HDL obj) {
  return obj->GetValue();
};

__declspec(dllexport) void __stdcall FooSetValue(FOO_HDL obj, double NewValue) {
  obj->SetValue(NewValue);
};

};

But, to be really safe, you also need to make sure that no exceptions leave the DLL boundary. So, in theory, you would need to wrap all the bodies of all the exported functions with a catch-all clause, as such, for example:

void __stdcall FooSetValue(FOO_HDL obj, double NewValue) {
  try {
    obj->SetValue(NewValue); //if this operation throws an exception, it must not propagate further.
  } catch(...) {             //so, catch all exceptions.
    //do something.. or not.
  };
};

But, the above is a bit tedious and few people do it. If an exception occurs and you don't catch it before the boundary of the DLL is traversed back during stack unwinding, you will get a crash (in some case that's acceptable, in others, it is not).

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

When your code grows larger, one book becomes essential: C++ Coding Standards, by Sutter and Alexandrescu. And probably reading through a few of the GotW website is also a good idea.

The Boost guidelines are also very good. And this article too.

Other than that, I have rarely seen any real good resources (online or not) that comprehensively treat the subject of error-handling (I think many traditional C++ programmers still have trouble committing too much to exception mechanisms and still rely on C-style error-codes for a lot of things, if not all).

But one thing is clear though, from all those who know what they are talking about, the best error-handling method is throwing and catching exceptions, no doubts about that. So, the starting point is understanding exceptions and learning how to use them effectively. Read the C++FAQ on exceptions, as a starter.

A few useful things:
ScopeGuards, Pragmatism, RAII, Copy-and-swap, Non-throwing swap.

Ancient Dragon commented: You always have great answers :) +36
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>i've seen in some sources that some classes have Getters and Setters even for public data members
Remember that a large amount of open-source software is designed like a steaming pile of dog... Don't consider everything you see as "good practice" or as if the design choices they made were good, justified or even planned at all. This is true of roughly all programming languages with equal proportions: the amount of very poorly written open-source code far exceeds the amount of well-written open-source code. It doesn't mean that it is not _usable_, it just means that you shouldn't derive too many programming guidelines from the open-source code that you see.

>>I don't know why would someone lose time for declaring functions for public data members
Did you consider that maybe this didn't come at once? Maybe it used to be private/protected and used via get/set in many other functions of the software, then somebody decided that he preferred the data members to be public (a stupid decision IMO, but possible). Also, maybe there used to be more complex behaviour in the get/set functions (like bound-checking or mutex-locking) which was taken out after some testing or performance assessment, but the get/set were left such that the rest of the software would not need refactoring. There are plenty of other reasons why this might have happened (amongst them: just that the author is stupid). Real-world programming involves a lot of little issues, often related to maintenance, that make real-world …

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

>>Is there a particular thing it does that makes the program slow/unstable?
No. It makes absolutely no difference in terms of performance, it is just a trick to get the compiler to do its job.

>>Why should I only do the forward-declarations as a last resort?
I wouldn't call forward-declarations a last resort (there are far worst things, like using a void* and doing casts later). There is nothing wrong with a forward-declaration, but it should be considered only after taking a close look at the design to see if it is necessary. The reason is simple. A forward-declaration is generally used to achieve inter-dependency between two classes, which is never desirable on a software design and maintainability stand-point, but it is not always avoidable. But if the inter-dependence can be avoid, it will lead to better design. You have experienced that yourself. You looked back at your design a found a better, less-coupled way of achieving the same task (with a bonus of efficiency). That's why I recommended rethinking your design first, because I was quite certain that you could find a solution that didn't involve this inter-dependency (most of the time, forward-declarations are avoidable via better design).

griswolf commented: Good points +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This is called a circular referencing problem (Particle needs MapGrid, which needs Particle, which needs MapGrid, ... ad infinitum). Headers guards won't solve that problem. You need to either break the circular referencing through a (better) design of the software, or you can turn the circular referencing to a semi-circular referencing.

Options to restructure:
- Perhaps the functionality for which one of the classes needs the other could be implemented differently. Often, circular dependencies are an indication that the tasks are not properly split between the two classes. Take a second look at the functionality to see if it really makes the most sense to do it that way.
- Perhaps you simply need to define a base class for one of the two classes. If one of the classes uses the other in a simple non-intrusive manner, then, probably, you can put this simple interfaces as pure virtual functions of a base class. In this case, you have no more circular referencing. For example, MapGrid could depend on BaseParticle, and Particle could depend on both MapGrid and BaseParticle, i.e. no more circular dependency.

Breaking Circularity:
If the above options are not suitable for your application, you can break circular dependency via forward-declarations. Here is an example:

//in MapGrid.h
#include <windows.h>
//...
//do not include Particle.h

class Particle; //forward-declaration of class Particle (found in Particle.h)

class MapGrid {
  ///... uses Particle* or Particle& in the function prototypes or data members.
};

//in MapGrid.cpp
#include …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Alright:

1.Are memory adresses a certain size?

This is implementation dependent, but normally a 32bit system would take 4 bytes (32 bits) to store a pointer (on a 64bit it is usually 8 bytes).

2. A pointer like this: int *pointern; does what exactly?

It declares a pointer named "pointern" which can store the address to an integer value, but since it is not initialized, it is not pointing to any valid or usable memory (the address is a garbage value). Reading or writing to the address stored in pointern (i.e. a garbage address) is undefined behaviour (meaning that in the best case it will just corrupt your memory, in a worse case it will crash your application, and in the worst case it will crash your operating system (very unlikely, but possible, I guess)).

3. When I do: pointern = new int[5]; . The adresses are 0x5f0fb0, 0x5f0fb4 etc. What happened to the 0x77159e34?

The 0x77159e34 was the garbage value previously stored in pointern, it could be any address and probably would be different (almost) every time you run the program. This previous address is meaningless, it does not point to valid memory, nothing happens to it after the above statement, and who cares?

However, if pointern did point to valid memory before, memory that was dynamically allocated (with new), then simply resetting the pointer to point somewhere else would mean that the memory at the previous address becomes unreachable and, more …

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

>>how can it have negative values?

Say you have 8 bits, thus, it can represent 2^8 different numbers (which is 256). Well, you can split the range in two and represent numbers from -128 to 127, inclusively. You could, for example, reserve one bit (at the start or end) that gives the sign of the number (i.e. 0 = plus, 1 = minus). That's one way that is typically used for floating-point numbers (but these numbers have a more complicated representation). Usually, however, negative integers are represented by taking the 2's complement of the bits, see this wiki. The computer architecture (the processor) has particular representations, in binary, of the numbers (integers and floating-point values) and the modules of the processor are made to use those particular representations and perform the required operations on the values.

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

I can't answer those questions directly because they sound too much like assignment questions and you shouldn't be given a freebie (it would help you to learn). However, I can correct some of your underlying misconceptions.

>>I've seen some that have 6 characters after the 0x and some that have 8 after the 0x
How the values are printed to the screen (when using cout) does not relate to how much memory is used to store them. For instance, on a 32bit system, normally, an integer (int) would take 4 bytes in memory, but, with 4 bytes, you can store an integer up to about +-2 billion (+-2^31). When printed to the screen, a large value would take much more that 4 characters, but it still requires only 4 bytes to store in memory (in binary, 4 bytes = 32 bits). So, whatever the number of characters that the address stored in a pointer takes to be printed out does really matter that much.

>>Selects a location in the memory? Randomly? Or maybe like the first availible memory adress?
A pointer is a variable like any other variable and it has a value (in case of pointer, that value represents an address in memory). If you create a variable like int i; without giving it an initial value, it will have the value that corresponds to whatever bits were in the memory location where that variable exists at the time it was created (i.e. we usually …

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

The syntax is:

class Thing
{
    public:
    template <typename T>
    operator T(); //notice, no return type (it is implicit for conversion operators)
}

And it certainly is possible (at least it works on GCC). I'm not sure why you would want to do that, but you can.

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

Yes there is.

First of all, your solution of adding an int variable to the Base class that the most derived class will set upon construction is a very basic form of RTTI (Run-Time Type Identification). But, C++ already has RTTI, and it can be used in two ways, via typeid() and via dynamic_cast. Both require that you have at least one virtual function in your classes (which you should, since the destructor of the Base class has to be declared virtual, if you are going to derive the class). So here is an example:

for(std::vector<Base*>::iterator it = Container.begin(); it != Container.end(); ++it) {
    DerivedC* ptr = dynamic_cast<DerivedC*>(*it);
    if(ptr) {       //if ptr is non-NULL, then the cast succeeded and *it is a DerivedC object.
      delete ptr;   //Delete the object.
      it = Container.erase(it); //and erase it from the list (and reset the iterator).
      --it;
    };
  };

This can also form the basis of the Visitor Pattern in OOP (not to be confused with the Visitor Pattern in GP, which is far more powerful). I personally am not a fan of the OOP Visitor Pattern, but it can be useful sometimes.

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

First of all, this is highly dependent on the capabilities that you want your plugin system to be able to handle. It can range from a very simple set of capabilities, leading to a fairly easy task to accomplish, to a very comprehensive set of capabilities, leading to a very very difficult task to accomplish.

Simplest case:
If all you want is for your plugin to be a DLL that provides a certain set of functions, then it is pretty easy to do. For example, imagine that the plugin's sole purpose is to load a sound file and play it. You could define a certain number of standard functions (like LoadAudioFile(), PlayAudio(), PauseAudio(), StopAudio(), etc.). Then, in your application, given a DLL, you have to load it dynamically (with LoadLibrary() (windows) or dlopen() (linux)), get function pointers for each of the standard functions (with GetProcAddress() (windows) or dlsym() (linux)), then, if all the pointers are non-NULL (i.e. they all exist in the DLL, or at least, a non-optional subset of them), you can use those function pointers to execute the functionality from the DLL, and finally, when done with it, you free the DLL (with FreeLibrary() (windows) or dlclose() (linux)). And that's it, pretty much.

Complex case:
If you want your plugin to provide an extensible set of functionalities and possibly an extensible set of classes, then it becomes much harder. I have done …

jonsca commented: Nice post. +8
gerard4143 commented: Nice break down +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>I was just wondering why you passed const Matrix2D& a as the first variable in your version of getTranspose()? Does the const mean that a cannot be changed by the function?

Yes. This is called const-correctness. If a function does not modify a parameter that is passed by reference or pointer, it should use a const qualifier to force the non-modification within the body of the function (in case you mistakenly modify it) and to publish to the anyone using this function that it will not modify the parameter.

You might encounter a small issue with that. Constness is "infectious" in the sense that once you have a variable (parameter or otherwise) that is const-qualified, you can only call const member functions on it or pass it to a function that takes a const-qualified reference or pointer, or by-value. This implies that the functions like getNumRows, getNumColumns, and getElement should be const as well, as such:

class Matrix2D {
  //....
  public:
    int getNumRows() const;            //notice the const at the end.
    int getNumColumns() const;         //ditto.
    double getElement(int, int) const; //ditto.
  //...
};

//and similarly in the definition:
int Matrix2D::getNumRows() const
{
  return r;
};

int Matrix2D::getNumColumns() const
{
  return c;
};

double Matrix2D::getElement(int i, int j) const
{
  return elements[i * c + j];
};

In the above, the const at the end of the member functions impose the restriction that the data members of the Matrix2D object cannot be modified within the body of those functions. This …

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

Just print the 3 last elements of the sorted array:

//this prints the first three elements (largest elements)
     for(i=0; i<=2; i++)
     {
        cout << x[o[i]] << " " ;
     }
     //this prints the last three elements (smallest elements)
     for(i=0; i<=2; i++)
     {
        cout << x[o[15-i]] << " " ;
     }
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Also, are DLLs okay on Ubuntu?
I think rubberman answered that.

>>What format are the librarys like iostream or cmath in?
What format? They are just C++ header files, without the .h at the end. You can check it out for yourself, they are usually located in "/usr/include/c++/4.4/" (or /usr/local instead of just /usr, and that version 4.4 depends on the version of your GCC compiler).

>>the <> really matters because then I don't have to put the file in all of my projects.
The difference between "" and <> with the include of headers is just that with "" the compiler will look for the file first in the current directory of the file that is being compiled, and then, it will look in the include directories (the stuff you specify with -I in the command-line compilation) and finally, will look into the standard system-wide include directories (like /usr/include/..). With <>, the compiler will not look in the current directory of the file being compiled, but it will look in all the same directories after (as with ""). Basically, you typically use "" when it is a custom header (part of the software/library you are working on), and <> otherwise. But really, there is little difference between the two (mostly a convention, but note that some compilers could behave differently).

To add your library's include directory (where you have all the header files) to the system's include paths. On Linux, these paths are …

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

For an FEA software, I highly recommend that you pick an off-the-shelf library for the matrix operations and numerical methods. These are not things that are trivial to code and produce efficient and lean implementations of. Furthermore, you really need a sparse matrix library, because FEA matrices are very often extremely sparse and running full-matrix operations on them is just very very wasteful. But, of course, good sparse matrix libraries are even harder to find.

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

First, the way that you can test whether you have run out of memory in the program is to check that the pointer you get from malloc is not NULL. This pointer will be NULL if you are out-of-memory. This is also why you get the error of dereferencing a NULL pointer (access violation).

Second, memory issues are hard to solve with limited knowledge and experience, but they are even more problematic when using C-style arrays (and with malloc). You should definitely switch to std::vector storage instead. And for you matrices, store them in one contiguous memory block (not array of arrays, but one big array). With this changes, your constructor of Matrix2D would be as such:

// assuming that elements was declared as: std::vector<double> elements;

Matrix2D::Matrix2D(int n_rows, int n_columns)
{
	r = n_rows;
	c = n_columns;

	elements.resize(r * c);
        
        for(int i=0; i < r; ++i)
	{
		for(int j=0; j < c; ++j)
		{
			elements[i * c + j] = 0.0; //map the indices as so.
		}
	}
}

With the above changes, you won't need to worry about clean-up (deallocating memory), because the std::vector object will take care of that. Similarly, the copy-constructor and assignment operator are also automatic deep-copies and won't leak.

Finally, if your matrices are large, you really need to make sure that copying is minimal (i.e. don't copy matrices around all the time). Your "transpose" function is extremely wasteful (at least if the compiler isn't really good at optimizing, which it is …

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

The << and >> operator do have higher precedence than the bitand & operator, see this table.

However, I would not recommend that you rely on operator precedence in that kind of fashion. If you need, absolutely need, to use a #define, then wrap everything with parentheses and avoid the problem:

#define FLAG_FAST         (1 << 0)
#define FLAG_VISIBILE     (1 << 1)
#define FLAG_BIG          (1 << 2)

In this case, however, you are defining those flags in a very impractical fashion. This is the more "usual" way, using hexadecimal numbers:

#define FLAG_FAST         0x00
#define FLAG_VISIBILE     0x01
#define FLAG_BIG          0x02
#define FLAG_FOO          0x04
#define FLAT_BAR          0x08
//...

But when I say that the above is "usual", I really mean that it is commonly found in C libraries or APIs, but not in C++ code. In C++, there are several alternatives that are safer and better. One is to use a const global variable (or static const data member of a class):

const unsigned int FLAG_FAST     = 0x00;
const unsigned int FLAG_VISIBILE = 0x01;
const unsigned int FLAG_BIG      = 0x02;

Another popular solution is to use an enum:

enum MyFlags {
  FLAG_FAST     = 0x00,
  FLAG_VISIBILE = 0x01,
  FLAG_BIG      = 0x02
};

And usually, the enums are nested in the class or namespace they are used in or for.

MACROs in C++ have their place for very special purposes that cannot be achieved by any other means and do require a simple text-replace preprocessing. But defining …

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

What you need is basically a discriminated union (often called a variant type). This is just a union of an integer and a character along with a flag to tell which type is actually stored in the union. Here is a simple example:

class CharOrInt {
  private:
    union {
      char c;
      int i;
    } data;

    enum { char_data, int_data } data_type;

  public:
    explicit CharOrInt(char c) { data.c = c; data_type = char_data; };
    explicit CharOrInt(int i) { data.i = i; data_type = int_data; };

    CharOrInt& operator=(char c) { data.c = c; data_type = char_data; };
    CharOrInt& operator=(int i) { data.i = i; data_type = int_data; };

    bool operator <(const CharOrInt& rhs) const {
      if(data_type == char_data) {
        if(rhs.data_type == char_data) 
          return data.c < rhs.data.c;
        else
          return ((data.c < '0') || ((data.c <= '9') && (data.c - '0' < rhs.data.i)));
      } else {
        if(rhs.data_type == char_data) 
          return ((rhs.data.c > '9') || ((rhs.data.c >= '0') && (rhs.data.c - '0' > data.i)));
        else
          return data.i < rhs.data.i;
      };
    };
};

You can basically used the above data type instead of the int type in your sorting algorithm and it should work as you want. If not, just modify it to suit your needs.

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

**Please use code-tags in the future**

The following expression numerater/denominater is a division of integers, this will be computed with integer arithmetics (the remainder of the division is discarded, i.e. 1 / 2 = 0, 4 / 3 = 1, etc.).

To obtain the answer of the division as a "normal" real-valued division, you need to cast the integers to floating-point values first, and then do the division, i.e. float(numerater) / float(denominater) .

That should fix your problem.

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

I already did in a previous post (using the name Timer), just to clarify:

//in MySingleton.h:
#ifndef MYSINGLETON_H
#define MYSINGLETON_H

class MySingleton {
   int value;
   // Private constructor, to forbid the construction from outside this class.
   MySingleton () : value(0) {} 
   //Non-copyable (such that another instance cannot be created)
   MySingleton(const MySingleton&);
   //Non-assignable for the same reason.
   MySingleton& operator=(const MySingleton&);
public:
   //Static member function that returns the instance of the singleton by reference.
   static MySingleton& instance (); 

   //other public member functions:
   int getValue() const { return value; }
   void setValue(int NewValue) { value = NewValue; }
};

#endif

//in MySingleton.cpp

//define the static member function in the cpp (this is crucial):
MySingleton& MySingleton::instance() {
  //Create a static-scope instance (initialized only once).
  static MySingleton only_copy;
  return only_copy;                  //return by reference.
};

Here is another example I wrote. And similarly on wikipedia (only for the description, because the code is in Java and should not be used in C++ because it is not safe (C++ has different rules about global objects like singletons)).

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

>>I guess I could use my singleton as a master class from which all other classes would be derived
NO! Don't do that. Really, don't!

>>maybe I could use some friend functions.
Hissh, probably wouldn't do that either, sounds messy and unnecessary.

>>how can the member functions of my set of classes access the float value they need within my singleton.
If it makes sense for different part of the software to modify the float value at will, then provide a function to do that. In other words, have both a GetValue() and SetValue(float NewValue) functions defined in your singleton.

>>I am defining my singleton within main()
That's not the way to do it. You need a separate header for the singleton's declaration and a separate cpp file for the singleton's implementation (don't put any of the two in your main.cpp file, I mean, for real, it completely defeats the purpose of the singleton).

All the classes that need to access (public) members (data or functions) of the singleton should include the singleton's header and use the static member function to get the instance of the singleton on which to operate.

I don't see how this could cause any problems, as long as the public functions of your singleton are sufficient for the purpose that any classes could make of it. If your singleton doesn't provide enough access to its members, add access to them, that's all (but don't abuse, because …

VernonDozier commented: As always, good post. +13
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The more typical way to handle these situations is to have a "finalize" function in the SecClass that the MainClass can call before "really" destroying itself. This way, the responsibility is on the MainClass to make sure that "finalize" is called when the MainClass is still fully-functional. Then, the destructor of SecClass no longer has to do this trickery (and, this also works whether the SecClass object is held by pointer or by value in the MainClass).

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

Just contact the author/distributer of the library and make your case for adding your functionality or fix to the code. If it doesn't change the interface and has good justification for the addition, the author will probably be happy to add it.

Otherwise, use an ad-hoc fix, because as arkoenig said, this is not safe or maintainable.

Amongst ad-hoc solutions, there are a few things that can be done. First, you can wrap the class in another one (not inheritance, but composition). This would not be possible if you need the modification to access protected members of the class, or if you must also have many other classes derived from this class to include the new functionality. In that case, if the class in question is a class template, you can use a dummy wrapper class for the template argument and specialize the class template for that argument. For example, I could reimplement the constructor of std::vector using a dummy allocator class:

template <typename Allocator>
class wrapper_dummy : public Allocator { };

namespace std {
  template <typename T, typename Allocator>
  class vector<T, wrapper_dummy<Allocator> > : public vector<T, Allocator> {
    public:
      vector() { 
        //add functionality here.
      };
  };

};

The above might not work as is, but that's the basic idea of it. Specializing templates is one classic way to hack your code in, legally and safely. But, this only works if the class is already a class template and if it is possible to specialize it without …

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

The downside of using extern constants is that they will require linking. Basically, the header tells the code that you are compiling that when you link your application, there will be definitions for those constants available to the linker to find. So the compiler annotates those constants as having to be looked up at link-time (with associated external symbol). Also, when compiling the source file in which the constants are defined, it creates a published symbol for each constant.

The disadvantage is obviously that you get "larger" static libraries (or shared libraries) because they need to have more external symbols. This means "longer" times for linking the compiled code. Also, if compiled into shared libraries (.so or .dll), it will result in "longer" time for loading up the program. But, of course, if the number of constants is small, it really won't be that much longer (probably not noticeable).

The advantage is that you can change the value of those constants in the source file without having to recompile all the code that uses these constants (you only need to re-link them, if compiled in static libraries, and you don't need to do anything more if compiled in shared libraries).

Generally, I would recommend that you use extern constants only if you plan on changing their values fairly often. For constants that are really "constants" like PI/2, there really is no point, just take out the "extern" keyword and define them in the header (as in your …

thekashyap commented: Good desc of the limits.. +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The general rule is that the lifetime of an object ends as soon as the body of the destructor is entered. This would normally mean your code is "illegal". However, it technically isn't entirely. You should still be able to call member functions or access POD data members fairly safely (it is against good coding practices, but it shouldn't crash).

The only reason that I see why it would crash is if: you call a virtual function of the MainClass. Then, it should crash. If you call a virtual function, you should know that the virtual table of the object is no longer valid when you enter the body of the destructor and you will basically be dereferencing a null-pointer.

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

I personally don't know much at all about hash tables (except for what they are and what they are useful for). But I think this article by Narue is probably a good place to start.

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

A program that does this kind of manipulations is called a "symbolic math" engine or library. For example, softwares like Maple or Mathematica use or include symbolic math code. I have never used any free C/C++ library that does that (because it is not really a trivial thing and is rarely useful), but I know of one which is GiNaC (under GPL).

Frankly, if all you want is to turn a "non-standard" formulation into the standard formulation for a problem like a linear system of equations, just do it.

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

A constant time algorithm is trivial:

int main() {
  int i = 0; //this "algorithm" is O(1)
  return 0;
};

Constant-time just means an algorithm (or part of an algorithm) that takes the same time to execute without any dependence on the number of elements or size of data or anything like that. For example, a simple (naive) algorithm to take the average of an array could be:

int main() {
  int numbers[] = {1,2,2,4,6};
  int sum = 0;

  for(int i=0; i < 5; ++i)
    sum += numbers[i];      //taking the sum is O(N), here N = 5.

  double avg = sum / 5.0;   //computing the average from the sum is O(1).
  return 0;
};

Also, note from the above, the "standard" or at least "usual" way of writing a for-loop in C++ (arrays are indexed from 0 to N-1).

In the little code above, the first "algorithm" (taking the sum) runs in O(N) because the more data you have the more time it takes, linearly proportional. The second "algorithm" (getting the average from the sum) is O(1) because it takes the same time regardless of the amount of data. But, the overall algorithm takes O(N) because the constant part is negligible compared to the linear part, this is why you don't see things like O(N^2 + N + 1) in the "order of magnitude" notation, because the fastest growing term always subsumes the others when N is taken to be large.

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

The reason why your code looks messy is mainly because your knowledge is still very limited. For example, here is how the solution would turn out if I wrote it with the code that I use on a day-to-day basis (omitting a few details, like the headers used and such):

int main() {
  vect<double,3> v1,v2;
  cout << "Enter coordinates please.." << endl;
  cin >> v1 >> v2;
  cout << "the answer is " << norm(v2 - v1);
  return 0;
};

But the above requires knowledge of numerous techniques in C++, which you will learn in proper time. Basically, the above uses a custom class template (called vect) that I wrote, which represents any fixed-size vector with a full suite of overloaded operators, helper functions and template specializations. But these are a bit too advanced to explain here or now. Be patient.

But besides that, there are several stylistic improvements you can make to the code that make it look a lot cleaner, here are a few I can think of just now:
- Use consistent indentation.
- Leave curly braces on their own lines.
- Declare variables on site of first use, if possible.
- Don't abuse local variables when they are not necessary and don't contribute to clarity.
- Give sensible names to variables.

Implementing these changes, your code turns into:

void print_distance(int x1, int y1, int z1, int x2, int y2, int z2);

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

Your eyes will also get used to the C++ version with time. For instance, I find the C++ version you posted more appealing to the eye. And your fingers will also get used to it, believe me.

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

Well you could just put a bit more "style" into it:

std::cout << "ERROR " << event 
          << ": "     << (origin ? origin : "?") 
          << ": "     << fulltext 
          << std::endl;

It takes more lines of code, but it is worth it in terms of clarity.

If you have code like this that gets repetitive, like an error report that is basically always "event" "origin" "message", then just make a function for that:

inline void report_error(int event, const std::string& origin, const std::string& message) {
  std::cout << "ERROR " << event 
            << ": "     << (origin ? origin : "?") 
            << ": "     << message 
            << std::endl;
};

Or use a MACRO like this:

#define ERROR_REPORT(A,B,C) "ERROR " << A << ": " << (B ? B : "?") << ": " << C

//and use it as:
std::cout << ERROR_REPORT(event,origin,fulltext) << std::endl;

Or use exception messages as Fbody said.

Or, just use printf, if you prefer, there's nothing really wrong with that. You should always consider the C++ options first because they are often better, but wherever the C style works fine, it's ok too (as long as it is within a small piece of code that is well encapsulated).

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

"Time Complexities" is really just a measure of what running times you should expect as a function of the amount of data you are working on. It is not a precise measure (at least it rarely is), and can't really be "used". It's more like a measure of how good an algorithm is (often, compared to another algorithm or to how "difficult" the problem is).

For example, if I have an array that I want to fill with 0 values, then I would go through each element of the array and set it to 0. I don't really know how much time it takes to set one element to 0, but I know that it takes the same amount of time to set any one element or another to 0, in other words, the time for this operation is a constant, lets call it A. Then, since I will go through each of the N elements of the array, the time that it would take is A*N. But since I really don't know A (without doing performance tests on my computer), I just say that the operation is proportional to N, another way of saying it is that it is of the order of N, and hence, the big-O notation O(N).

The point is that this measures how scalable an algorithm is. Since any problem is trivial if N is really small (i.e. if you have 5 elements to sort, it doesn't matter much what algorithm you use, …

vmanes commented: Good explanation +7
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It is generally wasteful to compute the square using the pow function, just do g = d*d + e*e + f*f; (you generally try to avoid using pow for integer powers (2,3,4,...)).

Then, the sqrtf is a non-standard function from C (which is provided by most implementations of math.h). You should, instead, use the C++ version. For this, use the function h = sqrt(g); from #include <cmath> instead of #include <math.h> (notice the "c" in front and no ".h" after, this is pretty much true for all the C libraries, although the math.h works like many other C libraries do, the versions that are written as cmath or cstdio or cstdlib (instead of math.h, stdio.h and stdlib.h) are more compatible with C++ code, and it might avoid you the pain of some crazy-looking compilation errors).

For the rest, it seems pretty ok. You are, of course, missing the #include headers that should go at the very start of your code:

#include <iostream>  //for the cout and cin
#include <cmath>     //for sqrt()
using namespace std; //to avoid having to write std:: in front of cout, cin, sqrt, etc.
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Normally it is done as follows:

//in stack.h

#ifndef STACK_H
#define STACK_H

//include whatever you need.
#include <exception>

namespace my_code { //put your stuff in a namespace of your choosing.

struct stack_full_failure : public std::exception {
  const char* what() const throw() {
    return "Stack is full!";
  };
};

template <typename T>
class stack {
  //... your implementation of stack.

  void push(const T& NewElement) {
    if(numElements == stackSize)     //if the stack is full
      throw stack_full_failure;      //throw your exception.
    data[numElements++] = NewElement;//else, add the element to the stack.
  };
};

};

#endif

Whether the code is in the header file or in the cpp file doesn't really matter (I mean the "standard" guidelines still apply: don't put too much code in the header, don't break the clarity of the code, if stack is templated you pretty much have to put the code in the header, etc.).

The custom exception classes that you might want to define (like stack_full_failure in my example) are basically part of the interface of your class, so it makes sense that they would reside in the same header file.

Also, for a real library, it makes sense to document things well, for example with doxygen tags:

/**
 * This exception class is thrown when an operation that requires growing a 
 * stack's size cannot be performed because it exceeds the stack's maximum 
 * capacity.
 */
struct stack_full_failure : public std::exception {
  //...
};
/**
 * This class implements ...
 */
template <typename T>
class …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you are going to use a singleton, do it correctly. The code that L7Sqr posted has two big flaws: before calling instance(), the pointer "only_copy" is not necessarily NULL, and thus, the test (!only_copy) is likely to be false even on the first use of instance(); second, there will be a different copy of "only_copy" in each translation unit (that might not be a concern to you right now, but better learn the proper way soon rather than later).

The recommended way of implementing a singleton is as follows:

//in Timer.h
class Timer {
   int x;
   Timer () : x(0) {} // Private
   Timer(const Timer&); //make the Timer class non-copyable (such that another instance cannot be created)
   Timer& operator=(const Timer&); //make non-assignable for the same reason.
public:
   static Timer& instance (); //return the instance by reference.
   int getX () { return x; }
};

//in Timer.cpp

Timer& Timer::instance() {
  static Timer only_copy; //static-scoped instance (initialized only once).
  return only_copy;       //return by reference.
};

Later, you can use it as:

Timer& t = Timer::instance();
  int x = t.getX();

Putting the "only_copy" instance as a static variable in the cpp file, you guarantee uniqueness across translation units (and modules), and you guarantee that it will be initialized at least once and exactly once.

L7Sqr commented: Thank you for the corrections. +1