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

There is probably a way to make it work as a function within the function. However, this is really unusual and unnecessary. The proper solution, seconding NathanOliver on this, is to make the recursive function a private member function of your class.

Also, having those static local variables like that is a bit weird, too weird for my taste. In fact, it's a bug because if you call the same function more than once, then those static local variables will not be initialized again (will keep the values they had after all the recursions of the first call. Personally, I think you should just create a private nested class within your class to do the recursion. As so:

class RMatrix
{
    int sizeH;
    int sizeL;
    int TotalN, Replace;

    class RepMatrixCalculator {
      private:
        RMatrix* parent;
        int Row;
        int* RepIndex;
      public:
        RepMatrixCalculator(RMatrix* aParent, int MAX) : 
                            parent(aParent), 
                            Row(0),
                            RepIndex(new int[MAX]) { };
        ~RepMatrixCalculator() { delete[] RepIndex; };

        void RepMatrix(int NDR, int size, int PosIR, int calls);
    };

protected:
    bool ** Matrix;
    RMatrix(int, int);
    ~RMatrix(){for (int x = 0; x<sizeH; x++)delete [] Matrix[x]; delete [] Matrix;}
    void DisplayMx ();
    void RepMatrixf();
};


void RMatrix::RepMatrixCalculator::RepMatrix(int NDR, int size, int PosIR, int calls)
{

    if (calls==0)
        ;
        //memset(parent->Matrix, 0, sizeof(parent->Matrix));
        // NOTE: The above line of code is completely wrong.
        // NOTE2: Setting the matrix to zero probably something you could do in 
        //        the constructor of RepMatrixCalculator.
    for ( ; PosIR < size-(NDR-1); PosIR++)
    {                                       
        RepIndex[calls]=PosIR;                
        if (NDR==1)                             
        {
            for (int x = …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

CERN has just announced that they have detected a new particle consistent with the predicted Higgs boson (a.k.a. "The God Particle"). This is huge! CERN has observed the particle tied to the field that gives everything mass! And its mass is at 125.3 GeV (just shy of 5-sigma confidence).

This is a pretty huge day for physics, the culmination of 50 years of work to detect that elusive but extremely massive particle!

I just wanted to share this with you guys. Anybody else excited about this?

Here are some videos: Joe Incandela, Peter Higgs, and the actual announcement.

Reverend Jim commented: Heavy! +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

To me, the image that the word "hacker" invokes in my mind is that of a kid who has an irrepressible need to pick his home radio appart to understand every detail of it and tweak it, or to use the remote and receiver from an old TV to try and make his coffee-maker activated by the TV-remote. At least, that's the image it invokes for me, and that's probably the kind of things real hackers did when they were kids. Also, this kind of "hacking electronic gizmos" is the kind of activity the first people to be called "hackers" were doing.

The end goal is not really the main motivation for a hacker, but rather the sheer joy of picking a system appart and mastering it. For as long as there have been systems, there have been hackers picking them appart (which is usually illegal). Whether it is Frank Abagnale Jr. picking appart the bank's check systems to forge his own checks, or whether it is people who put bits of electronics on their phone line such that every call they receive looks, to the phone company, like the phone has been ringing for half-an-hour when they are really making a long-distance call (saving themselves the bill for it). Or, true story, a friend of mine who, as a kid, learned all about how to program a boot-loader on a computer, just so that he could put in a fake boot-loader, one which only printed a mean-looking error message, …

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

The problem is you test program, the following three lines:

Bitmaps A = Bitmaps("C:/Meh.bmp");
Bitmaps B(Bitmaps("C:/Meh.bmp"));
Bitmaps C = A;

The first line will call the constructor that takes a string (or char pointer). That is simply the syntax to call an explicit constructor. The second line does the same thing as the first. And the third line is one way to construct an object using the copy-constructor.

If you want to invoke the copy-assignment operator, you should do:

Bitmaps D;  // default-construct it (or construct it otherwise, doesn't matter).
D = A;      //  then, you do the assignment.

If you want to invoke the move-constructor, you should do either of these things:

Bitmaps E(std::move(A));   // the std::move marks A as "to-be-moved".
Bitmaps F = std::move(A);

If you want to invoke the move-assignment operator, you should do this:

Bitmaps G;
G = std::move(A);
// Or, you can also do:
G = Bitmaps("C:/Meh.bmp");  // assign a temporary (rvalue).

And, by the way, if you have a copy-and-swap assignment operator which passes the object by value (which is correct), then you don't need a separate move-assignment operator because the copy-and-swap will also act as a move-and-swap if the passed value-object is constructed from the move-constructor (instead of the copy-constructor used in the copy-and-swap).

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

That never occured to me that such a thing can be done. I have never seen such code before.

The non-copyable idiom is a classic technique in C++. It is not used as much as it should, but it is a nice technique, it is one of those nice and simple examples of how you can get the compiler to help you to write correct code (by forcing it to produce compilation errors when the code is not correct).

With that implementation, is it still safe to supply a move constructor?

Yes. The move constructor generally makes sense for this case. You might not really need it though, but it doesn't hurt to have one. If you want to get more or less the same behavior as move-semantics, but remain legal C++03 (previous standard), then you need to define a default constructor (null handle) and a swap function.

Towards the end of my tutorial on RAII in C++11, there is a non-copyable class example (a home-brewed array container).

Should I supply one or is it just not necessary?

It is not necessary, unless you need to move the object around, but it doesn't hurt to have it anyways (and you never know, you might want to have a container of such objects (like a thread-pool), which is possible even if the class only has move-semantics, with C++11 enabled STL containers).

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

The HANDLE is what one calls an "opaque pointer". This just means that it is essentially a pointer but you have no idea what it points to, and you're not supposed to know (it's "opaque").

If you library from which you got the opaque pointer does not have a method to copy (or duplicate) the resource that it points to, then you cannot copy it, and you shouldn't attempt to.

If you should copy something, then you must disable copying. This can be done in a number of ways, depending on what you've got to work with. The basic technique is to declare the copy-construct as a private member function and not provide a definition for it, so that any attempts to call the copy-constructor is going to result in a compilation error:

class Foo {
  private:
    Foo(const Foo&);  // private copy-con, no definition (declaration-only).
    Foo& operator=(const Foo&);  // private copy-assign, no definition either.
  public:
    //... the rest of the class.
};

Another possibility is to inherit from boost::noncopyable which is basically just a simple class like the Foo class above, that declares private copy-con and copy-assign. Finally, if you have a C++11 compiler (as I assume from your mentions of move-constructors), you can use the explicit deletion of the constructor, as follows:

class Foo {
  public:
    Foo(const Foo&) = delete;  // non-copyable
    Foo& operator=(const Foo&) = delete;  // non-copy-assignable
};

The effect is the same as with a private, undefined copy-con and copy-assign, but the …

triumphost commented: PERFECT! +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First of all, the scan() function should take the vector by reference, to avoid unnecessary copying. That is, as so:

bool scan( std::vector< unsigned char >& data );  // notice the '&' here.

If the memcpy "breaks" (would be useful to know what the error is!), it is most likely a problem of bounds. Did you use the resize() function before doing the memcpy, to make sure the vector has the needed size for the elements that you are copying into it. Also, when reading binary data from a file, you need to make sure the endianness is correct and that you use "fixed-size integer types". Types like short or int are not fixed in size (the size varies between platforms), you should use types in the header <stdint.h> which include types like int16_t or uint32_t, for 16-bit signed integers and 32-bit unsigned integers, respectively.

If I remember correctly, the 3ds file format has a "chunk-size" field, I hope that your file format has that too because it is very important. You should make sure to check that your mem-copies do not exceed the chunk-size, to make sure things are consistent all the time.

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

Yeah, you use a thing called "placeholders". In Boost, these are _1, _2, etc. The number represents which parameter is passed there, so you can even change the order if you want, and you can fix some parameters and leave others to be passed to the function when it is called. As so:

#include <boost/bind.hpp>
#include <iostream>

void func(int i, int j) {
  std::cout << i << " " << j << std::endl;
};

int main() {
  boost::function<void(int,int)> f;

  f = boost::bind(&func, _1, _2);
  f(42,69);

  f = boost::bind(&func, _2, _1);
  f(42,69);

  boost::function<void(int)> f2;

  f2 = boost::bind(&func, 0, _1);
  f2(42);

  f2 = boost::bind(&func, _1, 0);
  f2(42);

  return 0;
};

Read the Boost.Bind docs for more examples of what you can do.

DeanMSands3 commented: Nice! I need to look into that! +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First of all, welcome to Daniweb!

Second, your code is not remotely as horrible as you say it is (I've seen a lot worse). It is pretty good overall, with a few issues to solve.

Ok, so, on to the issues:

1)
You have a memory leak in the load function. The function allocates an array of unsigned chars for dumping the file content into, before scanning it. That array is never deallocated. The load function really should have the type bool as output (you even have a return false; statement), and there is no point in returning an unsigned char. Also, because you have two exit points (one from an error, returning false, and one from reaching the end without errors), you would need to delete the array at both of these points. That is annoying to do, it is much easier to use an STL container instead to store the array, this way, it will automatically be cleaned up when you exit the function (from whichever exit-point). So, this corrected version would make more sense:

bool sdObj::load(string const &filename)  // return 'bool'
{
    //unsigned char *funcObjData = NULL;
    vector< unsigned char > funcObjData;  // use a vector container instead of array.

    ifstream infile(filename.c_str(), ios::binary | ios::in);

    if(!infile.is_open())
        return false;     // this is a fail, right?

    infile.seekg(0, ios::end);
    filesize = (long)infile.tellg();
    infile.seekg(0, ios::beg);

    /*if(funcObjData != NULL)
    {
        delete[] funcObjData;
        funcObjData = NULL;
    }*/ // This check is not useful because funcObjData is local.
        // Your compiler should …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Code optimization and time-complexity are separate issues (at least, IMO).

Algorithmic complexity

Time-complexity just means to analyse what is the relationship between the size of the data and the amount of time it will take to perform a given operation (algorithm) on that data. Typically, N usually represents the size of the data, like the number of elements in an array, number of nodes in a graph, number of words in a dictionary, or number of entries in a database, and so on. Of course, sometimes there are more than one such number to represent the size of the data, in which case other letters are used. Basically, the Big O just represents the fact that we don't care about the actual time that it takes (e.g., how many seconds to perform the algorithm on 1000 elements), but rather only care about the biggest functional relationship between time and data-size. So, if you see O(1), which we call "constant-time", it really means that the time taken to perform the algorithm is the same (constant) regardless of the amount of data. If you see O(N), which we call "linear-time", it means that the time taken to perform the algorithm grows as linear function of the size of the data (i.e., twice the size equal twice the time). And so on, you'll see things like O(N^2) (quadratic-time) or O(N^3) for more complex algorithms. The reason why you won't see things like O(N^2 + N + 1) is because there is usually an …

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

And, you should make the base-class desctructor virtual, as so:

class Digitize
{
 protected:
    int * number;
    int Digits;
 public:
    Digitize(_uint64);
    virtual ~Digitize() {delete [] number;} // notice the 'virtual' here.
    void Display();
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you like the std::pair solution, then you should be aware of a neat little function called std::tie (also available in Boost, for pre-C++11, as boost::tie). This function basically constructs a pair (or generally, a tuple) of references to its given parameters. This allows for this type of code:

MemberRawArrayVector my_vect;
MemberRawArrayVector::iterator it, it_end;  // declare two iterators.
for(std::tie(it,it_end) = my_vect.range(); it != it_end; ++it) {
  /*  do whatever  */
};

This tie function is pretty useful for all sorts of schemes where you return a tuple (or pair) from a function (as opposed to the traditional solution of giving pass-by-reference parameters to store additional result-values of a function).

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

I think you need a little lesson in common practices and idiomatic C++ programming.

In the first class with vectors, it returns the member array and it is read only to prevent resizing. Thing is, I want to be able to modify the values in it without the SetMemberValue function.

First of all, in any case, you probably don't want to return a pointer (or reference) to the vector because that just exposes too much of the internals of your class. As for what you want to achieve, let me think, you want to be able to access all the elements in the vector, be able to modify them, but not be able to resize the vector. There is a well established practice to do exactly that, it is called "iterator ranges". Typically, you would do this:

class MemberRawArrayVector
{
    private:
        vector<unsigned char> MemberRawArray;
    public:
        typedef vector<unsigned char>::iterator iterator;
        typedef vector<unsigned char>::const_iterator const_iterator;

        MemberRawArrayVector(int Size) : MemberRawArray(Size) {}
        void SetMemberValue(char Value, int Index) { MemberRawArray[Index] = Value; }
        // either this:
        iterator begin() { return MemberRawArray.begin(); };
        const_iterator begin() const { return MemberRawArray.begin(); };
        iterator end() { return MemberRawArray.end(); };
        const_iterator end() const { return MemberRawArray.end(); };

        // or this (or both):
        std::pair< iterator, iterator > range() { 
            return std::make_pair(MemberRawArray.begin(), MemberRawArray.end()); 
        };
        std::pair< const_iterator, const_iterator > range() const { 
            return std::make_pair(MemberRawArray.begin(), MemberRawArray.end()); 
        };
};

Just about any functions that you might want to write that does anything with the elements in an array (or list, or …

triumphost commented: +1 Thinks way outside of the box! Excellent answer! +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Which is the best to use?

It really depends on the case. Explanation below.

If I use const T&, will it create temporaries every single time?

No. The whole point of it is that it won't create any temporaries. However, it will cause indirection, meaning that it is like a pointer (under-the-hood) and thus, everytime you access the value of the referee, there is an implicit dereferencing happening (fetching the value at the underlying pointer address. This is the core of the issue, with a reference parameter, you eliminate the overhead of the copying (replacing it with the often cheaper operation of taking a reference (address) and copying that address (underlying pointer)), but then you suffer the overhead of the indirection every time you access the referee's value.

So, we can first take care of the case for T&, because that's easy. If you need to modify the call-site object that is given as a parameter, then you must use T& (unless you go with T*, however, that is usually not recommended).

If you need a fresh copy of the object within your function (e.g., to do some temporary modifications to it), then you should use T (pass-by-value). This is because if you are going to make an internal copy of the object (internal to the function-body), you might as well do it as it is being passed into the function because it is going to help the compiler avoid unnecessary copies from the call-site.

If …

triumphost commented: I chose my function parameters based on this answer :) +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It depends what you mean by "share". If you just mean to "distribute" it, then that's just a matter of compiling your program in release mode (after being completely finished with it), packaging it in an installer, and distributing it (for free or for cash). If you mean sharing code with others (in the hopes that they will contribute to it), then you need to get them to sign an agreement (physically sign a paper, anything else is worthless) on the terms of their involvement, which can range from relinquishing all their copyrights to you, to giving you license to use their contributed code under specific clauses (e.g., it can be free of charge but closed source, or with a royalty, etc.). And, it goes without saying that if you are using code under a copyleft license (like GPL) then you don't have much choice, you must distribute your game as open-source, under the same license.

As for distribution (within an installer), then it is just a matter of picking one of the hundreds of sites that host freeware / shareware programs for download. Of course, you probably should first test that your program installs and works on many platforms (especially if in Windows). You can do that by asking friends or family that can give you access to a few different Windows computers with different versions and without any developer's libraries installed (like Visual Studio or whatever else), this is important to make sure you don't have dependencies. And …

claywin commented: Okay, thanks! That was a lot of helpful information; you answered my question and probably any future ones! +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Hi all!

This is a simple piece of code that I wrote about a year ago, in response to a question on Daniweb. I decided to infuse it with some C++11 magic, which led to a pretty sweet code snippet, full of neat little techniques you might want to use, not to mention that this class can actually be pretty handy to have. There are a few similar implementations out-there, but they all use a different approach, my main inspiration is the scope-guard technique.

This is an implementation of a simple wrapper class template that allows a variable to be externally made thread-safe via a mutex lock. This can be useful when a single variable (e.g. non-trivial object, like a std::string or std::vector) is of a class that has no built-in thread-safety, when thread-safety is required. The typical solution is to pair the object with an associated mutex and lock it during any thread-sensitive operations. For example, if the object is a std::vector, one could wrap all calls that rely on the underlying elements (like accessing them or insertions) with a mutex lock. Although this is typically the best solution in terms of fine-grained control over when threads can get blocked, it can be cumbersome to implement in general (at worst, creating a "completely thread-safe std::vector" would involve wrapping every member function in a mutex lock).

This simple wrapper superposes a scoped locking mechanism on top of an underlying object. This forces all the operations on the object to be …

Ancient Dragon commented: good work :) +14
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Don't panic, relax, all is well.

What that tutorial is refering to is the difference between value-initialization, default-initialization, and zero-initialization. These are a set of rules that the compiler follows to initialize objects in different "construction from nothing" cases.

Basically, value-initialization and zero-initialization are the same, they set everything to zero (unless there is a user-defined default constructor for that class). This will occur when you write:

Foo f = Foo();   // value-initialized local variable.
     // btw: Foo f();  is an error, it is a function declaration!

Foo* pf = new Foo();  // value-initialized dynamically-allocated object.

Bar() : member_var() { };  // value-initialized data member.

While default-initialization will call the default constructor of the class if one exists (user-defined or not), otherwise it doesn't do any initialization. This will occur when you write:

Foo f;   // default-initialized local variable.

Foo* pf = new Foo;  // default-initialized dynamically-allocated object.

Bar() { };  // member_var will be default-initialized.

The same initialization rules apply to all kinds of initialization, whether it is a local (static) variable, a dynamically-allocated one, or a class data member (or a base-class initialization). There are only some special rules for global variable (with externs and stuff), but you don't have to worry about that.

At the end of the day, class types always use the default constructor (user-defined or not). The only "weird" thing about this is that primitive types (int, float, etc.) can be initialized to zero without having to do int i …

triumphost commented: Thank you! I feel much safer now. Going to read the PDF. :) +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

What if I want to go from char* to BYTE*? I'd use reinterpret_cast right?

Yes and no at the same time. The reinterpret_cast is, generally, to be avoided because almost anything you do with it is "undefined behavior", except for this one case you pointed out. When casting pointers whose only common base is void* (i.e., the pointee types are completely unrelated), the expression reinterpret_cast<T*>(p) is required, by the standard, to be exactly equivalent to static_cast<T*>(static_cast<void*>(p)), which makes the reinterpret-cast just a shorter syntax for a double static-cast (cast up to a void-pointer and back down to a T-pointer). But, in almost all other cases, the C++ standard only requires that the reinterpret-cast be a reversible cast (and should only be used for that purpose), meaning that if you cast a A* pointer into a B* pointer and then cast it back to a A* pointer, then the A* pointer value should be the same. But, technically, the value of the intermediate B* pointer (the actual address it holds) is implementation-defined. In practice (not guaranteed by the standard, but often so in implementations), it will probably behave the same as one static-cast or as two static-cast (via a void-pointer, like in the case where the two types are completely unrelated), but there are cases where it might not (like cases where a static-cast would fail or be ambiguous, then, the output of the reinterpret-cast is really anybody's guess).

And, of course, when it comes to using reinterpret-cast for …

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

Your question makes very little sense to me. What do you mean by "trying to get mangling for variable .."?

Name mangling is not something that you should ever be able to see from within the code, because it is a feature used for linking (happens after compilation).

Name mangling in C++ is necessary because of features such as namespaces and function overloading. When you compile a piece of code in C++, the compiler must generate a symbol table of all the functions, types and global (extern) variables that can be found in that code. This is used later when the linker puts many pieces of compiled code (object files) together to produce the final binary (library or executable). In C, this is trivially done by using the actual names of functions and variables as the names of the corresponding entries in the symbol table (i.e., no name mangling in C). But, in C++, because functions, types, or variables with the same name can exist (either as different overloaded versions or in different namespaces), the compiler has to create new names which encode the identifier (name of function, or variable), the namespace (or other scope), and the parameter types (for function overloads). This is called name mangling, and it generates a weird-looking and unique name for functions. The only reason to be concerned with that is if you are trying to inter-operate between C++ code and C code (or others), in which case, you must disable name mangling with the …

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

I have never tried this, but I believe that you can use this Wake-On-LAN feature that most ethernet cards have (unless it is really old, or bad). You can follow these instructions (they are a bit old, but should still work). You can install the package wakeonlan on your remote computer (not server) to do this, I believe you can even turn on a powered-off computer remotely with this program (I think that sending the WOL packet is basically equivalent to hitting the power-button). Of course, this assumes a wired connection between your server and a router. It's a pretty low-level thing (send a UDP packet to a MAC address), so I'm pretty sure you can also wake-up the server from a Windows / Mac computer too.

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

if i m not wrong it means , i have to create a reverse link list and then read it , in order to read a link list in backward fashion

No. You understood AD and pyTony correctly (I think), that's what they suggested. But that is certainly not a good way to traverse a single linked-list in reverse, it's pretty much the worse thing you could do. And if you also have to modify the linked list while you are traversing it, then that solution becomes a nightmare.

There are a number of ways to traverse a single linked list in reverse (if you cannot use a double linked list). The actual technique you use depends on your requirements (mostly the size of the list, and your desired running time vs. memory usage trade-off). Here are the main options:

  1. You can do an in-place reversal of the list while you are going through it in forward direction, then follow those links to go through the list in the backward direction (and do whatever operation you wanted to do in the first place), and at the same time, you do another in-place reversal of the list to bring the linkages back to the original. The advantage of this is that it uses no additional memory, the disadvantages are the double traversal (forward and back), the overhead of the in-place reversals, and temporary re-linking of the list (which you may not want to do).

  2. You can create an array …

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

Thank you for your kind words! This is really what DW is all about, a cycle of helping, teaching, learning, personal growth and (virtual) friendships.

Cheers!

mrnutty commented: Thanks a lot mike. You are one nice person. Hope you realize how much impact you have to this community and to each individual person in this community, whether they have realized it or not. +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First of all, if the idea of the Parser function is to fill the vector of words contained in Lexical, then I see no point in returning that vector of words from the function.

As for the overloading problem, I would recommend just going with the std::istream idea. The standard way to extract any kind of non-trivial information from a std::string is to put it in a std::stringstream anyways (which is convertible to std::istream&, so you might as well have the user of your Lexical class do so at the call site. And, while you are dealing with the std::istream class, you might as well use the >> operator instead of a function call. So, for a simple "extract space-separated words" Lexical analyzer, you could do this:

class Lexical
{
    public:
        Lexical();

        friend
        istream& operator >>(istream& in, Lexical& lex);

        friend
        ostream& operator <<(ostream& out, const Lexical& lex);

    protected:
        vector<string> words;
};

istream& operator >>(istream& in, Lexical& lex) {
    string s;
    getline(in, s, '\n');
    stringstream ss(s);
    while( ss >> s )
        lex.words.push_back(s);
    return in;
};

ostream& operator <<(ostream& out, const Lexical& lex) {
    for(unsigned int i = 0; i < lex.words.size(); ++i)
        out << lex.words[i] << " ";
    return out;
};

int main() {
    ifstream file_in("my_file.txt");
    Lexical lex1;
    file_in >> lex1;    // input the words into the Lexical object.
    cout << "File words are: " << lex1 << endl;  // output the words.

    Lexical lex2;
    cout << "Please enter a sentence: ";
    cin >> lex2;      // input the words from …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Since Schol-R-LEA listed the options, I might as well complete the thought with the remark that using-statements like using namespace std; or using std::cout; can also appear within function bodies, and, in fact, that is the preferred option of "professional" programmers. So, the order of preference (from preferred to to-be-avoided) is this:

  1. Prefer using only individual using-clauses (like using std::cout;) in the function bodies; or else,
  2. Use only individual using-clauses in the global or namespace scope within your cpp files; or else,
  3. Use a namespace using-clause in the cpp files; but,
  4. Never put a using-clause in a header file (1).

(1): Except for the specific purpose of transfering a class or function from one namespace to another (this is a common trick in library-code).

Also, another small correction:

You see, the majority of objects and classes in the standard library are in the std namespace

Not the majority... ALL standard classes, objects and functions are in the std namespace (and std::tr1, and std::tr2 to come), even those from C standard libraries (like cmath or cstdlib). Some compilers put C functions in the global namespace, but that is not a standard feature (the standard mandates that they be in the std namespace, but allows the compiler-vendors to put them in global namespace also, but some don't, like MSVC). Worse yet, sometimes the global-namespace version of C libraries are not C++ friendly (e.g., no overloading of abs() for type double), and those who are unaware of this issue could …

Schol-R-LEA commented: Excellent points +7
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I can use the capture_man object and all of its functions

Very often, just calling a member function of an object doesn't actually require the object to be valid or even existing at all, it is only when you access the data members (either within the member function, or from the outside) that you'll get a seg-fault if the object is not valid (e.g., the pointer is NULL). Technically, you can do this without an error:

struct Greeting {
  void say_hello() const {
    std::cout << "Hello!" << std::endl;
  };  // notice how there is no access of a data member (via the 'this' pointer).
};

int main() {
  Greeting* p = NULL;
  p->say_hello();
  return 0;
};

So, being able to call member functions successfully isn't enough information to say that the object actually exists, because a seg-fault would only occur when you try to access a data member.

but whenever I try to access ringinf I get a segmentation fault

Case in point.

Anything obvious that I am doing wrong. ??

Well, the devil is in the details, there aren't enough to know for sure. Where do you actually create the capture_man object (the pointee)? From where and when do you try to access it? Could you have fallen prey to the static initialization fiasco? This would be my guess.

The kind of thing you are writing, where you have a class with a unique instance of that class accessible …

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

If you are using VS, then you can put this line at the very top of your source file:

#pragma comment(lib, "wsock32.lib")

Another option is to go into your project options menu and add the "wsock32.lib" to the list of external libraries to link to (amongst the list of all other external libraries, you'll see names like "kernel32.lib", "user32.lib", "gdi32.lib", etc., you just need to add "wsock32.lib" to that list).

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

In the future, you should restrict one thread to one question. The discussion becomes difficult to have and to read when there are three separate issues in parallel.

They are the exact same syntax, it works for all my classes, why does it not work for literal types? I've coded them all the exact same so are Literals special when overloading?

Literals are not special when overloading, except that you might not be aware of their original type. A string literal, as in "hello world" has the type const char[]. In order to send it to a function that takes a parameter of type const std::string&, it must first be implicitely converted into a std::string and then bound to the const-reference parameter. If the expected type is const StringArray&, whatever that is, the process is the same (implicit conversion + const-ref binding). To the compiler, if both paths are possible, they are equally good, and thus, it cannot make a decision and tells you instead that the overload is ambiguous.

In your other example, you probably never encountered that issue because there was always a clear favorite choice. In a nutshell, the compiler basically chooses the most direct path (i.e., prefers no conversion at all, or just a reference binding, and will want to avoid multiple conversions), and when there's no clear winner, it forfeits with an "ambiguous overload" error.

So, the error is in the implicit conversions that you allow from a string literal to a StringArray

triumphost commented: Excellent Solution. +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Typo?

template<typename T>
CustomType<T>& CustomType<T>::Delete(CustomType<T> ValuesToDelete) // notice the <T> here.
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

struct Inner //Named struct

That's not a named struct, that's a nested struct type declaration. As in:

// this declares a struct type called Foo:
struct Foo {
  //.. 
};

// this declares a variable called 'foo' of an unnamed type:
struct {
  //..
} foo;

// this declares both a struct-type called Bar and an object 'bar' of that type:
struct Bar {
  //..
} bar;

Inside a union declaration, it is the same logic. In your example, you have declared a struct-type, nested in the union declaration, accessible as the type RGB::Inner. The point is that it is a type declaration, not a data member of the union. The thing that C++ does not allow is this:

struct {
  //..
};

Because it is neither a class declaration or an object declaration (of unnamed class). Some extensions (in gcc, for example) allow the above within a another class/struct or union declaration, and it is treated as the declaration of an anonymous object of an unnamed class/struct.

The legal way to declare your RGB union is as follows:

typedef union RGB
{
    uint32 Color;
    struct
    {
        unsigned char B, G, R, A;
    } Channels;
} *PRGB;

Now, when you initialize an object as RGB P = {16777215}, it will also fill the channel values, accessible through P.Channels.R, P.Channels.G, P.Channels.B, P.Channels.A. So, that's what I meant when I said that it is only syntactic sugar to have an anonymous struct in your …

triumphost commented: :o Thank you lots! Time to go learn why it pads. +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The undefined reference means that none of your functions actually have an implementation for them. And as per the issue that I explained (the two choices of where to put your function implementations), if you follow that, it should work. As I said, with the code you posted before, none of your public functions have a corresponding implementation, and thus, all the undefined reference errors.

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

Whenever an object is const, it means that it cannot be modified. Like in the main() function, the object cdi is const and cannot be changed. Now, the problem is that if you call a member function (like at()) on that object, how can the compiler make sure that the object is not modified within that function? It needs to know that the function that was called in particular will not modify the object. The way to tell that to the compiler and to enforce that immutability within the function is to append the const keyword at the end of the function declaration:

class DirectionSequence {
  //...
    int size() const;  // notice the 'const' here, 
                       // it means this function will modify the object.
  //..
};

You can do the same with the at() function, and it will fix the particular problem that you reported. However, you have plenty more problems to worry about.

I think you didn't quite understand the idea behind the public/private access rights. You declared a bunch of member functions in the public interface of the class, and then you implemented these functions in the private part. That's not what public/private means in this context. The access right specifiers (public, private, and protected) only pertain to how outside code (outside as in, code that is not part of your class' code) can access or use your class. Functions and members that are public are accessible directly from anywhere (any part of the code). Functions …

Psyho commented: full-on, understandable explenation +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Most of your questions will find their answers in my tutorial on the subject. The tutorial involves C++0x / C++11 features (which is the new standard, not yet well-supported by compilers), you can just ignore those features.

The only problem I can possibly see with my bitmap class is the GetPixels function which returns my internal pointer and that if the returned pointer is deleted, it can mess up my class when the constructor is called. Is a copy constructor going to fix this?

No. Nothing will, for that specific issue. First of all, it must take a complete idiot programmer to go and delete a pointer that was delivered from an object (as in your bitmap class). The general idea is to avoid exposing an internal pointer like that. However, in situations like these (image class), it is often necessary to do so (unless you're a really clever programmer). The general understanding in this case is that anytime a pointer is delivered from an object (via a get-function), then that pointer is only valid for as long as the object is not changed in any way (via a mutator member function, that is, a non-const member function), and, obviously, nobody should call delete on that pointer. This is a pretty universal thing.

Why do I need both the copy constructor and the assignment operator?

Because they do different things. The copy-constructor creates an object by duplicating the content of another. The copy-assignment operator …

Lucaci Andrew commented: Indeed, a very complete tutorial. +3
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Why does this say shaddowing?

Because your data members have the same name as your parameters. Whenever this happens, the compiler will always assume that when you refer to that variable name, you mean the variable with the most local scope, in this case, it would be the function parameters. You should never use the same names for the parameters and data members. My trick is to simply add an "a" in front of the parameter names (some people also use a trailing underscore). As so:

Point::Point(int aX, int aY) : X(aX), Y(aY) {}
// or:
Point::Point(int X_, int Y_) : X(X_), Y(Y_) {}

The compiler says it "shaddows" the data members because when you use those names, it won't refer to the data members, i.e., the parameters hide the data members.

Also why should I include <complex> to use std::abs instead of including math.h and using fabs?

Because "math.h" is not a standard C++ header. You should always use <cmath>. As for the absolute function(s), the C++ standard cmath header contains all the same functions as the C standard "math.h" header, but they are in the std namespace. And thanks to C++ overloading, the fabs and abs functions are the same (as opposed to C, in which fabs is for floats and abs is for integers). You can use either one of the absolute-value functions std::fabs or std::abs, they are the same (and overloaded for all types).

triumphost commented: Did not know about CMath :D Thank you +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It is probably a simply typo. The string conversion produces a .NET string of type System::String^, not a C++ string of type std::string. If you use the lower-case name string, my guess is that it refers to std::string, which is not the same as System::String^. This should work:

System::String^ makebreak1 = makebreak.ToString();

If you want a C++ string, then you will have to marshal the .NET String.

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

I'll just say that in the code given in your last post, you certainly don't need to allocate the Configuration object on the heap. In general, there is almost no reason to ever dynamically allocate a single object within a function just to use it in that function (use a local object instead). And by the way, a little correction on Schol-R-LEA, the more formal term for dynamic memory or heap-based memory is the term "freestore", the other two terms are colloquial terms.

When it comes down to it, there are really only three main reasons to use dynamic allocation of memory:

  1. If you have to store a number of objects (e.g., array) for which the size (or number of objects) is unknown at compile-time, e.g., a dynamic array (or other dynamically-sized data structures, like strings, trees or lists).
  2. When using polymorphic objects which often have to be heap-based (mostly due to how they are produced and then owned).
  3. When you have objects that are meant to be shared amongst different parts of the code, and the life-time of those objects can vary depending on where they are still in use (e.g., there is no single and obvious owner for it).

And, in modern C++ programming, none of these cases involve using the new/delete mechanism directly, nor (raw-)pointers for that matter. And for those reasons, delete is a very rarely used keyword in day-to-day C++ programming, but it is important to understand it (new can also be almost entirely …

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

Very often, if a function call is ambiguous to the compiler, it is also ambiguous to the programmer. In your code, there are two functions that do two very different things, the first returns the absolute value of a, and the second makes the given variable positive. Why are these functions called the same? To me, this is ambiguous and weird, and I wouldn't accept it in any reasonable interface. Don't abuse overloading in this way.

As for actually fixing it, well, the answer is that you need to explicitely cast the function in order to tell the compiler what overload it should look for. If you are not familiar with function-pointers, this will look alien to you, but, otherwise, here is the solution:

int main() {
    int a = -1;
    (( int (*)(int) ) absolute) (a);
    // or: 
    (( int (*)(int&) ) absolute) (a);
    return a;
}

Now, you might also observe why it is easier to just give them different names. Only use overloading when the function parameters are different enough that there is very little chance of ambiguity.

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

He's basically right. But I don't like his or your terminology.

A pointer stores a memory address. When you use the new operator, you allocate a chunk of memory (either for a single object or for an array of objects) and it returns the address of the allocated memory, which you would store in a pointer. When you are done using that memory, you must deallocate it, which you do by calling delete on that address (pointer). So, only and all memory that was allocated with new must be deallocated with delete.

So, if you get a pointer by getting the address of an existing object, as in, param_vector = &pParams.files;, then you should not use delete on that pointer, ever. Doing so will either cause a crash or a heap-corruption (which will go silent at first, but could quite bad later).

BTW, there is a bug in your code (beside the delete statement), you need brackets for your last else-case:

else {
    cout << "Invalid configuration paramter " << name << endl;
    bad_param_name = true;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Hey is that (void) needed? I removed the void and it still worked

Can you post that code. I'm not sure what you mean, where you removed the void* cast. If you only remove the cast to a void* type, it should still work because all pointers are implicitly convertible to a void* pointer (this is a relic of C). But you will still need the cast from void* to std::function<void()>*. Also, you should get used to using the C++ cast operators instead of the C-style casts. In other words, you should use:

std::function<void()> func = *static_cast<std::function<void()>*>(lpParameter);

I have problems doing that with Class Functions since I don't have the grasp of it yet.

To use bind with class member functions, you have to provide the pointer to the member function, and the object on which to call it. As so:

Debug X;
std::function<void()> F = std::bind(&Debug::DebugWindow, &X, "one", "two", 100, 100);

This the same mechanism as for boost::bind, see here.

triumphost commented: :D I'm quite happy today +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It's a simple typo. Line 14 should be:

Test((void*)F);  // notice no & here.

Because when you do &F, the type of that expression will be std::function<void()>**, and then, later you cast that into the type std::function<void()>*, and thus, the crash (or undefined behavior).

triumphost commented: Very good eye lol didn't notice that +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Uh what could happen if it's not initalized and I do assume?

Anything can happen, it is undefined behavior. The more likely outcomes are that nothing happens (and your flag setup is inaffective), or that your program crashes before it even starts executing the main() function.

Whether cout will be initialized at the point where you set the flags depends on the compiler, the platform and the order in which the linker decides to arrange things. Quite unpredictable.

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

First, why does this not cause a stack overflow?

If you call a function in an infinite loop, you will not get a stack overflow. The stack is, well, a stack. Things get pilled on and pulled off. You enter a function, it uses some space on the stack for its variables, and when you leave the function, that space is released. So, repeatedly calling a function only causes spaces to be allocated and deallocated repeatidly on the stack, there is no net growth during the iterations.

Will both of them result in the same stack overflow? Will they BOTH overflow at all?

Your recursion calls will not result in stack overflow because their stack frames have a size of 0. You don't have any local variables, parameters, or return values. There is no reason to take up any space on the stack for that function (unless there are debugger-related things). So, you allocate 0 space on the stack an infinite amount of time, what is infinity * 0? Answer: 0.

Both never seem to return to me so the Bleh recursion should overflow exactly like Meh's?

Yeah, there is no difference from a stack-overflow perspective between direct and indirect recursions. The only thing that matters is the size of the stack frames required at each recursion, and if those recursions cause a growth of the stack usage (it is possible to have a non-zero stack frame, and yet have no stack growth, this …

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

The subject of the snippet is of your choosing, the programming language is of your choosing.
The only question for the contest is: Are you up for it?

TrustyTony commented: ;) +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

"In computer programming, clever and simple are synonyms." - your humble moderator

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

The library should be part of "glibc" package, which is a fundamental system package, I doubt that you lack it.

To find the ld-linux.so.2 try to run this command:

$ locate ld-linux

It is possible that the file in question appears in the wrong directory, like /lib64 or something. You can then make a symlink to that file in the /lib folder.

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

The way I see it, every programmer has a bag of tricks that they use. To me, the point of the contest is to show off one such trick that you think is clever and/or useful. It can be a nice language-technical trick (e.g., doing something that people don't suspect can be done), a nice algorithmic trick (e.g., a clever tail-recursion, or something), or a very useful little tool (e.g., a kind of smart-pointer). When you program a library or large application, most of the code is boringly ordinary, but once in a while you come up with a very neat solution to a particular problem / application. The idea is to take one such trick (or come up with one) and formulate it in a self-contained snippet (like the class that implements the solution, and a basic program that demonstrates it use / purpose). Then, it will be part of the code-snippet library, and people that read it might think its just cool or a very nice way to solve a type of problem.

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

The two rational numbers, r1 and r2, should be declared outside of the loop if you want them to keep on storing the last values entered (just like you used to have those ratNum1, ratNum2.. variables before). So, if you move the declaration, Rational r1, r2; to where the "option" variable is declared, all should work fine.

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

You can assume, for all practical matter, that the std::vector class just stores two fields: the size of the array and a pointer to the first element of the array. In other words, this is the same as what you would have to do if you allocated the dynamic array yourself with new[]. When you have a fresh vector (empty), the internal pointer is most likely set to NULL. You can also assume that the iterator type std::vector<int>::iterator is the same as int* (e.g., a pointer). So, when you call begin(), it will, in effect, just give you the pointer to the start of the array (the pointer that the vector stores internally). So, on a fresh and empty vector, that pointer is NULL (and so will be the iterator at begin()), and dereferencing it is going to cause a crash (access violation, segmentation fault). This explains the crash if you have both lines 21 and 23 commented out.

If you have resized the vector, then the internal pointer is no-longer NULL, which explains the non-crash behavior when using line 21 or 23. If you allocate space for 1 value, but end up writing 3 elements (via an iterator), you will be writing beyond the memory that was allocated (or allowed), this may or may not result in a crash, but in either case, it is bad. The reason why you get (1,0,0) after you resize the vector is because resizing from 1 to 3 adds two elements which are …

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

Hi,

I've been experiencing a weird bug in the editor (for a week or so). If I write a post, everything is fine and dandy until I start a block of code. From the first line of code that I write, and for every subsequent line of code after that, the cursor (the blinking line) gets offset by one pixel upwards. By the time I've written like 10-20 lines of code, the blinking line sits a full line above the place where I'm writing. The behavior continues after the code block is done (when writing normal text again), but the offset stops getting worse. The same offset applies to selecting some text that appears after the code.

This is quite annoying. I can always write the longer posts from a text-editor on the side and copy-paste the text back again, but I shouldn't have to do that.

Also, the blocks of code no longer appear in fixed-width font (when highlighted in the editor) like it used to. Writing code without a fixed-width font is very annoying.

FYI, I'm using Google Chrome, running under Linux (Kubuntu 11.10).

Anyone else experiencing the same problem? Dani, any ideas what the problem is? Solution?

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

I find that Python is a really nice language to learn in addition to C++, because it is very different (very high-level), easy, and it works very well along-side C++ (Python is often used as a high-level scripting language to use to run C++ code, through python-bindings).

I read everywhere that programmers should know several languages, but tell me, aren't you confusing them all the time when coding once in one language, and then in another ?

I happen to speak four languages at functional to fluent level (English, French, Swedish and German), and I have basics skills in a few others (Spanish, Italian, Finnish, and Dutch). I usually don't confuse them when I speak or write. But, for example, when I go to Sweden, it takes me a week or two to get used to speaking Swedish on a daily basis (which I don't use here, in Canada), in that time, my skills and knowledge of the language move from latent (passive) to active. Also, knowing many languages gives rise to a few quirks, like using words from one language when speaking another, or being frustrated once in a while to not be able to express something in one language as well as you could in another (e.g., I always swear in canadian-french, because it expresses it better). Then, there are subtle influences, for example, because french is my native language, when speaking english I tend to use more words and expression of french ethymology, and my …

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

Sorry about the "r" thing, it's a typo, it should be "rat" (i.e., the function parameter!). As in:

//output operator, to print a Rational number:
ostream& operator << (ostream& out, const Rational& rat) {
  out << rat.getNumerator();
  if(rat.getDenominator() != 1) // print denominator only if it is not 1.
    out << "/" << rat.getDenominator();
  return out; // don't forget to return the ostream object.
};
//input operator, to input a Rational number from a stream:
istream& operator >> (istream& in, Rational& rat) { // notice the & here.
  int num = 0, den = 1;
  in >> num;
  if(in.peek() == '/') { //check if there is a denominator.
    char temp;
    in >> temp >> den; // read the denominator.
  };
  rat.setNumerator(num);
  rat.setDenominator(den);
  return in; // don't forget to return the istream object.
};
alsz commented: Hey Mike, No need to apologize man, I should have figured it out myself. I really appreciate the help and thank you so much for all the help and hints. Have an awesome day!! Sincerely, alsz +0