Bench 212 Posting Pro

Rule one of optimizing: Find a better algorithm.

I disagree there. Rule one of optimising: DON'T!

at least, not until you have a working program which has been thoroughly tested and the result of that testing has shown that it actually needs optimising; at which point, careful analysis needs to be done to make sure that the bits which are being examined for optimisation are actually the bits which are causing problems in the first place.

Bench 212 Posting Pro

There are several beginner level books which often come highly recommended by the real experts/guru's in the C++ community; i.e. those people who understand the language, and also understand the correct way to teach it.

- "Accelerated C++": http://accu.org/index.php?module=bookrevie...ch&rid=1185
- "You Can Do It!": http://accu.org/index.php?module=bookrevie...rch&rid=470
- "C++ Primer 4th Ed": http://accu.org/index.php?module=bookrevie...rch&rid=778
- "Programming: Principles and Practice using C++": http://cplusplus-soup.com/2009/02/01/programming-principles-and-practice-using-c/


The first book in that list, Accelerated C++, is an excellent introduction, but its extremely concise and condensed - the amount of good information per-page means that you might expect the same amount of information from a book with 3 times as many pages (although its worth reading cover-to-cover at least twice). if you're looking for a "gentler" introduction, then you might prefer one of the other books

"you can do it" is very hobbyist-friendly, and comes with a small graphics library which most of the book's examples make use of - again, this is a small-ish book, and covers the essentials of C++ with an emphasis on helping beginners get a firm grip on the fundamental building blocks - you would probably want to "graduate" from this one to Accelerated C++ if you were really serious about learning the language.

The other two books are more like big tomes. Principles and Practice is written by Bjarne Stroustrup - the man who created the C++ language; he uses that book to run Computer Science …

Bench 212 Posting Pro

I agree with daviddoria. C++ has taken several evolutionary steps beyond C. The first (and probably most difficult) step for you to take, is to get out of the C mindset of doing everything the long way, using arrays and pointers for everything. Instead focus for energy on learning the C++ standard libraries - you'll hopefully quickly realise that many common problems which you may be familiar with from C are already solved and packaged up neatly within the STL.

The <string> library replaces everything you might have previously done using char*
The STL replaces almost everything you might have previously done using arrays; particularly vector, list, set and map.
The stream libraries replace functions such as printf/scanf/fgets/sscanf/etc. Use <iostream>, <fstream> and <sstream>

Its probably worth getting familiar with strings, the STL and streams before getting into more hot water with classes on top of that. The worst thing you can do is begin mixing C and C++ - the languages are vastly different to each other, and really don't mix very well.

Bench 212 Posting Pro

This seems somewhat unnecessary to me - the STL will already do this for any container which supports bidirectional iterators - all of those containers support begin/end and rbegin/rend, so you can use the std::equal algorithm

#include <functional>
#include <algorithm>
#include <string>
#include <vector>
#include <iostream>

int main()
{
    std::string str("level");
    std::vector<char> vec(str.begin(), str.end());

    if ( std::equal(str.begin(), str.end(), str.rbegin()) )
        std::cout << "str is a palindrome" << std::endl;

    if ( std::equal(vec.begin(), vec.end(), vec.rbegin()) )
        std::cout << "vec is a palindrome" << std::endl;
}
Bench 212 Posting Pro

I am curious, but wouldn't this allow *any* class that happens to allocate the same amount of memory as Small?

No, That's not how it works - there are two overloaded functions which are used to determine the convertability.

small test(base&);
big test(...);

the class checks the sizeof the return types of these functions. the sizeof the return type will only be 'small' when the class is convertable to base&, otherwise, the type will fall into the ellipsis.


This isn't in any way circumventing the language constructs - its completely portable, and works on well-defined behaviour of the ellipsis operator ...

Bench 212 Posting Pro

Andrei Alexandrescu came up with a way to check convertability between types at compile time as part of his Loki library
http://loki-lib.sourceforge.net/

