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

That's odd.

I can explain the "posts voted down" section showing only 3 posts. This is because this section only shows the posts that are currently negative overall. This means that all those down-votes were counter-balanced by the up-votes on the same post.

But the overnight down-votes is very weird. And being that you only have a total of 2 down-voters, it would seem like someone has a grudge against you. Knowing who is beyond my "powers" as a moderator.

In any case, this is not the end of the world, but if it keeps on going, we'll have to look into it.

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

Each digit stands for a power of 2, just like decimal digits stand for a power of 10. For example, if you have a decimal number:

5498
5          4          9          8
5 * 10^3 + 4 * 10^2 + 9 * 10^1 + 8 * 10^0
5 * 1000 + 4 * 100  + 9 * 10   + 8 * 1
5000     + 400      + 90       + 8
5498

For binary numbers, it is the same thing (except you only have two digits (0,1) and the base is 2 instead of 10):

1101
1         1         0         1
1 * 2^3 + 1 * 2^2 + 0 * 2^1 + 1 * 2^0
1 * 8   + 1 * 4   + 0 * 2   + 1 * 1
8       + 4       + 0       + 1
13

As far as doing the conversion between binary and decimal numbers, there are a number of "mental" tricks to do it, or you can just do it on the calculator (Windows calculator or whatever). For example, with the number 13, that is easy to convert mentally, you just start with the highest power of 2 that fits within the number. For 13, the highest power of 2 that fits in it is 8. Then you subtract them, giving you 13 - 8 = 5. And you repeat the process, noting down a 1 for each power of two that can fit, and 0 for each that does not, until you reach …

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

If I have a number like 13, its binary representation is 1101 (i.e., 13 = 8 + 4 + 1 = 1 * 2^3 + 1 * 2^2 + 0 * 2^1 + 1 * 2^0). If I do a bitshift of the number to the left by one bit, i.e., 13 << 1, it simply means that I shift all the bits by one position to the left (filling the new bits with zero), giving me 11010 which is 16 + 8 + 2 = 26. And as you can see, this has the effect of multiplying the number by 2. If I do a bitshift of the number to the right by one bit, i.e., 13 >> 1, it simply means that I shift all the bits by one position to the right (discarding any bits that fall off), giving me 110 which is 4 + 2 = 6. And again, the effect is the same as an integer division by 2 (which discards the remainder). Shifting by more bits just means a higher power of 2 (multiplication or division). In other words, this is just a quick and efficient way to multiply / divide a number by powers of 2. Or, it can be used to do other bit-wise manipulations (usually for low-level purposes).

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

The reality is that there are limits to what you can achieve using the combination of implicit conversion operator and the assignment operator. You will not be able to make the "property" look like the actual value (i.e., make a property variable look like a normal variable but have hidden calls to get/set functions).

The main problem is that you can't overload everything, and you can't rely on the implicit conversion to apply everywhere. For example, if you were to have property<PropTest,std::string,READ_WRITE> Name;, then you'd have the following issues:

void Foo(std::string s);

void Bar(std::string& s);

template <typename Something>
void Bla(Something s);

void Bla(std::string s);


int main() {
  PropTest a;

  Foo(a.Name);  // OK, uses implicit conversion.

  Bar(a.Name);  // ERROR, implicit conversion returns a temporary string, which cannot be bound to a non-const reference.

  Bla(a.Name);  // UGH... this will call the template version, not the string version.

  std::cout << a.Name;  // ERROR, will look for a << operator for the property class.

  getline(std::cin, a.Name);  // ERROR, same as Bar().

  a.Name.length();  // ERROR, property does not have a member function named "length".

  // ....

};

The point is, the implicit conversion operator can only really work in a few "easy" situations. You will still need a "get()" function of some kind, very often.

Another important matter is the matter of references. Currently, your property class causes a lot of copying (much of which might be elided, but not all), and if the value-types of your properties are expensive to copy, this …

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

Your decoding can be fixed by flipping the subtraction at line 50, getting this:

input[count] = 'z' - ('a' - input[count]) + 1;

As for capital letters, that's not any different than for small letters. You just have to check before whether the letter is a capital letter or not. The "isalpha" function already checks if it is a letter (small or big), you can just replace that with a test for small letter and a test for big letter:

        if((input[count] >= 'a') && (input[count] <= 'z'))
        {
            input[count]+= 4;
            if (input[count] > 'z')
            {
                input[count] = 'a' + ( input[count] - 'z') -1;
            }
        } 
        else if((input[count] >= 'A') && (input[count] <= 'Z'))
        {
          // same strategy as above, but with 'A' and 'Z'.
        };
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

There are a number of bugs in your code. Much of which you could easily figure out by simply adding a print out in the midst of the encoding/decoding loops and examine what happens when you try it.

First, at line 51, you have input[count] == 'z'; where it should obviously be input[count] = 'z';, notice the single equal sign.

