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

What about using a function templates like these ones:

template <typename T>
T read_value(char*& ptr) {
  T result = *(reinterpret_cast<T*>(ptr));
  ptr += sizeof(T);
  return result;
};

template <typename T>
void write_value(char*& ptr, const T& val) {
  *(reinterpret_cast<T*>(ptr)) = val;
  ptr += sizeof(T);
};

And then do this:

char* Data = static_cast<char*>(GivenPtr);

char* cur_ptr = Data;

switch( read_value<int>(cur_ptr) ) {
  case OBJECT:
  {
    // ... 
    double some_value = read_value<double>(cur_ptr);
    //... etc..
  };
  break;
  case OBJECT2:
    // ...
};

How can I tell what Indicies to write to after each cast?

Whenever you read/write something from the buffer, increment the pointer by the size of the value you read/wrote. This is easiest with a function template as I showed above.

Is there a way to just write it straight to a char* and then read straight from that char?

That's pretty much what you are doing already. The type casts will not really cause any overhead, beyond that of breaking word-alignment.

Better yet, can I do this with a void?

It is preferrable to do it with a char* because it has a guaranteed size of 1 byte, while a void has undefined size, which is going to cause trouble when doing the pointer incrementing.

triumphost commented: Ahh :o I never thought about templating it :o Best solution! +6
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Being a big C++ advocate, it would be hard for me not to recommend it. I would certainly say that using Qt (with QtCreator) in C++, doing that project that you envision will be a walk in the park, if you are at least somewhat comfortable already in C++. The learning curve is really the only obstacle to C++, once you are passed the steepest part of it, almost everything is very easy. But if you are familiar with things like assembly programming, that hurdle shouldn't be too hard to overcome.

And also, generally, most assembly programmers I've met are happiest when they are in control of the low-level details and are in a predictable run-time environment (i.e., they are generally OK to work in C, and a little uncomfortable in C++, but can't stand anything "higher" than that). That could be a problem with Python. I know that is a little bit of a problem for me, I love the style and ease of use of Python, but I also know how important certain optimizations are, like streamlined memory traversal patterns and locality of reference issues, that I have a hard time in an environment that gives me little to no control over that. But, of course, the application you have in mind is not anywhere near being performance critical or heavily algorithmic (which is the kind of thing I do), so all these issues don't matter, but be aware that it might be an unpleasant feeling, if coming …

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

Writing a custom allocator is just about obeying the interface specified by the C++ standard. It's not really that hard at all. Of course in order to be able to use a custom allocator, you need to specify it in the instantiation of your STL containers, and if it is stateful you need to construct the allocator during the construction of the STL containers.

As for tutorials / guidelines, I think that pretty much every C++ book that talks about the STL has a chapter or section that talks about creating a custom allocator, many of which use the example of a memory pool allocator. Bjarne Stroustrup has a section about allocators in "The C++ Programming Language" with a memory pool example. Then, I wrote a quick and simple example of a no-init allocator as an answer to this SO thread. Scott Meyers talks about allocators in his items 10 and 11 for "Effective STL". Then, you'll find chapters on allocators in books like "C++ Programming with the Standard Template Library" (David R. Musser) (Chapter 24), "The C++ Standard Library: A Tutorial and Reference" (N.M. Josuttis) (Chapter 15), and in "Modern C++ Design: Generic Programming and Design Patterns Applied" (Andrei Alexandrescu) (Chapter 4) (warning: this last book is pretty advanced).

What is hard about creating a custom allocator is making sure it is efficient and robust (reliable), let alone be worth it, because very often the conjunction of OS memory handling mechanisms, the optimizations within the heap implementation, …

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

Is there any default user name n password for ubuntu???

Read my answer above. Short answer, write sudo su in the terminal, and enter your user password, then you can reset the root password using the passwd command.

Darshan5 commented: Thanks, Mike... +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

"In recognition of this intent, a single-argument constructor in C++ is called a copy constructor."

That statement is false. Here is the standard definition, from Section 12.8/2:

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments (8.3.6).

Then, all constructors that can be called with a single argument are called (explicit) converting constructors ("explicit" only if marked with the attribute explicit). The copy-constructor (and move-constructor) is a special kind of converting constructor.

So, the authors of the book were wrong, you were right.

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

Another simpler solution that doesn't involve a live CD and all this fiddling with the system files is to simply boot into single-user mode. I had this happen to be a couple of times, grabbing a dusty old Linux box that noone had the password for, booting into single-user mode and just resetting the password with passwd command takes about 5 minutes at most.

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

I can already picture it:

After a hard day's work on a new warp drive for the ferry ship to Europa (Jupiter's moon), I drive my personal flying machine back home at super-sonic speed. Before I know it, I'm sitting in my entirely automated home, and I decide I feel like slashing some monsters. So, I grab my super-powerful quantum computer, plug it into my cortex implant (via a pico-USB cable) to enter the virtual world of Diablo XIV, but then, I read: "Please wait while Windows 28 is installing 143 critical updates. Do not unplug your implant from the computer. Only 87 minutes remaining..."

np complete commented: This is funny :P +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It depends. There are generally three kinds of libraries in C++: shared libraries, static libraries and header-only libraries.

In the classic plain C++ world (e.g., basic OOP code, no template), the library will be made up of header files that declare classes and functions, and corresponding source files that implement the functions and classes. If you want other people to use the library without having to import all the source files into their "project" (e.g., the list of source files in your IDE), then you need to compile all the source files into a library, which can be either static or shared (also called "dynamic-link library" in Windows lingo).