- you could use a similar trick to enforce the types which are allowed to use your container

class base {};
class derived : public base {};


template<typename T, typename Base>
class relationship 
{
    typedef char Small;
    class Big { char dummy[2]; };
    static Small Test(const Base&);
    static Big Test(...);
    static T MakeT();
public:
    enum { exists = 
        sizeof(Test(MakeT())) == sizeof(Small) };
};

template<bool> struct check;
template<> struct check<true> {};


template<typename T>
class container : public check<relationship<T, base>::exists>
{
};

int main()
{
    container<derived> cd;
    container<base> cb;
}
Bench 212 Posting Pro

if the base class were responsible for cleaning up memory within its destructor, then stopping that code being called would of course cause a memory leak.

I can't see how that could benefit you, unless you have some reason why you'd intentionally not want that memory to be released - if this is the case, then you should think about changing the design of your program (move the responsibility for that memory block elsewhere) - or create a copy before that memory is cleaned up.

Whatever code you wish to prevent being run in your base class destructor, you might think about moving it out of that destructor, or perhaps setting a flag which dictates whether or not some or all of that destructor is used

class base
{
    const bool cleanup;
public:
    base() : cleanup(true) {}
    base(bool b) : cleanup(b) {}
    ~base()
    {
        if(cleanup)
        {
            std::cout << "base destructor" << std::endl;
        }
    }
};

class foo : public base
{
public:
    foo() : base(false) {}
    ~foo()
    {
        std::cout << "foo destructor" << std::endl;
    }
};

class bar : public base
{
public:
    ~bar()
    {
        std::cout << "bar destructor" << std::endl;
    }
};

int main()
{
    foo f;
    bar b;
}
Bench 212 Posting Pro

The C++ string type can be converted to a const null-terminated string using .c_str() for interoperability with legacy C code. However, this poses a potential problem when mixing std::string with functions designed to mutate a string in-place.

a const_cast to get around this issue results in undefined behaviour, since the underlying representation of a std::string may or may not be null terminated. The ideal solution is to rewrite legacy code into C++, but this isn't always possible (For example, if the legacy code is part of a dynamically linked library) so a typical workaround is to allocate enough space to copy the C++ string into, then work with a non-const char*, before copying the the result back into the C++ string. these extra steps can be encapsulated into a wrapper class.