Then, you seem to have used + instead of - everywhere, and vice versa. That is, at line 52, you should have input[count]--;. Then, at line 26, you should have input[count] += 4;. And finally, at line 29, you should have input[count] = 'a' + (input[count] - 'z') - 1;.

It seems quite obvious to me that the encoding method (lines 12 to 33) is much nicer than the decoding method.

And if you have further issues, just test it and observe the result, that's the best way to wield out a bug or a problem. So, to recap, the encoding method should probably look like this:

if (choice == 2)
{
    cin.ignore(10000,'\n');
    cout << "enter the phrase to be encoded: \n";
    getline(cin, input);
    for(int count = 0; count < input.length(); count++)
    {
        if (isalpha(input[count]))
        {
            input[count] += 4;
            if (input[count] > 'z')
            {
                input[count] = 'a' + (input[count] - 'z') - 1;
            }
        }

        // For debugging purposes:
        cout << "After encoding letter " << count << ", got this: " << input << endl;

    }
}

and similarly for the decoding, by flipping everything around (plus …

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

The most "powerful" top to bottom combination of languages for desktop / server applications seems to be C / C++ / Python. That's my two cents.

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

It sounds like some sort of phishing scam. When I google for those numbers, I get hits of all kinds, mostly saying that each of these numbers are tech-support numbers for microsoft / MSN / hotmail, facebook, norton, and just about any other prominent IT company.

My guess is that you call there, for tech-support, and they get you to give them your credentials (username / password). And the rest is obvious.

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

US wouldn't be wormongeres if all the little piss-ant sized nations like Syria would cut all that crap out. Actually, seems to me I recall this all being started by Syrian people themselves.

As Rep. Alan Grayson would put it:

"I don't know where we got this odd notion that every time we see something bad happen in the world, we should bomb it."

If you think Syria is a piss-ant sized nation, then why should we even bother to do anything. You cannot imply, in the same sentence, that every small country in the world should behave according to your wishes, and at the same time imply that it's their fault that you have to police them. You can't have the cake and eat it too.

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

Easier said than done. How do you plan to get through his army in order to arrest him??

It would certainly seem easier than full out war. Just saying.

<M/> commented: Exactly! +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

cygwin is a bash environment for Windows. This means that you have to navigate it like you navigate a bash terminal environment (i.e., Linux/Unix). Here is some introductory material on that.

To access the hard drives like C:, D:, etc.. in cygwin, you have to go to the directories /cygdrive/c, /cygdrive/d, etc... As so:

$ cd /cygdrive/c

Once you navigate to the directory in which you have your C++ source file(s), you can compile it like this:

$ gcc -Wall my_source.cpp -o my_program.exe

where "my_source.cpp" is the source file, and "my_program.exe" is the executable's name as you want the compiler to generate it (i.e., the -o is for "output" option). The command literally means, "compile with all warnings the source file 'my_source.cpp' and produce as output the executable 'my_program.exe'".

You can also check out this instruction video.

NathanOliver commented: Always Informative +11
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

All
Goblins
In
Texas
Are
Totally
Enraged

Obviously, I agree with Jim too.

Competition

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

Deliberate
Environmental,
Industrial, and
National
Sabotage with
Testomonies from
Intellectual
Twits
Utilizing
Their
Investigations
Onboard the
Navy and
Army's
Legislative
Institutions in
Saudi
Arabia to
Tout
Inhumane
Organizational
Nationalism.

Let's get back to sanity:
Software

Ketsuekiame commented: For this sir, you can have a medal :D +0
Reverend Jim commented: I bow to the master. +0
<M/> commented: here's a trophy... +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Youth
Organization for
Unconstructive
Time
Usurpation and
Banal
Entertainment.

Next one:

Twitter

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

First thing's first, did you notice the update on the instruction website:

quote:

Update 2: the installer now requires you accept the Oracle license before the installation begins. This is only required once. If for some reason you need the installation to be automated, you can run the following command to automatically accept the Oracle license:

$ sudo echo oracle-java7-installer shared/accepted-oracle-license-v1-1 select true | sudo /usr/bin/debconf-set-selections

end quote.

The easiest is, by far, to simply install openjdk-7 instead of the Oracle version. So, the first thing is to make sure that you absolutely need oracle-java and cannot live with openjdk instead. The two are just two different implementations of the same library (one open-source, the other not).

It is very possible that the installation succeeded, but failed to create the final links such that you can actually run java command.

The first thing to try is running this command:

$ locate javac

which might output a whole bunch of stuff (depending on if you installed openjdk before or not), and somewhere in that stuff, you should find something related to oracle-java. For example, I have the previous version (6) installed (from some time back), which was from Sun (old name), and this is part of what I find in the output of the locate command:

/usr/bin/javac
/usr/lib/jvm/java-1.5.0-gcj-4.6/bin/javac
/usr/lib/jvm/java-1.5.0-gcj-4.6/man/man1/javac.1
/usr/lib/jvm/java-1.5.0-gcj-4.7-amd64/bin/javac
/usr/lib/jvm/java-1.5.0-gcj-4.7-amd64/man/man1/javac.1
/usr/lib/jvm/java-6-openjdk-amd64/bin/javac
/usr/lib/jvm/java-6-openjdk-amd64/man/ja_JP.eucJP/man1/javac.1.gz
/usr/lib/jvm/java-6-openjdk-amd64/man/man1/javac.1.gz
/usr/lib/jvm/java-6-sun-1.6.0.26/bin/javac
/usr/lib/jvm/java-6-sun-1.6.0.26/man/ja/man1/javac.1.gz
/usr/lib/jvm/java-6-sun-1.6.0.26/man/man1/javac.1.gz
/usr/lib/jvm/java-7-openjdk-amd64/bin/javac
/usr/lib/jvm/java-7-openjdk-amd64/man/ja_JP.UTF-8/man1/javac.1.gz
/usr/lib/jvm/java-7-openjdk-amd64/man/man1/javac.1.gz

As you can see, there are a number of java installs on my computer, including gcj4.6, gcj4.7, openjdk-6, …

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

Maybe you should try the follow the official instructions first.

Stuugie commented: Thanks for this, I really appreciate it! +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

What I'm mainly curious about is how the things you listed above that generate C code have that compiled?

They would generally rely on the system's C compiler (if there is one). For instance, matlab's real-time workshop (RTW) just generates a bunch of C source files and a bunch of makefiles (and I think some TCL scripts), and then it just "makes" that project, which automatically detects whatever C compiler is installed on the system and uses that.

This is pretty much the same as what you would do to create any library. You need build scripts that are capable of detecting the installed compiler (and dependencies) and use that to compile all the source. You just do exactly the same, but for your generated code.

I have been looking into this, is that something I should be using for compiling C?

I don't see the point. If someone is going to install your special "New Language" compiler, wouldn't he be able to install any of the standard C compilers (GCC, Clang, MSVC, etc.)? In fact, he most probably would already have it installed.

Another possibility is to distribute your compiler as an add-on to GCC or LLVM (which already has many).

But, to be honest, I would worry about distribution later.

Thanks for the info, I have researched these things, I have found limited resources on LLVM and none on GCC.

In GCC, the intermediate language is called the Register Transfer …

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

There are two common options for the code generation. Most compilers have an "intermediate language" that is kind of like C but less human-readable (i.e., a basic procedural language, but more compact). Other compilers simply generate C code and then compile it (for example, the Comeau C++ compiler just generates C code, and another example is Matlab which can also "compile" matlab code into C code and then compile it).

Writing a good back-end is super difficult (i.e., that's where all the crazy optimizations and static analysis goes on). So, you would probably be much better off using an existing back-end, like GCC, LLVM, or any C compiler. Generating C code is probably the easiest thing, but if you want tighter integration with existing back-ends, you might want to use their intermediate languages (and I believe LLVM and GCC have the same intermediate language).

phorce commented: Good advice. +7
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

My signature-spam detectors are going off the charts here, or is it just me?

Rahul and Izhar, you are walking a fine line. If you keep going, you might get infracted and banned, again. The rule states:

Keep It Spam-Free

Do ensure that all posts contain relevant content and substance and are not simply vehicles for external links (including links in the signature).

There are too ways to comply to that rule: have substantial posts (the ones on this thread are dubious); or, do not put (commercial) links in your signature.

hello guys i love someone but i scared becsause if i propose and she say no so that time what should i do that time we are best friend and we are sharing everything that's why i scared so tell me i propose her ya not?

My two cents on the subject. Getting a "no" is not the end of the world, it might just mean you get to keep a good friend and starting looking elsewhere for a mate, or it might mean she's not ready for that yet but at least it'll be clear that you are and that she should start looking at your relationship in that light to figure out if it might work or not. If you don't ask, you'll never know either way, and she won't know either. I say give it a shot, but if it is a "no", try to be understanding and figure out what kind of "no" …

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

oh i thought that the x-- was the bit processing speed but its the architecture i guess. thanks!

These are names for the instruction set (also called the architecture), they are technically not supposed to be named after the 32 vs. 64 bit thing.

I don't know what you mean by "bit processing speed". The 32bit versus 64bit refers to the native size of the registers on the CPU. The registers are a small number of memory slots that are directly on the CPU chip and from which every operation takes its input values and puts its output value.

So, a 64bit CPU means that the preferred size for numbers that the CPU will operate on is 64bit (8 bytes), which includes integers, pointers, and floating-point numbers. Conversely, a 32bit CPU prefers 32bit numbers.

In earlier times, Intel was just putting out CPU series with an assigned model number and a certain instruction set that it supported. Then, they needed to fix it in time and standardize it as PCs became more of an important market. The main result of that is the 80386 instruction set, usually referred to as either i386 or IA-32. That is an instruction set that requires 32bit registers (and thus, supports operations on 32bit numbers), but also supports 16bit operations for backward compatibility. Except for some isoteric platforms, this instruction set is supported by every CPU model since the mid 90s.

Generally, the term x86 refers to the family of instruction sets from …

Assembly Guy commented: Bravo, great detailed explanation +3
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Undeserving Noobs Investing Vast Energy and Resources Solving Insignificant Technical Yawningly-boring-problems

Yellowfish

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

What about the CPU's heat sink? If you removed it and didn't glue it back on with proper heat conducting glue, the CPU will overheat in a matter of seconds and shut down. Just a thought.

Stuugie commented: True but note the screwdriver post! +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Congrats and welcome Jorge!

JorgeM commented: I appreciate it Mike. +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

What people don't get is that the rich do not spend much money at all. Your typical 1% guy will spend or invest on average 5 to 10 percent of his revenue, most of which is in the "risky" part of his investment portfolio. In other words, if you give 1 dollar to a 6-7-figures-salary person (through tax-cut, loop-hole, or subsidy), you are likely to find that about 90 to 95 cents of it will go into a safe investment (e.g., gold, bonds, stable currencies, safe company stocks, real estate, etc.), then most of the rest will go into slightly more risky investments (e.g., "promising" new company, venture capital, etc.), and then a remaining insignificant portion will go to spending (buying stuff). This is why giving money to the rich is considered a depressant for the economy because it takes money out of circulation in the economy and puts it into dormant deposits. It does not create jobs. That's an empirical and logical fact.

By contrast, the poorest people generally spend every dime they can get. This means that every dollar you give to the poor is automatically spent right back on buying stuff (e.g., food). And generally, the people making and selling those things are often fairly poor themselves, meaning their salary is also entirely spent again to buy other stuff, and so it goes. It is only when wealthy business owners take their cut that the money stops circulating (because of what I just explained). This is why …

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

At line 211, you cannot have public: within a function body. This is only allowed (and meaningful) at the class scope. Remove it and it should solve the errors.

Also, you should learn to indent and space out your code better, it will be really helpful in the future to find bugs and for general clarity of the code. Consider this:

#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

template <class A>
class Array
{
    private:
        int siz;

    public:
        A *a;

        void create_array(int cap)
        {
           if( cap > 0 )
           {
               a = new A[cap];
               siz = cap;
           }
           else
           {
               cout << "the size is wrong";
           }
        }

        void store(A values,int index)
        {
            if( index < siz && index >= 0 )
                a[index] = values;
            else
                cout << "invalid index";
        }

        A retrieve(int index)
        {
            if( index < siz && index >= 0 )
                return a[index];
            else
                cout << "invalid index";
        }

};


template <class S>
class stacks
{
    private:
        Array <S>obj;
        int top;
        int capacity;

    public:

        stacks()
        {
            top = 0;
            capacity = 0;
        }

       void create_stack(int s)
       {
            capacity = s;
            top = 0;
            obj.create_array(s);
       }

       void push(S value)
       {
           if( !isFull() )
           {
               obj.store(value,top);
               top += 1;
           }
           else
               cout << "stack overflow";
       }

       S pop()
       {
           if( top != 0 )
           {
               top -= 1;
               return obj.retrieve(top);
           }
           else
               cout << "stack underflow";
       }

       bool isFull()
       {
           if( top == capacity )
               return true;
           else
               return false;
       }

       bool isEmpty()
       {
           if(top==0)
               return …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I often joke that I can read and write C++ code faster than English. It's probably true in sheer number of lines. But this is definitely just something you acquire with time. And yes, for a long time, I would always have to refer back to previous code for lots of stuff from basic file layout to specific programming tricks (or how to use a particular class or something). But over time, it is just that more and more things can be done without reference to previous stuff or online examples. And it just transitions like that.

Also, you might get the impression that "we" can put together a lot of code quickly by seeing us write examples when answering questions on Daniweb, or maybe when a teacher or tutor writes a demo program in two minutes. But remember that for most seasoned programmers, these kinds of exercises or small snippets of code present a very low level of difficulty. For example, I took a compulsory introductory Java course not too long ago, I solved all of the class' assignments for the term (about a dozen assignments) in little more than an hour, it's just that it's really really easy to do those things when you've programmed for so many years before. Because most of this stuff are things you've done hundreds of times before, so, you read the "problem description" and you instantly have all the code in your head, and then it's just a matter of typing it …

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

There are many ways to solve this problem, including just basic OOP-style polymorphism (make A and B be derived from some base-class with the necessary virtual functions you need, and create a new object of type A or B in the constructor).

The most obvious way to solve this is using boost::variant. As so:

class A { /*...*/ };
class B { /*...*/ };

class Foo {
  private:
    boost::variant< A, B > data;

  public:

    enum dataType {
      A_type = 0,
      B_type = 1
    };


    Foo();
    Foo(dataType member_type)
    {
      switch(member_type) 
      {
        case Foo::A_type:
          data = A();
          break;
        case Foo::B_type:
          data = B();
          break;
      };
    };  

    void ProcessCall(Object& obj) {
      switch(data.which()) 
      {
        case Foo::A_type:
          A& a = get<A>(data);
          /*...*/
          break;
        case Foo::B_type:
          B& a = get<B>(data);
          /*...*/
          break;
      };
    };
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I'm sorry, but I am not able to make heads or tails of what you are trying to do. Can you show a minimal "toy" example that shows what you want to do?

Use this as the starting point:

class Foo {
  public:
    enum FooType {
      A = 0,
      B = 1
    };

    Foo(FooType flag) {
      // ??
    };

  private:
    // ?? (data members?) 

};

int main() {
  Foo f( (Foo::A) );
};

Just write the "complete" code that you would like to have working (not just comments saying "here is where I'd like do something", but actual (invalid) code, and pointing out what doesn't work).

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

I'm not sure this is really what you should expect a beginner to produce... seems a bit too advanced. Anyways, here are a few nit-picking remarks.

1) They are not called "template functions", they are called "function templates". This is an easy slip of the tongue, but the latter (and grammatically correct) terminology is useful in stressing the character of templates as being instructions to the compiler on how to generate some code for a given set of compile-time parameters (template arguments: types, etc.). In this case, it is a template to instruct the compiler on how to generate a function for a specific type T, it is not a special kind of function.

2) toupper and tolower are in the std namespace (like all other standard functions and classes, even those coming from C libraries). You forgot to put the full qualification or using-clause.

3) There is no need to flush std::cout just before taking an input from std::cin. Taking an input from std::cin is guaranteed to trigger a flush of the standard output.

4) I suspect that you used the "min" parameter in your takeIn function template just so that you wouldn't have to specify the type T explicitly at the call-site. Although I see the convenience in that, I don't really agree we this kind of practice in general. One reason for that objection is that you end up compromising your interface for a rather trivial reason. And your takeIn function is a good example of that. …

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

I have a bug to report. When I click on the "XX hours ago" to jump to the last post on a thread, it gets me there but the top of the last post comes flush with the top of the browser window, and then, the floating "<DANIWEB>" purple bar appears on top of that, which means I can't actually see the last post without scrolling back up.

Here is a screenshot of one thread where I just clicked to get to the last post and didn't do anything else:
37a09c18318ecc56707f1e7502567400

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

I encountered a nice programming example of Schrödinger's cat. If you have this code:

int main() {
  int a, b, c;
  a = 1;
  b = 2;
  c = a + b;
  cout << "value of c is " << c << endl;
};

Then, the compiler is allowed to re-order the operations in any way such that the result is the same. So, technically, you don't know (without looking at the assembly code) for sure in what order the operations will be performed (because the value-assignment of a and b could be reversed without any difference in the outcome). But, if you wanted to check that the order was indeed the way it was written in the code, you'd have to add some print-outs:

int main() {
  int a, b, c;
  a = 1;
  cout << "value of a is " << a << endl;
  b = 2;
  cout << "value of b is " << b << endl;
  c = a + b;
  cout << "value of c is " << c << endl;
};

But the problem now is that because you have added those print-outs, the compiler is now obligated to perform the value assignment of a before the first print-out, and then do the assignment of b before the second print-out. Which means that you won't be able to answer the question about the order of operations from the first program, because you've now modified the thing you were trying to observe.

So, …

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

@AD: Let me clear that cloud of confusion. Clang is the C / C++ / Objective-C / Objective-C++ front-end for the LLVM compiler back-end. It is a GCC-compatible compiler suite (i.e., you can usually replace any clang-llvm tool with a GCC one, like the linker or standard libraries). Clang is purely a compiler suite, exactly like GCC. It can generally be used as a drop-in replacement for GCC (only the very advanced options differ). It has been mainly supported by Apple and Google, and it is the main official compiler for Mac platforms (for all languages mentioned).

@triumphost:
The Windows support by Clang is only experimental at this point. This means no binary distributions (have to compile from source), no guarantees, no help.

One option is, of course, to use Cygwin. Cygwin is basically a unix system running inside a command-line interface in Windows, which means it is a unix system, and clang is supported, and is even distributed as a standard package (but not the last version) in cygwin's package manager. If you want the newer version, you'll have to compile it from source, which will require either GCC or an older Clang version installed in Cygwin. For doing this, you should just follow the Unix/Linux instructions, because Cygwin is no different. But this also means that you are not really in Windows, and the programs you compile will be compiling for Cygwin, not Windows (Cygwin does have a run-time distribution that allows you to distribute cygwin-compiled programs …

ddanbe commented: Is there anything you don't know? +14
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

There is generally no difference between using an index or using a pointer. Using pointers is technically faster, but using an index will usually result in the same code once the compiler has optimized it (unless it is really bad at optimizing or that the context makes the preservation of the index value necessary).

So, the idea here is that you should use whatever feels more natural and clear in the context. For example, if I want to fill an array with sequence numbers, I would do this:

int number_seq[100];
for(int i = 0; i < 100; ++i)
  number_seq[i] = i;

Instead of this:

int number_seq[100];
for(int* p = number_seq; p != number_seq + 100; ++p)
  *p = (p - number_seq);

Because the first one is much clearer and more natural. The resulting compiled code is likely to be identical in both cases.

In other words, this is just one of these cases where you can trust the compiler to produce pretty much the best code possible, and all you have to worry about is making it "human-friendly".

Also, in C++, there is strong emphasis on the concept of "iterators", which are a kind of abstract generalization of pointers in the context of traversing a sequence of values (array, list, etc.). And in that sense, using pointers to traverse the array is a "natural" thing to do in C++, but obviously, index-based traversals are preferred in many contexts similar to the example above (and for example, …

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

People, this is a signature spam post, look at the OP's signature.

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

To be on the safe side, you should add cin.ignore(); after each input from cin.

adil.ghori commented: thank you +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

There are really only three options (in C++03, pre-C++11) to pass a parameter: by value, by reference or by const-reference. In the case of the copy-constructor, you cannot pass the parameter by value because to be able to do the copy (of the passed object), you need a copy-constructor, so that's impossible. The remaining options are by reference or const-reference, which I think you know already.

So, this boils down to the difference between a reference and a const-reference. As you said, a reference is a kind of const-pointer in disguise. However, like a pointer, it can refer to either a const or non-const object. So, what a const-reference really means is that you obtain a reference to an object that you are not allowed to modify, which is usually fine for a copy-constructor (i.e., a "copy" usually should not modify the original object). And as per the principle of minimum requirements, you should not require that the object be modifiable if you really don't need to modify it, and that is why you would almost always use a const-reference for the parameter of the copy-constructor (although, technically, you could use a non-const reference too, but you will have some rvalue/lvalue issues).

A const-reference is generally preferred whenever the object could be expensive to copy (or cannot be copied at all, like when it is a parameter to a copy-constructor) and all you really need is to be able to "look" at the object (read-only operations). Non-const references should only …

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

This may help, I've compiled with maximum warning levels, using Clang compiler, I get the following warnings:

sales_receipt_prog.cpp:238:1: warning: control may reach end of non-void function [-Wreturn-type]
}
^
sales_receipt_prog.cpp:314:1: warning: control may reach end of non-void function [-Wreturn-type]
}
^
sales_receipt_prog.cpp:263:15: warning: variable 'last' is used uninitialized whenever 'if' condition is false [-Wsometimes-uninitialized]
          if (s>0)
              ^~~
sales_receipt_prog.cpp:297:50: note: uninitialized use occurs here
          cout<<"*******"<<setw(23)<<first<<" "<<last<<setw(26-len5)<<"********"<<endl;
                                                 ^~~~
sales_receipt_prog.cpp:263:11: note: remove the 'if' if its condition is always true
          if (s>0)
          ^~~~~~~~
sales_receipt_prog.cpp:247:26: note: initialize the variable 'last' to silence this warning
          char first,last;
                         ^
                          = '\0'
sales_receipt_prog.cpp:453:1: warning: control may reach end of non-void function [-Wreturn-type]
}
^
sales_receipt_prog.cpp:523:1: warning: control may reach end of non-void function [-Wreturn-type]
}
^
5 warnings generated.