A static library is essentially just a raw collection of compiled code (i.e., each source file is compiled separately into an object file (.o or .obj extension, usually), and then they are collected together in one static library file). A user of the library would write his code, including the headers from your library, and link to that static library (i.e., to fetch the compiled code that implements the functions he uses). With a static library, the linker will grab all the relevant compiled code from the static library and copy it into the user's executable. At this point, the executable is entirely standalone and does not require the users of that application to have the library installed on their computer.

For a shared library (or dynamic link library (DLL)), the library is technically-speaking more like an executable than like a …

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

Is this just wrong or are they being cautious about mixing C and C++?

No, it is correct. When you are using a compiler like GCC (within MinGW distribution), this is actually the GNU Compiler Collection which includes both a C compiler and a C++ compiler (at least, but often a few others like Fortran, Ada, and possibly Objective-C and Java compilers). What Ancient Dragon explained about extensions *.c vs. *.cpp is that CodeBlocks will invoke the gcc.exe program to compile all the source code, and that program is made to check the file extension and compile the code accordingly with the appropriate compiler (i.e., its C or C++ compiler). GCC uses the same backend for all its compilers and it uses one linker for all linking tasks, so, once individual source files were compiled, it doesn't make a difference from which original language they were compiled from, they all just link together (as long as they have the appropriate extern "C" wrapping in the headers in between C and C++ code). So, SQLite is correct in saying you can't compile their code with a C++ compiler, only with a C compiler, but that is already what is happening under-the-hood when you add the C code to your project.

The more pedantic way to do this is to take all the C code from that external library and compile it into a static or shared library, and then link that static library to your compiled C++ code. It …

daino commented: Thanks for the effort. Great Answer. +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Sure. Use an archive manager application. For KDE, the standard one is Ark. For Gnome, the standard one is File Roller. Both open-source and installable from repositories, and they will certainly allow you to preview text files. I know that Ark is well integrated with other KDE programs to allow you to open just about any typical document you'll find in a tarball.

If you are talking about doing this in a terminal, then you just need use the tar command, which has many options, including that of filtering through bzip2 compression/uncompression. For more details, type man tar in your terminal.

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

Your best bet is to use Poppler because PDF is a complex format with no easy way to extract text from, you need to rely on a library made to load PDFs, like Poppler. There is a utility called pdftotext which does exactly what you want. You can use it in a bash terminal (Unix / Linux) for example to save the text to a file:

$ pdftotext my_file.pdf > my_file.txt

Or to count the number of occurrences of the word "the" in a pdf file:

$ pdftotext my_file.pdf | grep -w -o the | wc -l

Within a C++ program, you can simply issue a system() call with commands like the above, or you can use the libpoppler C++ API directly.

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

(1) The money invested to produce those capital gains has already been taxed once, so you're really talking about taxing it twice;

Taxes are essentially applied to any money transfer, that's how it works. It's not about how many times a given chunk of money has been taxed. Taxes are like a toll paid to the government at every transfer of money, from employer to employee (as payroll tax), from company to investors (capital gain), from buyer to seller (sales tax), etc. If you don't like this system, that's one thing to argue about, but you cannot say "this money was taxed twice" because that makes no sense from the perspective of what taxes are, by definition.

The problem with arguments about why this or that particular kind of tax should be lowered or abolished is that it leaves a route for money to travel untaxed or at a reduced tax rate. And those who have the means to choose different paths to route their money into their pockets or their tax-haven account will choose the path for least taxation.

(2) Over longer terms, most of the returns from capital gains are due to inflation.

Then adjust the capital gain tax to be valued against present value. I agree that the inflation part of the capital gains should not be taxed as it is more a part of the principal than a part of the revenue. But the problem with the capital gain tax is not …

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

can the same source code run in different operating systems ? how?

The same source code can be compiled for different operatings systems (and overall platform). There are about 4 kinds of "source code": the standard library, the operating system's API, third-party libraries, and your own code. The standard library is provided to you along with the compiler (GCC, MSVC, ICC, etc.), and it was either specifically made for the target platform (e.g., MSVC) or configured to work well on the target platform (e.g., GCC). The functions and classes available in the standard library are, well, standard, so they apply across the board, all conforming compilers must provide it on each platform that they provide compilers for (with some exceptions for restricted environments like micro-controllers).

The operating system's API is obviously platform-specific. If you need to use it, you must be aware that it will only work on that platform. If you want to do the same thing (e.g., open a network connection) on different platforms, you must use conditional compilation, typically looking like this:

#ifdef _WIN32
 // put Windows-specific code here..
#else
 // put Unix/Linux-specific code here..
#endif

Third-party libraries (or external libraries) will vary depending on whoever wrote them. Most library implementers try to be as cross-platform as possible with their implementations. The way to do that is to use only use standard libraries and other external cross-platform libraries, and use the above techniques whenever a operating system API feature is needed …

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

Looking at another interest of mine, being Robotics at the moment at University which kind of combines all of my main interests...