(This example demonstrated using Dave Sinkula's C string reversal function: http://www.daniweb.com/code/snippet216514.html )
Exactly what the legacy C function does is irrelevent here - the important outcome is that the code calling mystrrev() is not cluttered by memory management or string copying - instead, mystrrev() is passed a temporary c_string buffer which refers to the C++ string - when mystrrev finishes, the c_string automatically updates the original C++ string.


This wrapper class was born out of a need to convert legacy C-based code into C++ code, without needing to add clutter or to rewrite tried-and-tested functions

Bench 212 Posting Pro

This seems to be the age old 'artificial' problem that your classes are (at least in part) fundamentally unrelated to each another, but regardless of that they have an established relationship anyway; i.e, your classes do not share a common interface - the fact that they each have a function called setParams is irrelevent, because those functions have nothing in common with each other. I get the feeling that inheritance is maybe the underlying cause of your problem rather than part of the solution.

do you have any more concrete examples of what the real classes actually are? You might be able to build in a different kind of relationship, perhaps by splitting out the data processing/behaviour elements which maybe are related, and the data elements into separate classes.

Bench 212 Posting Pro

I believe private inheritance more accurately represents "implemented in terms of"; which is slightly different to 'has a'; the main difference being that a privately inherited implementation is guaranteed to be initialised before a class' own private members. Something which is associated with a few interesting initialisation tricks.

Bench 212 Posting Pro

Posting the errors you get is never pointless; People reading your post aren't psychic, so we have no idea what errors you're seeing; and they might try to compile it under a different compiler to you, which means they may get different errors (Especially if you use non-standard libaries like <conio.h>)

Bench 212 Posting Pro

I don't think there's anything in the standard which actively prevents &str[0] from being the same as str.c_str() - AFAIK its something left undefined.

Bench 212 Posting Pro
int length(string word)
{
	int len=0;
	for(int i=0; word[i]!=NULL; i++)
		len++;
	return len;
}

This function is completely unnecessary - it could also lead to undefined behaviour since the underlying representation of std::string is not necessarily "null terminated", which means that you could quite easily crash your program or do other strange things with this construct word[i]!=NULL However, it shouldn't matter, since std::string already has a "length" function;

std::string s("Hello, World!");
std::cout << "s is " << s.length() << " characters long" << std::endl;

Even if your length function appears to work, since a std::string is not null terminated, your length function may overrun if the first byte after the end of your string happens to be some other junk value (It may or may not be memory owned by the string - but don't leave it to chance - you've got a 50/50 chance of something going wrong). The only way to guarantee access to a null terminated string is with the .c_str() function - at which point you may aswell simply use strlen instead.

Bench 212 Posting Pro

p->prev looks to be a pointer: p->prev.next did you intend to do this instead? p->prev->next

Bench 212 Posting Pro

Some would argue that get and set methods themselves are a symptom of bad design, but even in those situations, they are still superior than providing direct access to a private member variable because they at least do you the service of preventing someone from obtaining a pointer-to your class' local data - something which is nearly always a bad thing.

As others mention, there's also the scenario where a simple set/get combination cease to be simple if perhaps constraints are added to the data (maybe an exception needs to be thrown if the data is invalid?), or perhaps the storage of that data is exported off to some other part of the program and it ceases to be a data member.

The reason we employ design idioms often isn't to add flexibility to a program - quite the opposite, its to add strict constraints to stop other programmers from breaking our code, by forcing the compiler to kick up an error when some other bit of code does something dumb.

IMO, The worst kind of code is usually that which has been designed with the sole intention of saving keystrokes.

Sulley's Boo commented: riiiiiiiiiiiiight +6
Bench 212 Posting Pro
//main.cpp
#include <iostream>
#include "player.cpp"

int main(){
    players();
    return 0;
}

Note that i've included player.cpp, not player.h (Which i accidentally named header.h, soz)

This is a terrible way of doing things, and can easily end up in creating a mess - please don't encourage others to #include a source (cpp) file.

the correct code should look like this:

#include <iostream>
#include "player.h"

.cpp files are intended to be used to hold definitions - they're not to be included within other source files unless you want a mess on your hands (Except in the rare situation when you might be playing around with splitting templates between files, but that's not the case here). .

So, unless you have some compelling reason to do otherwise (such as with templates) you should only use #include on a header file.

pspwxp fan commented: tnks :) +1
Bench 212 Posting Pro

the : after a constructor signature denotes the start of an initialisation list. Have a look here for a more detailed explanation:
http://www.cprogramming.com/tutorial/initialization-lists-c++.html


Line 18 is a template for an overloaded constructor which takes an array by-reference (Not by-pointer); Its not an essential part of the class though.

template<int N>
double_linked( T (&arr) [N]) : head( NULL ), tail ( NULL )

I added that to the example as a way to quickly initialise double_linked using an array of size N (where N is the template parameter, automatically deduced by the compiler).

An instance of that constructor is used here:

int arr[] = { 4, 6, 8, 32, 19 } ;
double_linked<int> dlist ( arr );

this call will create a constructor with the signature double_linked<int>::double_linked<5>(int (&)[5]) by way of deduction - the compiler knows that the array is size 5, and fills in the blank 'N'

Bench 212 Posting Pro

Here I know what exactly happened, and I want to show this message to the user

This is your major problem - exceptions should not be used for handling user errors, and users shouldn't need to know about exceptions which have occurred in your program - That is to say, if the user does need to know about it, then its not really an exception.