Addressing those warnings will be a good start to solving the problems (it probably will).

adil.ghori commented: always grateful to you +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The declarations are marked as const, which is correct. However, your definitions (in cpp file) are not marked const, which makes the declarations incompatible with the definitions. You need to match them exactly:

Declarations:

string get_name() const ;
int get_age() const ;

Definitions:

string person :: get_name() const // <-- notice the 'const' here.
{
    return name;  //<-- notice, you cannot modify 'name' inside this function.
}

int person :: get_age() const // <-- notice the 'const' here.
{
    return age;  //<-- notice, you cannot modify 'age' inside this function.
}

When a function is marked as const, it means that within it, the data members of the object cannot be modified. This is why I removed your code that prompts the user to enter the name or age. You need to do those things in a separate set of functions:

Declarations:

void prompt_for_name();
void prompt_for_age();

Definitions:

void person :: prompt_for_name()
{
    cout << "Please enter the name of the person ";
    getline(cin,name) ;
}
void person :: prompt_for_age()
{
    cout << "Please enter the age of the person " ;
    cin >> age ;
}

That's pretty much it. Enjoy!

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

Asking about what they are looking for is pretty bad. It is literally like saying "hey, tell me what you want to hear and I'll echo it right back to you.". It's a very old used-car-salesman trick: tell me what kind of car you need and, just like magic, I'll have exactly the right car for you in my lot. Insulting your interviewer's intelligence like that is not a good idea.