If you're interested in robotics, you'll have to make a choice about which way to go about it. Because it is a multi-disciplinary field (which is what I love about it), there are many aspects to it, essentially, hardware and software. The hardware side is usually called "mechatronics" (fusion of mechanics and electronics / electromechanical devices like actuators and sensors), and would normally require that you go down the path of getting a B.Eng. degree in either mechanical engineering or electrical engineering (or something in between, if you find a good mechatronics program). The software side is usually called "automation", and would normally require that you do something like a software engineering or computer science degree. Few people work in robotics without having at least a Masters degree, so that's something to be prepared for too, and that's also a good time to step to the opposite side (hardware vs. software) of what you did the undergraduate degree in.

maths may be an issue though.

Be warned, whatever you do in robotics, there is a ton of programming or a ton of math, and usually both. The programming is mostly low-level C and high-performance C++, with some interludes with languages like matlab or Java (for tools or testing things out). The math is mostly probability theory (artificial intelligence stuff), computer sciency things (like graph …

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

Playing to the stereotypes: What's the best brand of vodka?

nitin1 commented: excellent question!! ;) +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

but i never say anyone about my awesome and fabulous source is. ;)

You are reaping the benefits of a community of people who find that it is important to share knowledge and help others to improve, and are generous enough to take the time to do so. Then you turn around and keep that knowledge and resources to yourself. Not cool, man.

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

@AD: That's a screen shot of msys, the MinGW replacement from cmd.exe (command prompt). It is a unix-like bash shell for Windows, like cygwin. That's the standard way to run MinGW/GCC in command-line (unless you want to suffer and use the command prompt).

@Vastor: The problem I see on the screenshot is that you are using a DOS-style address of the folder, but msys (or cygwin) uses Unix style. In other words, you entered cd C:\Users\mat, but, in Unix style, it should be cd /c/Users/mat. That's all. It might be good to for you to know a few basic Unix shell commands.

There shouldn't be an access rights problem here, since you are the user "mat", and if there is, it will display a message saying that. It is usually preferable to avoid user directories in Windows, they are a mess of access restrictions and convoluted symbolic links.

Vasthor commented: thank you very much. +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Glad you figured it out. For a more complete understanding, I suggest you read the relevant parts of the C++ Standard: Section 3.1 "Declarations and Definitions", and Section 7.1.1 "Storage Class Specifiers".

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

Let's have a look at the C++ Standard, shall we:

Section 17.6.4.3.2/1:

Certain sets of names and function signatures are always reserved to the implementation:
— Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.
— Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

So, the first person was correct. Technically speaking, this only applies to global names (including pre-processor defines of MACROs), but to be on the safe side, you'd better avoid it altogether.

Then someone today said that that advice was 100% wrong and that it was better the first time and that the convention, for configuration / ini files where the user changes the code to allow or disallow options, a leading underscore is used to specify that this is a pre-processor name as opposed to, say, a constant.

There is no wide-spread convention that I know of that prescribes leading underscores for #defines. That guy pulled that out of his ... hat. You might see leading underscores in the standard library implementation provided by your compiler, but that's the point, it is reserved for the "implementation" (which means the compiler and its standard library implementation). You might see that in Boost libraries too, being the anti-chamber for standard libraries, it's just an exception to the rule.

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

The only real difference between a struct and a class is in the default inheritance and access rights. Given a base-class B, you could write:

class C : B {  // inherits B privately, by default, same as ': private B {'.
  void foo();  // private member function, same as 'private: void foo();'.
};

struct D : B {  // inherits B publicly, by default, same as ': public B {'.
  void foo();   // public member function, same as 'public: void foo();'.
};

Generally, it is not recommended to use the default inheritance or access rights, so you should always spell it out (i.e., have the public or private keywords explicitly stated). With regards to the C++ Standard, there is never any distinction made between a struct or a class (except where it specifies the default rights associated to them), they are both referred to as a class.