If you know exactly what happened, then you can deal with it in some other way. Exceptions are generally used for handling mistakes which you or another programmer might make when using your code - where those mistakes affect the inner workings of something else; for example, passing invalid data to a constructor or running an iterator or loop beyond the boundaries of a container. - situations where the best solution to a problem is to throw the error back to the calling code, and let that code clean up any mess which may have been left over.

You may be approaching C++ exceptions with a Java mindset, where exceptions are often used to handle all kinds of things (obviously, C++ is not Java). In C++ you should only use exceptions to handle circumstances which are truly exceptional - user interaction really isn't one of those things, since you should always be expecting that a user is likely type in something wrong, and don't really need to throw errors back to calling code.

Most of the time validation which can decay into …

Bench 212 Posting Pro

If you're doing this in C++, you might want to think about a vector of lists, e.g.

#include <vector>
#include <list>

int main()
{
    std::vector< std::list<int> > lists;
    std::list<int> new_list;
    new_list.push_back(1);
    new_list.push_back(2);

    lists.push_back( new_list );
}

As for a 'C' implementation:
Do you know how to create an array of pointers?
Do you know how to implement a linked list?
If you can do both of those, then that's 95% of the work.

This link appears in the "similar threads" box - maybe worth a read:
http://www.daniweb.com/forums/thread114911.html

Bench 212 Posting Pro

Probably the easiest way is to use a map (An associative container), which lets you associate "keys" (identifiers) with values/objects.

hello world;
    world.name = "Earth";
    world.size = 100;

    hello people;
    people.name = "Everyone";
    people.size = 2;

    std::map<std::string, hello> table;
    table["world"] = world;
    table["people"] = people;

STL maps come with a premade 'find' function, to let you find whether or not a 'key' exists within that map

std::map<std::string, hello>::iterator iter;
    iter = table.find(classname);

if the iterator returned by find reaches the end of the table, then that object doesn't exist in the map (strings are case sensitive too), otherwise you can use the iterator to access the object

if( table.end() == iter )
        std::cout << "object \"" << classname << "\" not found";
    else
    {
        hello& object = iter->second;
        std::cout << object.name << ' '
                  << object.size << std::endl;
    }

(quick example)

#include <string>
#include <iostream>
#include <map>

struct hello
{
   std::string name;
   int size;
};

void display_hello(const std::string& classname, std::map<std::string, hello>& table)
{
    std::map<std::string, hello>::iterator iter;
    iter = table.find(classname);

    if( table.end() == iter )
        std::cout << "object \"" << classname << "\" not found";
    else
    {
        hello& object = iter->second;
        std::cout << object.name << ' '
                  << object.size << std::endl;
    }
}

int main()
{
    hello world;
    world.name = "Earth";
    world.size = 100;

    hello people;
    people.name = "Everyone";
    people.size = 2;

    std::map<std::string, hello> table;
    table["world"] = world;
    table["people"] = people;

    display_hello("world", table);
    display_hello("people", table);
    display_hello("blah", table);
}

It would probably be better to wrap the map …

jonsca commented: Nice post +1
Bench 212 Posting Pro

The solution to your "do {} " problem is down to your own logic in the code. you can't write a "do{}" block on its own, so to fix it, you either need to remove do or you need to add a while statement.

The compiler pointed you to the correct line; In the place where you have return 0 its expecting while ( /* blah */ );. In other words the bracket before 'return' is the end of the "do" loop.

The fact that its there suggests you intended to repeat something, but only you could know what and why.


The structs aren't "branching off each other" - they're completely unrelated to each other, which is the problem. WeaponOne has no relation to WeaponTwo or WeaponThree, etc.