People tend to caution against over-confidence, but I'm not one of them. I think the right attitude coming in an interview is "I'm the best candidate, I just need to make sure they understand that". And as far as knowing what they need in a candidate or what they are looking for, the answer is you, they just don't know it yet, so you have to convince them. And most of the work of an interview is before the interview, when you figure out what the job is, the company is, the things they want to hear are, etc.. You can't come to an interview like you would to a blind date: "just to see if you like each other".

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

they remove use of things like virtual functions (including destructors) that cannot be deterministic.

I'm not sure of that. It would depend on what parts of the kernel you are talking about. For example, the Linux kernel does use dynamic polymorphism (dynamic dispatching / virtual functions) for its file-system management. Virtual functions are not generally excluded from hard real-time applications or things like kernel or embedded code, because virtual function calls are deterministic. A virtual function call is no different from calling a function pointer, which will at most (AFAIK) cause one cache miss. And AFAIK, function pointers are heavily used in kernel code.

Multiple inheritance and virtual inheritance are different though, because they allow for arbitrary long dynamic dispatching paths, and thus, non-deterministic latencies.

When it comes to latency, the main thing to avoid is dispatching paths that have a non-constant dynamic complexity. A simple dynamic dispatch (virtual call) is O(1) with a statically predictable upper-bound on the latency. A cast from a derived class to a virtual base is usually O(N) in the number of occurrences of the virtual base within the inheritance graph (which is determined at run-time). For the same reason, a dynamic-cast from a base class to a derived class is usually O(N) in the total number of derived classes (also only known at run-time). I say "usually" because it's probably possible to do better (with some memory overhead) but the assumption is that it is not better than O(N) for these things.