In common coding practice and popular terminology, C++ programmers will often say a "structure" for something ressembling a C-style struct (meaning a struct that would be valid in C: no inheritance, only public data members, and no member functions). In formal language (as in the ISO standard document), this is called a POD-type (Plain-Old-Data type). Often, C++ programmers will use the keyword struct when building such a simple class (just a container of a few data members, with only simple and public member functions). But this is nothing more than a convention (and a bit of syntax convenience as POD-types …

np complete commented: nice information +3
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I would say neither.
The two words you've chosen are really bad to describe what addiction is (drug or otherwise). A disease usually implies either a virus or an infection, i.e., some kind of foreign organism (pathogene) spreading in your body. Addiction is nothing like that at all. And the word "defect" is usually associated with something permanent and genetic, like a birth defect. Again, addiction is a behavior that can be learned from others or develops on its own, and can be unlearned or tamed. I find that the tone of the terms you chose to use are pejorative.

At most, addiction is classified as a disorder (and a rather mild one at that). I think that officially drug addiction, specifically, is classified as a "substance use disorder". Personally, I think it's a stupid classification. Besides chemical dependence that some drugs cause (mostly tobacco, cafeine, cocaine, and opiates (heroine, morphine, oxycontin, etc.)), which isn't nearly as strong as people think, the main component of a drug addiction is just the behavioral addiction, which, generally speaking, could involve anything, not just drugs. You can be addicted to sex to the point that it ruins any relationship you try to have, you can be addicted to shopping to the point that it has you go bankrupt, and you can be addicted to a whole lot of other things (some more harmful than others, or less conspicuous than others). I would classify addiction as a personality disorder, that is, in the …

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

As AD said, there are many alternatives. Doing Win32 API directly is probably the worst option. In a similar style as doing Win32 API directly, you can use SDL, which is at least cross-platform and a bit easier, but still very basic and low-level like Win32 API. On the Microsoft side, one option is MFC, but it is old and is being deprecated by MS (which I think is a good thing, because MFC sucked), and then, there is WinForm (Windows Forms) which is better than MFC but WinForms is basically another name for the GUI part of the .NET platform, meaning you have to use C++/CLI (a hybrid language between C++ and C#) or a .NET-only language (like C#), so you basically have to learn a new language to use it (and the hybridization in C++/CLI is a bit quirky). So, there is no current, decent GUI toolkit in pure C++ offered by Microsoft right now (or there never was, depending on whether you consider MFC to be decent or not). A common practice is to compile the important C++ code into a DLL and call it from the GUI written in another language.

Outside the MS world, there a much nicer alternatives in C++, IMHO. wxWidgets is a popular one, but I have never used it. Ditto for GTK+. Qt is definitely what I recommend, it is cross-platform, easy and intuitive, and all object-oriented, …

sss93 commented: Thanks btw QtCreator works with what compiler ?? +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Why can't we do this in C++? The compiler says it's ambiguous or that the parameter x shadows a member of such and such class.
Is there any tricks to doing this?

The this pointer exists in C++ too (Java copied this feature from C++). You can access the members as this->x or this->y. The compiler is always going to complain about the shadowing of the member by the parameter if they have the same name, just to make sure you are aware that addressing x is not going to address this->x but the parameter. The easiest way to avoid this is to just use a different name for the parameter. Personally, I often just add a "a" in front and use a CamelCase for the parameters, in this case it would be aX. There are other conventions, like putting a trailing underscore for parameters, as in x_.

In the above, they use the this keyword to call another constructor of the exact same class! I read somewhere that it's bad to do this in c++ and that it's better to make a new object and just assign it to the current one. Is this true or can I actually do this in C++?

In C++, it is true that you should never call a constructor directly, and I don't think you would be allowed too, but it is possible through the placement-new syntax. Certainly, you should not call another constructor within one constructor, using …

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

Most programming languages and some scripting/interpreted languages have the capability of calling C functions in a DLL or .so file (i.e., a shared library). This is what usually serves as the glue between any two language, and is most often the basis for other frameworks geared towards inter-language interfaces (like COM objects in Windows). If you do this by hand (without the help of a special tool or library), the process is usually as follows:

  1. Write your code in Language 1.
  2. Write a set of C-compatible function (i.e., with a standard calling convention, no name-mangling, only opaque pointers or primitive types as parameters, etc.) in Language 1.
  3. Compile (or encapsulate) the code from steps 1 and 2 into a shared library (or DLL) which exports all the C functions.
  4. Write code in Language 2 that wraps the C function calls into a structure (classes, and functions) that mirror the original code (step 1), but in Language 2.
  5. Link (dynamically) all your Language 2 code with the shared library created in step 3.

For simple applications, the above can be done by hand very easily. For larger applications, it might be very difficult to do it just based on the two languages that you are dealing with (especially being able to do step 4 with fidelity). And, you would normally use an automated tool for this purpose. These tools vary between language combinations, and some consist only of libraries in the destination and/or source language, while some are more involved …

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

when I execute the program it gives me random numbers but it has given me anything from 3- 16.... instead of 3-14.

Then, you should use:

return (3 + rand() % 12);

Thanks for your help. I apologize for my poor use of words... it is in fact creating an object on each iteration. :) also I am a she not a he ;) not that it matters anyway... I hope. :)

Glad to help! Sorry for assume you were a "he"... and no it doesn't matter that you're a lady ;) If anything, you'll get more gallantry ;)

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

The seeding really only needs to occur once in the entire program (at the start). You don't need and shouldn't re-seed in the constructor of that object. Just call the seed once at the start of the main() function, and that's it. Try it, it will work as you want it to.

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

I just want to point out, there is one example of completely unfettered capitalism (i.e., a perfect "free-market"), it is called drug trafficking. Government has no effective control over that market, it doesn't regulate the workers, the products nor the economics. What is the result? Exactly what Adams Smith predicted, a feudal system of monopolies (drug cartels) where competition is harshly quelled, prices are entirely controlled by the suppliers, the drugs are most often produced in slave labor, and there is a whole bunch of power-drunk incidents and activities like hijacking local authorities and extorsions in local businesses. This is just a glimpse of the horrors of unfettered capitalism. Another interesting case is, of course, Chile, which has been this lab experiment for neo-liberals to try out a "privatize everything and no regulation" strategy. This state has been nothing but miserable failures one after the other, a huge gap between the poor and the rich, and just general mayhem of riots and protests ever since, even as they get tremendous "help" from corporations and foreign investments.

As for N. Korea, has anyone ever seriously suggested that it is a communist state? That's news to me. They might have originally been established with the help of the soviets and chinese (which are themselves just fascist states, as I said earlier), but now it is just this weird and crazy military dictatorship and "necrocracy" (with a dead man as eternal president). In fact, the words "communism" or "socialism" have been banned for …

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

The fact that it's human nature to want, means that any full implementation of these systems will fail.

That's very true. I see that argument as a warrant of caution for those who might dream of a total socialist overhaul of society. Most of what we can point to as the main components of a "civilized" society are the things that go against our human nature (at least, the nastier side of human nature):

  • Just grab the money and run: Can't do that.
  • Kill the guy who slept with my wife: Can't do that.
  • Punch the prick who cut in the line: Can't do that.
  • Slap that girl's behind: Can't do that.
  • Tell lies about your products to sell them: Can't do that.
  • Put your kids to work for a little extra drinking cash: Can't do that.
  • ... and so on..