However, if you only had one Weapon struct, you could create as many Weapon objects as you like, and they'd all be related by the fact that they're all the same data type.
(That's where functions come in too - you can write a block of code which works for any Weapon object rather than just one Weapon object)


Maybe write some small toy programs to get an idea of how to use structs/functions - you will be able to see what's going on far more clearly.

Bench 212 Posting Pro

Errors like this are hard to see when your bracket alignment is all over the place.

The closing bracket before return 0; is the end of a "do {}" block, so its expecting a while statement.

On a more general note, you don't need to create all those identical structs with different names e.g, instead of WeaponOne, WeaponTwo, WeaponThree, write a single struct Weapon . writing a struct creates a data type, just like int, string, double, etc.

You could also do with breaking up your code a little using functions. a 700-line long main() function isn't much fun to look at; functions are there to let yoú write code once and repeat it however many times you like.

Bench 212 Posting Pro

a statically allocated array is "statically allocated" because its size is known by the compiler (its size is static - static means that it can't and won't change)

The compiler will ensure that a statically allocated array is created with a fixed size.

However, the compiler has absolutely no control over anything which is not known at compile time; this includes concepts such as memory addresses and user input, therefore there is no such thing as a statically allocated array whose size is known at runtime - its a pure contradiction


if you wish to create an array at runtime, then the compiler doesn't know how much space you need, therefore you must manually allocate and clean up memory yourself, or use a container which will handle memory at runtime (And is free to shuffle data around in memory for you, so maintaining pointers to elements stored in a container is undefined behaviour).

Perhaps you could shed some light on exactly what you're trying to do in 'real' terms? i.e. what problem are you trying to solve?

Bench 212 Posting Pro

That would be a contradiction in terms; an array whose size is decided at runtime is a dynamic array.

If you mean you'd like a dynamic array where you don't need to worry about explicit memory management, then the STL vector is C++'s "dynamic array".

edit: But having seen what you're trying to do, that would cause more problems than it would solve.
Why are you trying to use a map to delete some objects which that map is not responsible for? The obvious solution would be to redesign your program so that the map itself is responsible for the objects, not the array.

I come before you, to stand behind you,
To tell you something I know nothing about.
Next Thursday, which is Good Friday,
There will be a mothers' meeting for fathers only.

Bench 212 Posting Pro

The code nick used is pretty similar to the example i showed using an absolute position

given a string called str string str = "Thequickbrownfoxjumpsoverthelazydog"; (1) find the position of 'j' int where = str.find('j'); (2) store the substring of 0..where string snip = str.substr(0,where); (3) erase the substring of 0..where str.erase(0,where); (4) append the snipped string str += snip;

Bench 212 Posting Pro

Templates and operator overloading are just tools like everything else in C++ - Use them when they're appropriate. If you understand what they're capable of, you'll be able to recognise for yourself where and when they might be useful; but if you'd like some specific examples, then look no further than the STL

Bench 212 Posting Pro

Do you have an example of input/output?
e.g. using 'substr' and 'erase' on a std::string

std::string str = "Hello, World";
    std::cout << str.append(str.substr(0,5)).erase(0,5);

"Hello, World!" cut at position 5 and appended to the end becomes ", WorldHello"

It would help knowing what your code is supposed to do before knowing what's wrong with it.

Bench 212 Posting Pro

The problem is in your Add function - When you read anything using cin >> , there'll be (at least) a newline character left over from when the user hit 'enter';

using cin.ignore() will discard one character, but if the user typed in any other junk, you might sometimes need to discard more; a better way to do that would be to tell cin.ignore to ignore everything

#include <limits>
std::cin >> x;
std::cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
Bench 212 Posting Pro

From the question, It seems like the program is quite easy. I am not sure why you have so much code . If I am not Completely wrong, is this what you are trying to do?

If you'd read the OP's code, you'd see that they are trying to write a string class, not a procedure in main. Most programs can be written without using OO/classes, but that rather defeats the point if their goal is to write a class.

Also, having also read the question, and the rest of the thread, I think you're some way off the mark, since the OP wanted to find the first and last occurrances of a character rather than every single one (Something which std::string will do with find_first_of and find_last_of).

(Apologies to the OP for the off-topic tangent)

but as for your code, there are occasionally times and places where 'goto' is arguably acceptable to break out of complex blocks as a "Labelled break"; but goto loops are pure evil and epitomise ugly spaghetti code; If you're going to write code inside an infinite loop, then you should make it obvious to someone reading by writing while(true) or for(;;) or something similar instead of letting someone have to guess or trace through your goto labels;

The problem with code which masks its true intentions is this: if someone else maintaining your code reads something like that, they might not immediately see the infinite loop (especially not if they're …

Bench 212 Posting Pro

Modern C++ beginner books start out by introducing vectors early on, sometimes without mentioning arrays at all except for the final chapters where they're discussed in among the 'C' subset of the language.

They do this for a good reason; C++ has been deliberately designed with the aim that programmers should never need to use arrays; the STL which all but replaces arrays is easy to learn, easy to use, safer, and usually more efficient. (Despite this, there are still a few odd situations where arrays are the best solution to a problem, but those are less common.).

If you're still in the early learning phase, skip arrays for now and focus on the STL (Hopefully you have a modern book which does this too). You lose nothing by learning how to use vectors, iterators and algorithms, and hopefully gain alot more in the time you spend than if you were to spend alot of time working with arrays.
You can go back to arrays later on when you're more comfortable with the basic parts of the STL, and you'll be in a far better position to see for yourself why arrays don't get used much.

Bench 212 Posting Pro

My first guess would be that seed could mean a number to pass to the srand function, for random numbers.
http://www.cppreference.com/wiki/c/other/srand


Otherwise, the best person to ask is whoever provided you with the details of the problem

Bench 212 Posting Pro

error C2146: syntax error : missing ';' before identifier 'ip1'

this is the error when i compile it.

Included in learning how to write C++ code is learning how to troubleshoot extremely common and self-explanatory compiler errors. The compiler has told you exactly what's wrong and where, why not try to fix it?

Bench 212 Posting Pro

This is unrelated to your compiler error, however, you've added #include <string> at the top of your program, but you're not using it; I imagine if you replaced every reference to char[] and char* with std::string instead, your program will get a lot easier.

Bench 212 Posting Pro

I know there are many things like this on this site already but my teacher is smart and will search to find out if we just copied from an internet interveiw

So you figured that a good way to avoid being caught cheating would be to beg on an IT forum for someone else to do your homework for you instead

For this course we are required to write a research paper on engineering career that we wish to pursue.

then DO the research. If you want a career, then cheating your way through a course through plagiarism won't get you it, unless your career of choice is flipping burgers.

By the way, "copying" is not plaguarism; in fact, correct research techniques usually require you to "copy" facts and quotations from documents/journals/books/websites.
Plagiarism is the act of passing someone else's work off as your own; Use google and learn about Referencing.

Bench 212 Posting Pro

Have a look at these reviews. The books listed are generally considered 'best of breed' beginners books in the C++ community
- "Accelerated C++": http://accu.org/index.php?module=bookrevie...ch&rid=1185
- "You Can Do It!": http://accu.org/index.php?module=bookrevie...rch&rid=470
- "C++ Primer 4th Ed": http://accu.org/index.php?module=bookrevie...rch&rid=778
- "Programming: Principles and Practice using C++": http://blog.cplusplus-soup.com/2009/02/pro...d-practice.html

Bench 212 Posting Pro

Well there are also other ways.

Here is a another way :
<snip>

Did you post this to the correct thread? I don't see how that relates to anything that the OP wanted to do; they wanted to change the behaviour of a template class depending on its type.

There are actually much better ways to do that than a runtime exception - you can write "static" assertions which will generate a compiler error message instead of letting your program wait until runtime; There is a boost library called 'static_assert' which lets you do this with meaningful error messages. (static_assert will also probably become a new keyword in C++0x too)

Bench 212 Posting Pro

Sequences of characters (i.e. 'words' or 'plain text') are known as strings. In C++, strings are represented as a type of data called string

#include <string>  //allows you to use 'string'
#include <iostream>

int main()
{
    using namespace std;

    string name;
    cout << "What is your name?" << endl;
    getline(cin, name);
    cout << "Hello, " << name << endl;
}

Output

What is your name?
Joe Bloggs
Hello, Joe Bloggs

You can use >> aswell if you really want to, but be careful that >> only reads up to the first 'whitespace' character and leaves the rest of your input alone to potentially trip you up later on. (Which means that if you're on a modern desktop system, the next time you try to do something with 'cin' the first input you'll encounter will be whatever was left over)

#include <string>  //allows you to use 'string'
#include <iostream>

int main()
{
    using namespace std;

    string name;
    cout << "What is your name?" << endl;
    cin >> name;
    cout << "Hello, " << name << endl;
}

Output

What is your name?
Joe Bloggs
Hello, Joe
Bench 212 Posting Pro

What the OP wants to do is called downcasting. It's not recommended for the obvious reasons, but it's a feature that C++ supports using dynamic_cast because it's sometimes necessary:

Yes, but the example shown in the OP was attempting to access a Base object via a Derived pointer

PersonClass* Person = new PersonClass;
LawyerClass* Lawyer = static_cast<LawyerClass*>(Person);

Unless I've misread the OP's intentions their goal is to change the type of the object itself at runtime (i.e. they want to extend it to become a valid LawyerClass object instead of PersonClass); Since that most likely means extending the size of the PersonClass object, I can't see any way that could be done safely without creating a new LawyerClass object elsewhere.

Bench 212 Posting Pro

Think about the relationship described by inheritance, and why what you're doing isn't possible;

class Vehicle {};

class Bike : public Vehicle {};
class Car : public Vehicle {};
class Truck : public Vehicle {};

The relationship can be described as "IS A"; in other words, Car IS A Vehicle and Truck IS A Vehicle. But the reverse is not true - Vehicle is not a Truck, and Vehicle is not a Car; Vehicle is just a Vehicle.

A Vehicle could be used as a starting point to create a Truck, Car or Bike, maybe, since a Vehicle contains some of the information about those derived classes, but that information is incomplete. You can't change the type of an object, so you will need to create a new one instead, using the Vehicle object as the derived object's constructor information

class Vehicle {};

class Bike : public Vehicle 
{
public:
    Bike(const Vehicle& v) : Vehicle(v) {}
};
class Car : public Vehicle
{
public:
    Car(const Vehicle& v) : Vehicle(v) {}
};
class Truck : public Vehicle
{
public:
    Truck(const Vehicle& v) : Vehicle(v) {}
};
Bench 212 Posting Pro

hey, everyone. I am still learning templtes and I have 2 questions:
1-Why is it that all the examples of templates I have seen are about arrays?Is that all templates are used for?

I suppose because containers are the most prominent and easy-to-explain examples when it comes to introducing templates - its probably safe to say that you'll encounter a vector very early on in your C++ learning, and a vector is a great example of an application of templates.
Beyond that, templates can be (*ab)used for some immensely complicated, mind-bending solutions to address some very large and difficult problems.

* = Some would argue that templates were intended to be simple, but the true C++ Guru's in the world discovered that templates were actually capable of almost standing alone as an entirely new turing-complete programming language, albeit one which is incredibly ugly and sometimes hard to understand, but extremely powerful nonetheless.

2-after pondering about the above question, I decided to try something else witha template..a generic unction.
However the program just hangs when I run it. Only one object is created(because I always put a sentence in my constructors, to know when an object is created. the sentence appears only once.)
Can someone help me out? Thanks in advance!!

T dat1,dat2;
 display():dat1(0),dat2(0){

Your initialiser list assumes that dat1 and dat2 are capable of taking 0 as their constructor argument - but for std::string, this will actually do something really dangerous (that zero converts …

Bench 212 Posting Pro

I would consider the 'safer' way to be to ditch the array and go with an STL container such as a vector. In fact, a std::vector is often nicknamed a "C++ Array".
They're automatically initialised since they start out empty by default, and resize automatically every time you "push" some data into it

In addition, vectors are easier to use, and easier to learn (Which is reflected in the fact that some of the 'best of breed' C++ beginner books introduce vectors in their opening chapters)

Bench 212 Posting Pro

Edit - Never mind, I didn't read the OP correctly

Bench 212 Posting Pro

You can do exactly the same as you have described for your statically allocated array, then create a new smaller array and copy all of your remaining elements to it (This is an inefficient and perhaps slightly naive solution, but its a simple one)

Bench 212 Posting Pro

Have you made any changes to the fill_pair() member function?

The mapmaker class relies on compile-time recursion to populate an array of "pairs". I wonder if any modifications you may have made to this have caused it to overflow (Judging by the compiler error, it looks like you may have removed the 'terminating' member function, which is fill_pair<0>() - this is the member function which halts the compile time recursion)

template<int pos> void fill_pair()
    {
        table[pos].first = keys[pos];
        table[pos].second = vals[pos];
        fill_pair<pos-1>();
    }

    template<> void fill_pair<0>()
    {
        table[0].first = keys[0];
        table[0].second = vals[0];
    }
Bench 212 Posting Pro

For anyone who gets fed up with the somewhat verbose syntax involved in populating an STL map container with static arrays of std::pair (Or any of the other somewhat tedious ways of writing 'pair' combinations), here is a function which allows two different (statically allocated) arrays, of equal length, to be used to populate a map by copy-initialisation.

One popular use of STL maps is to create a custom indexed lookup table, where keys and values can be anything (which must obey all the usual STL map key/value rules). This is intended to make the process a little cleaner.

an example is shown in main()

Bench 212 Posting Pro

This code snippet outlines a simple, no-frills linked list. Tested under MSVC++ 2003 and Comeau, but not guaranteed bug free. Snippet includes example main() .

This snippet is intended as an example of a possible implementation of a linked list class (Of which there are many variations) For a better linked list, use the STL <list> library.

Bench 212 Posting Pro

Is it an unsound supposition or a mild form of deliberate insult?
Have you ever seen my home library?

No offense nor insults intended at all. I merely assumed from your post that you had not read some of the highly acclaimed books from the likes of Sutter, Meyers, Alexandrescu, etc. If i'm mistaken, then ignore my response - though I'd still be curious to know why you believe TCPPPL is the only good C++ book (Unless i've missed some hidden sarcasm or irony, in which case ignore this) - if you've read any books by the authors I've named here, you'd surely be aware of their standing among the C++ community.

Bench 212 Posting Pro

I have no comments. I think the only good book on C++ is "The C++ Programming Language" by B.Stroustrup ;)...

Even Stroustrup himself wouldn't say that. There are many really excellent C++ books floating around (of which TCPPPL is just one). If the only book you've ever read on C++ is that one, then you're missing out on a wealth of information.

Bench 212 Posting Pro

In the latest code you posted, you're using the case keyword after an if statement. case is intended to be used in conjunction with switch, and is meaningless on its own.

Perhaps you could also show the declaration of your tfgame object, and the declaration for ToggleWarhead

Bench 212 Posting Pro

can the name possibly be a number or something, it has to be something that I can increment by 1 or something before I make another atom object, and yes I have used pointers like once or twice but havent found too much use for them yet in my programming, maybe now is the time :)

so basically everytime I create an atom object its name has to be slightly different to differentiate between all the atoms created in the simulator.

Why do they need to have names at all? isn't it simply enough to be able to store un-named atoms in a vector and be able to find them using their position/index within the vector?
The "names" which you see when you're writing your code are for your convenience only - when you send your program through the compiler, those names become non-existant, because your computer doesn't need them - it remembers objects by their 'index' (address) in your computer's memory instead.