rubberman commented: Well put - and in some regards I stand corrected. You have waxed more expressive than I was willing to do... :-) +12
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think it's slightly off, but close. A typical point that is raised when discussing the idea of writing kernel code (or similar high-performance low-level code) in C++ is that operations such as new, delete and dynamic_cast (not static_cast) do not have a deterministic timing (or latency). In other words, when you are talking about simple operations, such as an integer addition (c = a + b;), the operation will translate to a few machine instructions that will execute in a finite and predictable amount of time (number of clock cycles). At the level of kernel code, this kind of predictable latency is a very important thing (e.g., if you are writing the kernel's task scheduler to switch between execution threads, then you need to be able to estimate a guaranteed upper-bound on the time required for your scheduler to do its work or for the time that it will take the wake-up a sleeping thread, and so on...).

Now, operations like new / delete (or malloc / free), which would need to be implemented differently for kernel code, cannot have a predictable latency or even a guaranteed upper-bound on it. This is because the time that it will take for the heap to find a proper chunk of memory to allocate is simply not predictable as it depends on the amount of memory currently being managed, on the amount of memory still available, and on the level of fragmentation of the RAM memory. So, any kernel coder who is …

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

I don't see any reason for the ExposedA and ExposedB classes to enter the inheritance scheme at all. And also, from your simple example, I don't see any reason for B to inherit from A, but I assume that in your real this is needed.