Of course, you can argue that all the above restrictions and laws are destined to be failures, because you'll never be able to eradicate these tendencies. But does it invalidate those restrictions / laws / rules? No. The same goes for socialism. It goes against the tendencies of people to be greedy, to screw people over, to use their power to exploit and corrupt, to collude in order to control the market, and so on. In some domains, like health care, law enforcement, or fire-fighting, if those tendencies are given free reign, people die, and that's why so many civilized western countries have adopted a public …

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

Please correct me where I'm wrong.

OK

Every source file compiled is a translation unit.

That's correct. Everything that turns into one object file (.o or .obj) is a translation unit. The compiler only looks at one translation unit at a time, the linker then assembles them.

When I create constants.cpp and include constants.h in it, they both together form a translation unit.

Pretty much. The cpp file that you compile is the translation unit. As for the headers, you have to think of the include-statements as just a "insert file here" mechanism that grabs all the content of the header file and inserts it in place of the include-statement. So, the cpp file and all the headers it includes turn into one massive source file, and that is the translation unit.

Lets say I didn't use extern. It becomes static by default.

For const-variables, yes.

So when I now include constants.h in my several other .cpps,.. will copies of the same variable(stored in separate addresses) be made? Is this what internal linkage is?

Yes. That's what internal linkage means. It means that all the parts of the code in that translation unit will refer to (be linked with) an internal copy of the variable which only exists in that translation unit, and which is not visible to the linker when linking the object files (compiled translation units).

Given that a constant variable can't and won't be changed in …

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

You have a circular dependency problem. "Container.h" includes "Student_info.h" which includes "Container.h" which includes "Student_info.h" ... In terms of your declarations, you shouldn't need that. In other words, you shouldn't need to include "Container.h" in the "Student_info.h" file. Remove that include statement and your problem should be solved.

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

@mike (your Project manager?) in the youtube video is a real hottie. I don't think I'd be able to concentrate on what I was doing if she was leading... haha.

A rather juvenile comment if you ask me. Kat is one of the most competent engineers I know, and she used to be an airforce jet pilot. She now works as a system's engineer for one of the largest space contractors in Europe, and is well on her way to becoming an astronaut. You can't really be distracted by her good looks (which she certainly has), not with the amount of concentration, sharpness and professionalism required just to hold a project-related conversation with her. If anything, she has the opposite effect on people.

You projects are way out of my bounds :(

Out of bounds but not out of reach. That's what it means to challenge yourself, to reach outside your boundaries.

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

your all 3 phases are concentrated towards projects and projects. hey! Can you please share the projects we should take at this age (time) and what all projects you have taken?

If I skim through my old dev-folders in my computer, I get more or less this list of projects (by phase, and more or less in chronological order):

Phase 1: (more or less junior-high to high-school, up to maybe first half of undergraduate studies) (also, most of these things were never really completed, but at least the core of it was done)

GUI-based Calculator (Visual Basic)
Text-based RPG game (TI-83 assembly) (during boring math classes in high-school)
Transparent Notepad (Delphi & VCL)
Code-line Counter (Delphi & VCL)
Encrypted Archiving Program (Delphi & VCL) (kinda like a Winzip program, but for a home-made encryted archive format)
3D DNA Visualization Program (Delphi & OpenGL)
Started a 1st 3D Rendering & Game Engine (Delphi & OpenGL) (called it "Linak")
3D Skating game (Delphi & OpenGL) (never went very far with that)
3D Model Editor (Delphi, VCL & OpenGL) (never went very far with that)
Started a 2nd 3D Rendering & Game Engine (Delphi & OpenGL) (called it "Element")
Random Landscape Generator Algorithms & Editor (Delphi, VCL & OpenGL)
OpenGL-friendly Font Generator (Delphi, VCL & OpenGL)
Simple FPS Game (Delphi & OpenGL) (running on "Element")
3D Physics Engine and Collision Detector (Delphi) (for "Element")
Software-based Multi-texturing (Delphi & OpenGL) (before video cards could support multi-texturing)
Generalized my Random Landscape Generator to …

I_m_rude commented: eyes are not closing :-O +0
iamthwee commented: Great post, thanks for taking the time to write such detail as well +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

while const int may not even be given storage because the compiler may just treat it as if it were a macro by inserting its value wherever it is used.

No, it can't be treated as a macro (substituting for a literal constant), because the const-variable must have an address in memory, i.e., you need to be able to write const int* p = &var; and get a valid address out of that. Literal constants are prvalues, and thus, don't have an address in memory, while const-variables are non-modifiable lvalues, they're different.

In corresponding source, "constants.cpp", I would put const int var = 5;.

This is wrong. In the "constants.cpp", you need to write:

extern const int var = 5;

This is because, by default, a const-variable has internal linkage (i.e., not accessible from other translation units). This means that writing const int var = 5; is equivalent to writing static const int var = 5;, which is inconsistent with the prior declaration (in "constants.h") as an extern.

Then, every source file would get var. (supposedly)
Will source files, that don't #include "constants.h" get access to var?

Every source file that has an #include "constants.h" will have access to that one and unique instance of the const-variable var. In other words, if you print the address of var from each source file, you will get the same value.

If so, how would it possible if there is no link between …

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

Just share that what have you all done in your universities/scholl time which made you to come to this level of programming.

For programming, the University / School part was mostly irrelevant, I only ever took a few programming courses and they were all compulsory courses (as part of engineering curriculums there are usually a few introductory programming or numerical methods courses) that I took long after I was already more than proficient in programming. Don't think that university courses will teach you to be a programmer. They might teach you to be a good computer scientist, or even a software engineer (although, I'm very skeptical of that), but not a programmer. Programming is more akin to a craft, and is only learn as such, like other "crafts" like being a blacksmith or plumber, you learn by doing it a lot, filling your bag of tricks, taking example on more experienced people or mentors, and with lots of time.