Anyhow, the point is that ExposedA and ExposedB classes should probably just be wrappers of A and B objects. To get access to their protected / private parts, you would just need to have them either as friend classes or as nested classes. I tend to prefer the nested classes, as so:

class A
{
  protected:
    int a;

  public:
    int getA() const { 
      return a;
    }

    // nested accessor class:
    class exposed {
      protected:
        A* p_a;

      public:
        explicit exposed(A& aRA) : p_a(&aRA) { };

        const exposed& setA(int aA) const { p_a->a = aA; return *this; }
    };
};

class B : public A
{
  protected:
    int b;

  public:
    int getB() const { 
      return b;
    };

    // nested accessor class:
    class exposed : public A::exposed {
      public:
        explicit exposed(B& aRB) : A::exposed(aRB) { };

        const exposed& setB(int aB) const { static_cast<B*>(p_a)->b = aB; return *this; }
    };
};

Meaning that the main function looks like this:

int main() {
  B b_obj;
  B::exposed(b_obj).setB(1).setA(2);
  int a = b_obj.getA();
  int b = b_obj.getB();
  //I want the following two lines to fail:
  b_obj.setA(1);
  b_obj.setB(2);
};

So, this is really the simplest solution because it really does the only thing that you really need, which is to …

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

There are also a number of additional serious problems with your code.