I would describe my experience getting to where I am in three phases:

Phase 1 (formative years, and having fun):
Taking the analogy of becoming a plumber, this phase would be the years when you nag your dad to go with him to work (as a plumber) and do simple plumbing work, for fun.
By and large, what made me come to this level of programming was challenging myself constantly. Starting in teenage years is the best, you combine the capacity to be excited and passionate about …

I_m_rude commented: hats off! it's really valuable whosoever will read it. ;) +0
np complete commented: Nice read for young coders like me :) +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I watched "A Fistful of Dynamite" yesterday... man, I never get tired of this movie, a timeless classic, like most of Sergio Leone's work.

GrimJack commented: Jame Coburn was my hero - thank you for the reminder +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I am expecting an answer from an kind of a expert who have read multiple books .

The main problem with this is that you don't become an expert by reading books after books on C++ (I think I have maybe read, partially, about 3-4 books on C++, and all were the more advanced books from the "C++ In-Depth" series, i.e., expert-level books). You become an expert by spending years honing the craft. Maybe some of the experts here started their learning journey by reading one of those "beginners" book many years ago, but they have long since moved on. Safe to say, I'm an expert in C++, but I have never read a beginner's book. I started fiddling with programming on another "easier" language (Delphi), and when I switched to C++ (many years ago), a beginner's book was of little use to me.

The best I can do to help you is convey hearsay about recent readers having said "I learn C++ using book X, and it was really good.", and skim through tables of contents or the books themselves and assess whether it seems well written and has the right stuff in it. In that perspective, the C++ Primer (4th or 5th edition) are highly recommended. What you want to look for is who the authors are. You need authors that are knowledgeable, experienced, and have written a lot of such educational material before. In that respect, C++ Primer has a stellar track-record. And, …

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

Here is my two cents from taking a bit of time to skim through most of the major books on C++.

For Beginners

The best I can do to help you is convey hearsay about recent readers having said "I learn C++ using book X, and it was really good.", and skim through tables of contents or the books themselves and assess whether it seems well written and has the right stuff in it. In that perspective, the C++ Primer (4th or 5th edition) are highly recommended. What you want to look for is who the authors are. You need authors that are knowledgeable, experienced, and have written a lot of such educational material before. In that respect, C++ Primer has a stellar track-record. And, of course, the catchier the title, the worse the book is, usually. And, from those criteria, the list gets pretty short (I won't even mention those ridiculous "C++ for Dummies" or "Learn C++ in 21 days" books):

  • "C++ Primer, 5th Edition": Well written, well structured, has lots of examples and exercises, good authors, and no hidden agenda (or programming philosophy to convey), just straight-forward "learn to do stuff" approach.
  • "Accelerated C++": Original in its approach, very to the point, stellar reviews, recommended authors, and very complete. The drawback is that it is getting a bit old now.

Books that are tempting, but not good enough in my opinion:

Ancient Dragon commented: Excellent :) +14
~s.o.s~ commented: Good list +14
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

But I already do that! And its extremely easy to do with my method! Probably dramatically more so than any other way. I simply add a
#include “filename.test.cpp”
to my single everything.cpp file just after
#include “filename.cpp”
and I am instantly productive.
Even better I can change the entire configuration/implementations by just changing a few > template parameters!

Ishh... You actually have to modify code (by adding an include statement or changing a few template parameters) to add the unit-tests... that's very ugly, sorry. There are two common ways to setup unit-tests:

1) You put the "main()" function for the unit-test at the end of the cpp file containing the functions that are tested by the unit-test program, but you wrap that main() function with a compilation flag. As so:

// in a cpp-file:

#include "my_functions.h"

void foo() {
  //...
};

//... other function implementations.

#ifdef MY_LIB_COMPILING_UNIT_TESTS

int main() {
  //... all the unit test code.
  //... usually returns 0 for success and an error code otherwise.
};

#endif

2) You create a separate cpp-file for each unit-test and link it to your library.

The advantage of either of these methods is that you have no intrusion at all on your library's code itself. In order words, without changing anything in the code, you can seeminglessly compile all your code into static or shared libraries (and/or a set of executable applications) without leaving a trace of the unit-tests, and you can easily compile …

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

If this “careful method, with good interface designs and specifications, and comprehensive unit-tests, is a hugely useful and beneficial method” and if ¨there are rarely reasons to go back to the drawing table or to solve any difficult bug (there are always little typos and mistakes, but rarely anything serious)¨ how is it then that the biggest companies in the field (Microsoft, but I could also use other examples) isn't able to deliver on time its products, and even without such huge and significants bugs that it has, in the past, embarassingly crashed flagship presentation of their “new super-stable bug-free most-tested ever product in the world” ?