1) Your copy-constructor is wrong:

    CLibrary::CLibrary(CLibrary &B)
    {
        mA = new CArticle*[MAX];
        mA = B.mA;    // <-- Problem! Assign the pointer 'B.mA' to the pointer 'this->mA'
                      //  the memory you just allocated (with new) is leaked, and both the 
                      //  original object 'B' and this object will refer to the same memory.
                      //  This is called a shallow copy, what you need is a deep copy.
                      //  Such as:
        // std::copy(B.mA, B.mA + MAX, mA);   // copy data in [B.mA, B.mA+MAX) to [mA, mA+MAX).
        mName = strdup(B.mName);
        mNr = B.mNr;
    }

2) The destructor of a polymorphic base-class should always be declared as virtual to make sure that the correct derived-class destructor will be called when you delete the base-class object (via a pointer to it). So, declare the base-class destructor virtual as so:

class CArticle
{
    public:
        int mIndex;

        CArticle(int c = 0) {  // note: easier to have default-value instead of two constructors.
            mIndex=c;
        }

        // note: copy-constructor is not needed here (the default version is correct).

        virtual void print() = 0;

        virtual ~CArticle() {};   // virtual destructor.
};

3) The destructor of the CLibrary class is also wrong because you don't delete any of the objects that your library has ownership of, nor do you actually delete the memory you use to store that array of pointers. So, you'd need something like this:

    CLibrary::~CLibrary() {
        for (int i=0; …
deceptikon commented: I was hoping you'd chime in. I didn't have time yesterday to go into any real detail. :( +12
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I was wondering if there is a way to say do this:
...
Instead of having to do this:
...
I would have thought that if it wasn't possible that C++11 would have fixed that, given that it created the && move constructor, why couldn't it create some kind of reference re-assign operator?

Well, you came very close to the answer, sort of by accident, by mentioning the rvalue-references (&&). With your two examples, you missed out on one possibility, which is what is done in a standard class like std::reference_wrapper, i.e., the following simple trick:

class someDataClass
{// private:
    const largeDataType *data;
  public:
    someDataClass& setDataRef(const largeDataType& o) {  // take by reference
      data = &o;   // store the address
      return this;
    };
};

The only problem with the above solution is that because in C++ there is a rule to allow temporary values (rvalue) to be bound to a const-reference, which would allow people to call this function with a temporary value, of which taking the address would not be a good idea, obviously. But, with C++11, you can easily remove that possibility and that danger:

class someDataClass
{// private:
    const largeDataType *data;
  public:
    someDataClass& setDataRef(const largeDataType& o) {  // take by reference
      data = &o;   // store the address
      return this;
    };

    someDataClass& setDataRef(largeDataType&&) = delete;  // forbid calling with rvalue.
};

In the above, the rvalue-reference overload will be selected whenever an rvalue is passed, and thus, …

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

I prefer my Generic Programming (GP) version of bubble-sort:

template <typename ForwardIter, typename Compare>
void bubble_sort(ForwardIter first, ForwardIter last, Compare comp) {
  ForwardIter current_next;
  for(bool swapped = true; (swapped && (!(swapped = false))); --last) 
    for(ForwardIter current = first; (current_next = std::next(current)) != last; ++current) 
      if ( comp(*current_next, *current) && ( swapped = true ) ) 
        std::iter_swap(current, current_next); 
};

(warning: submitting this for a homework is going to draw a lot of suspicion)

NathanOliver commented: I like the warning +11
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you don't want anything special, just use defaults.

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

Are you using a MAC? Because a quick google search makes it pretty clear that this is a MAC OS X issue.

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

The standard input:

cin >> str;

will read the text that has been inputted only up to the first space character (or new-line, or tab, etc.), and it will store that resulting text (i.e., the first word) as a null-terminated string in the memory pointed to by str. So, the 0 character that your are getting right after the first word is not, in fact, the space character, but it is the null-terminating character that marks the end of the string (i.e., "null-terminated" means that the end is marked by a 0 character).

To read a full line as input, you need to use a function like std::getline() (to read into a C++ string) or cin.getline() (to read into a C-style null-terminated string). Also note that C++ strings are always preferred.

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

I'm starting to hate the whole new "convergence" and "personalized" strategies for google searches and others.

When I search for a coding issue, it is usually some obscure and very specific issue. It is true that SO often offers one or two reasonably related threads that can be useful to me, but very often there are gems to be found in more obscure sources, like less-prevalent forums, old bulletin boards, comment sections, personal pages from enthusiasts, mailing-list archives, or scholarly articles. I have noticed recently (roughly in the time frame you are referring to), that at least the top 5 results on google are almost always SO threads, and typically (for the kind of specific issues I look up), only one SO result is remotely related to the issue I looked up and the rest are unrelated or don't have any useful discussion in it. This is really annoying. I know that SO ranks high (deservingly) in general, but it should not mean that it should rank high for every specific search.

My impression is that the way it used to be, roughly-speaking, is that the top results are those that contain the best match for the search terms, with some conservative filtering out (or pushing down) of less reputable sources. Now, it seems to be reversed quite significantly, i.e., pull up the most reputable sources (most popular sites) and consider the search terms matching almost as a second thought. It is true that the way it was before (and …

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

The compiler explains it pretty well:

error: 'i' is a protected member of 'A'

That's pretty much all there is to it. The member function g is a member of class B, and the function f is a friend of class B. They both can only have access to private / protected members of class B, not those of class A. Before you say "what a minute, the protected members of A are accessible from B", I will correct you on that and state it more precisely: "member functions or friends of B have acces to protected members of A that the objects of class B have inherited".

This boils down to a case of "all B's are A's but not all A's are B's". In other words, the access to the members of A is granted to members / friends of B on the condition that they come from an instance of B. That's why you can't get access to them directly, either by pa->i or &A::i, you must always go through B class first.

nitin1 commented: excellent!! excellent!! +3