More recently in a previous discussion with Vanjiyan we came up with a bug in VC2009. I submitted the bug to Microsoft, they confirmed it. Surely, with the state-of-the-art techniques and seemingly perfect coding architecture you so eloquently described it should have been a breeze for a 73 billions annual revenue company to fix it giving that VC2009 is supposedly a flagship product? Wouldn't even a summer intern with such powerful tools you described been even able to suggest the fix himself? Well guess what: they respond it would be too difficult for them to fix and they would not fix it! So ciao, for that nice theory of easily repairable well-designed software!

Microsoft's coding practices are shameful, and have always been. They are primarily a marketing firm. If you read their internal communications, management has made it very clear that …

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

Here is a basic outline of how the vast majority of programmers work:

  1. Get an idea for a project, or be given a problem to solve from your boss or superior.
  2. Sit down alone or with your team to brainstorm / discuss / think about the best way to solve the problem.
  3. Draw diagrams to organize the specific parts will make up the code, understand the dependencies, split the responsibilities and sub-problems among the different parts of the code.
  4. Design the interfaces for the code, either alone or as a team, defining in a strict manner how each functions and classes will be used and what effects they will have (called post- and pre-conditions).
  5. Write header files which put these designed interfaces into concrete code in the form of class declarations, function declarations, and inclusion patterns.
  6. Split the implementation work among co-workers (or, on a lone project, split in terms of time (when you will do what part)).
  7. Work on implementing the interfaces you were given to implement, this goes into cpp files.
  8. Write a complete suite of unit-test programs to exercise and verify that all the functions implemented behave as required by the design specifications laid out in step 4. If tests do not pass, go back to step 7.
  9. Run a suite of integration tests to make sure that all the parts (written by you and your co-workers) interact as expected, if not, go back to either step 3 or 4.
  10. Deploy the product.
  11. ...

You see, …

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

To recall: I am not asking the moon:

No, you are not asking for the moon, but you are a bit too picky, you won't find an exact tool that does exactly what you ask for. But I guarantee that there are lots of tools that will satisfy all your needs once you get to know them. Remember that programmers often tend to prefer command-line tools, so, it's not always going to be plug-and-play, all bells and whistles tools like you seem to expect.

1) list the functions required by a file/function

I told you already, that's called a call-graph, see this example.

2) list all functions that are using my functions.

This is called a caller-graph, see doxygen instructions for CALL_GRAPH and CALLER_GRAPH.

Doxygen seems to be the tool you are looking for. But there are also many other tools that can either generate call/caller graphs or use such graphs for other purposes. For example, profilers like gprof or callgrind report their profiling results in the form of call-graphs (with execution times required by each).

One of the tool on the site, Graphviz, looked promising but it requires that you already have done one of my task (the reconcilisation of the function called with their definition) in order to run it.

Doxygen uses graphviz, like many other document-generation tools. Learn to use it.

KDevelop is probably useable on my Triskel/Ubuntu platforms but …

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

^ Granpa Jim

What gets me mad is those lame vocaleses that most R&B singers always feel the need to do. You know, when the singer takes one syllable, stretches it out forever and makes a whole "melody" out of going between high and low pitch while on that same syllable. Christina Agulera is a pretty extreme example of singers doing that kind of thing. I hate that stuff, it's the best way to screw up a good song just to show that you have a "great voice". Being a good singer is not about having the greatest voice, look at Leonard Cohen, Marylin Manson, and others, it's about conveying emotions (which may or may not require a powerful / accurate voice), and about striking the right cords (not all the cords, in a chaotic vichyssoise of high and low pitch vocals). That's what grinds my gears ;)

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

To your original question:

Is it possible to 1) count 2) extract types in/from a typelist using variadic templates.

The easiest thing is to put the list of template arguments into a tuple type and then extract the count and elements. As so:

template <typename... Args>
struct info_on_types {
  static const std::size_t count = std::tuple_size< std::tuple< Args... > >::value;
  template <std::size_t I>
  using element = std::tuple_element< I, std::tuple< Args... > >::type; 
};

However, you can more easily get the number of arguments in the variadic template pack using the sizeof... operator. As so:

template <typename... Args>
struct info_on_types {
  static const std::size_t count = sizeof...(Args);
  //..
};

Very often, I must say, it is easier to deal with tuples instead of variadic templates. Except in cases of function with variable arguments or constructor-forwarding functions, it is easier to dump the variadic template pack into a tuple and then carry the tuple type around instead (under-the-hood). That's just a little tip, while I'm at it.

I tried with GNU G++ something like this but it didn't work.

This because you have a syntax error (enums are not integers). Try using a static const std::size_t as the type for the recursive "value" computation (instead of the enum), and it will work.

Now, to your second set of questions (in the future, please start a new thread when you have a completely new set of questions, trying to keep things organized):

1) List all …

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

Hard coded time = 125ms
PreCalced Array time = 130ms
PreCalced Vector time = 624ms
Repetitive Calc time = 5444ms...

First observation, from your code, my first thought was: the compiler will optimize away the entire calculation part of the hard-coded loop. And that's gonna happen even at lowest optimization level (as long as it is in release mode). In other words, it will come down to this:

double CalcHardCodedVAls()
{
    for (int iCount = 0; iCount < numberOfReps; ++iCount)
    {
        if (iCount % dotFrequency== 0)
        {
            cout << ".";
        }
    }
    double valReturn = 33.23 * .00195779856;
    cout << valReturn << endl;
    return valReturn;
}

In the case of the array storage, it is very likely to be similar, with the calculation line as double valReturn = 33.23 * arr[8];. Which means, in effect, that all you are really measuring is the time that it takes to do the dot printing, and that's why the results are identical. A simple way to test this is to remove the dot-printing and check if you get very close to 0ms (under the same compilation conditions). This is also why r0shi added the += in the loop instead of the straight assignment, this actually forces the compiler not to optimize away the loop.

The only reason why the vector case was much slower than the array case, is because the compiler cannot infer the same things about a vector as it can about an array, …

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

cin (and other istreams) is a bit complicated to grasp at first, but here's the basic information you need to know:

cin is a buffer of data that accumulates whatever the user inputs, which it can then feed by various "extraction" methods. So, when the user writes something and then hits the enter-key, that data is placed on the buffer (internal to cin). When your program executes a line like cin >> userInput, the data is inspected (starting from the beginning of the buffer) for a floating-point value. It will skip meaningless characters like spaces, tabs, and new-lines, and will make sure there is a valid floating-point value there. If valid, it will set userInput to that value and will remove the extracted characters (skipped characters plus those making up the floating-point value) from the cin buffer. If invalid, it will leave the buffer intact and set an internal error flag (failbit to be precise). This sets cin into an error-state. When you evaluate it with !cin (or compounded as !(cin >> userInput)), it will be "true" if cin is in an error-state.

There are two things to notice. First, after one input failed, cin is in an error-state, which it will not "forget" on its own, you must tell it to forget about that error. This is what the function cin.clear() does, it tells cin to forget about its error-state. The second thing to notice is that extracting things from cin doesn't always extract everything from it. In fact, …

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

Most GUI tools will hide away the main() function, because you don't have to temper with it, shouldn't need to, and probably shouldn't, period. But if you want to know what it looks like or what it does, out of curiosity, I can tell you.

Typically, a GUI application is made up of two things: a main() function that creates the window, and an event-loop to handle messages relevant to that window. In Windows, the main() function is called WinMain() which replaces the main() function when compiling a Win32 application (as opposed to a "console" application). Usually, this function simply creates the window handle, attaches an event-processing function to it (i.e., a function pointer), starts the "execution" of the window (i.e., the window shows up and events start to get handled), and then it waits for it to be done (after you close the window). Usually, the WinMain() functions generated by typical GUI tools (like MFC, Qt, wxWidget, VCL, etc.) contain less than 10 lines of code. For example, this is a Qt main() function:

#include <QApplication>
#include <QTextEdit>

int main(int argv, char **args)
{
  QApplication app(argv, args);

  QTextEdit textEdit;
  textEdit.show();

  return app.exec();
}

The event processing is done via a call-back function, conventionally called WndProc(), which is registered to the OS as being the call-back for the created window handle. Basically, when you click anywhere on a window or push a key while in focus of that window, the OS creates …

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

1) Return-value-optimization (RVO):
The situation you describe is one of the basic applications of return-value-optimization. This is a classic optimization, permitted by C++, and implemented by all decent C++ compilers that I know of. You can check the assembly listings generated by your compiler for the given code to see what actual code it produces (if you do a lot of nano-optimization as you seem to imply, then you definitely need to learn to produce and read the assembly listings of your compiler).

Seems like this could be easily avoided through compiler in theory if syntax such as Vec4 c = a + b; was used.

Yes, the compiler can easily avoid the temporary in this case, and it will do so through RVO. Even for code like c = a + b;, RVO will apply as well, given certain conditions.

2) Plain-Old-Data types (POD types):
When types are very simple (C-struct like types), we usually call it a POD-type. If it meets a number of strict conditions, the compiler will also call it a POD-type and perform a number of more aggressive optimizations in that case. The conditions are basically that it should have a default everything (constructor, copy-constructor, copy-assignment, destructor), no virtual functions, and no non-POD data members. Essentially, this allows the compiler to assume that all creation, destruction and copy operations can be performed by trivial copying of the memory (like C-style memmove()). In other words, the compiler assumes there is no additional …

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

It appears you just don't have gcc installed (code-blocks or geany or kdevelop will not install the compiler, they are only IDEs). Run this command:

$ sudo apt-get install build-essential
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

"Antitrust" wasn't too bad either. But "Hackers" is the classic.

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

So, why this wouldn't work is because there could be some dependecies of this DLL that's present in probably another DLL?

No. It has nothing to do with the dependencies of the DLL, it has to do with the way the DLL code is packaged and what the import library contains (or doesn't contain). Let's do a quick review of the way these things are created and packaged:

To start, you have a bunch of cpp files (source files). Each cpp file is compiled separately (called the separate compilation model) as what is called a "translation unit" to create an object file (.o or .obj depending on compiler). An object file is a piece of compiled code, separated by functions (the code for each function). Each function is given a "symbol" (the name of the function, usually with some decoration or mangling) identifying the section of code that it corresponds to. In the compiled code in the object files, every function call that appears (except those that the compiler inlined) appears not as an actual function call instruction, but rather as a reference to the symbol of the function being called. So, each object file has a list of symbols that it defines (its functions) and a list of symbols (for each function) that it needs (you can obtain that list of defined and used symbols for a given object file by asking the linker for it).

A static library, or sometimes called an "archive" (in Unix lingo), …

myk45 commented: Thanks! +0