Advertisement

C++ Workshop - OO Analysis, Design, & Porgramming (Ch. 6 & Ch. 11)

Started by July 03, 2006 11:00 AM
75 comments, last by Dbproguy 16 years, 9 months ago
Quote:
Original post by CondorMan
Thank you for the detailed responses. One final thing, does it *have* to be an underscore which differentiates the scope or could it be some other legal non-character (i.e. not 0 - 9, a - z, A - Z)?



On the topic of underscores in names, I would like to point out an important language rule.

C++ compilers tend to use a lot of private symbols in their library header files, from #include guards to complex macros and all kind of typedefs which you are not supposed to be aware of. Some other compilers provide language extensions requiring new keywords (e.g. __declspec or __attribute__). Unfortunately, any such name they use becomes unavailable to you, the programmer, so they take great care to use names you are not likely to want to use in your own programs: imagine the trouble if a header defined a class named 'x'.

Compiler writes adhere to a naming convention that ensures that there will not be any conflicts with user code, and C++ explicit puts the names they use off-limits to you, the programmer:

[IMPORTANT]
You must not use names that begin with an underscore, nor can you use names which have a double underscore anywhere in them:
#define __MY_INCLUDE_GUARD__               NO!int _x;                                    NO!class foo__bar                             NO!{   void do_stuff(int _X) {}                NO!};

[/IMPORTANT]

If you open a header file, you will see such names used, which is precisely why you must not use them. It is a naming convention for compiler and standard library implementers, not for the general C++ programming population.

A single trailing (x_) underscore is OK, but a leading (_x) one is not.

[advanced]
Note that the actual rules are slightly less restrictive than what I have stated, but until and unless you are ready to deal with such subtleties in the language, they form a useful guideline. I still use it.

While names containing a double underscore anywhere in them are absolutely reserved for the compiler (for example: for new keywords or automatically defined macros), the leading single underscore case is more complicated: names that begin with a single underscore followed by an uppercase letter (such as _T) are reserved for the standard library implementers's usage. A single underscore followed by a digit (such as _3) is OK.
Names that begin with a single underscore and a lowercase letter are reserved, but only at global scope. Meaning that while you cannot create a function or global variable named _x, a member function or variable is fine.

I think making the distinction is not worth the trouble, and prefer to adhere to the "leading underscore are evil" guideline. [smile]
[/advanced]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Hello all! I'm reposting the week 5 quiz...this time with questions for Chapter 11 and an EXERCISE at the bottom!

Greetings All!

It's once again QUIZ TIME!!! That's right, listed below are a set of quiz questions to help you test your knowledge and understanding of the material contained in chapters 6 and 11.

In addition to the questions and exercises below, make sure that as you're reading the book you enter the examples into your compiler, build the program, and run the executable. I know this is a time consuming process, but the repeat use of keywords, syntax, and semantics will help ingrain the information into your long-term memory. My advice is to create a simple "driver" project with a function main. As you read, enter the examples into function main, test it, and then erase it for use again in the next example.

PLEASE DO NOT POST THE ANSWERS TO THESE QUESTIONS OR EXERCISES. If you are unable to answer these questions, please ask for assistance, but DO NOT POST THE ANSWERS. Any question which is not marked with [Extra Credit] can be answered by reading your textbook. Questions which are marked [Extra Credit] either have been answered in the thread previously, or can be answered by doing a bit of research.

I will create an answer thread for these questions immediately, so that people will have a chance to get the answers more quickly.

Chapter 6 Quiz

1. What was the ‘C’ capability which allowed you to combine related variables? Did this solve the problem of connecting data with behaviors?
2. How do you make a new type in C++?
3. What is a class?
4. What is another name for variables within a class? What is another name for the member functions?
5. What are the requisite parts of a class declaration? Show an example.
6. What are the two things a class declaration tells your compiler?
7. When discussing naming conventions, what’s the most important point to remember?
8. What is an object?
9. How do you declare an object? Show an example.
10. What operator is used to access members and methods of a class for objects created on the stack.
11. What is the difference between public and private members/methods within a class? Which is the default?
12. In general, should methods or members be private? Why?
13. What is the primary way you initialize the member data of a class?
14. How can you identify a constructor for a class?
15. What is a default constructor? How is it called.
16. What does “declaring a method of a class const” mean? What is the syntax for such a declaration?
17. In the context of classes and objects, what is a client?
18. Where do class declarations go? Where do the member function definitions go?
19. When one class has a member variable which is an object of a different class they are said to form a ___ relationship?
20. What is the only difference between C++ classes and C++ structs?

Chapter 11 Quiz

1. What’s the purpose of a model?
2. What is the basic philosophy of iterative design/development?
3. What’s the difference between waterfall vs. iterative development?
4. What are the 6 steps listed in your book for iterative development.
5. What happens if you lose sight of the vision of your product?
6. What is a use case?
7. What is a domain expert?
8. What is an actor?
9. What are the 6 questions you should ask yourself about the actors when determining use cases, according to your book?
10. What is a domain model?
11. What is a scenario?
12. What are the 9 items, according to your book, should you include when documenting a scenario?
13. What is systems analysis?
14. What is the simplistic technique, according to your book, for determining the classes in your project?
15. What are the three areas of concern for the Static Model of your classes?
16. What is the most important principle when deciding the responsibilities of a class?
17. What are the two types of diagrams shown in the book for determining how classes interact?

Exercise 1 – The random character generator

In the game “Dungeons & Dragons” by WoTC, each player controls a character. The character has a number of attributes, specifically, they have Strength, Dexterity, Stamina, Intellect, Wisdom, and Charisma – each which can have a score in the range of 1 to 20. These “ability” scores are used to determine the success and/or failure of skills used, as well as how your character performs in combat. We’ll explore more of that later. For this week, I want you to write a program which contains a “Character” class. The character should have attributes representing the 6 ability scores, with accesses for each score. As well, the class should contain two constructors, 1 which takes as input 6 ability scores, and the second which is the default. The default constructor should randomly assign each ability score a value in the range of 1 to 20. To make it easier, I’ve posted the code below to help generate random numbers. Your main function should create two “characters”….one by using the default constructor, and one by passing in values between 1-20…might want to check in your constructor to make sure the input is valid (1-20). After both characters are created, use your accessors to print the attributes of each character to the screen with appropriate labels.
// Required headers#include <stdlib.h>#include <time.h>// Call this ONCE, in your main function to seed the random number generatorsrand( (unsigned)time( NULL ) );// Call this in your default constructor in order to generate a random number from 1 to 20.int randomNum = ( rand() % 20 ) + 1;


Cheers and Good luck!

Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
Chronicles of Elyria (An In-development MMORPG)
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints
Advertisement
While skimming through the regular Beginner's Forum I bumped into something new, and as it appears to be connected to stuff on week 5 I decided to post my queries in here.

So could someone give a nice thorough explanation of initializer lists?

P.S. Should I be posting my answers to quizzes and exercises, or is it fine to just do them and keep on my own HD?



Two questions concerning this weeks exercise.

1. Aren't there any non-.h versions of stdlib.h and time.h? I thought that using the .h was deprecated.

2. Calling the srand function once in your main looks a little bit weird. I know you only need to seed your rand function once, but doing it in main doesn't seem like the correct place to me when we use the rand function in the Character class. Where would you normally put this? I was thinking of a singleton which has the srand in it's constructor.

RinusMaximus,

Both good questions. Let me take a moment to answer them both in turn.

1. The .h extension is deprecated for header files which are part of the C++ Standard Library. The files which I indicated in the example are stdlib.h and time.h, neither of which are technically part of the C++ Standard Library. They are, however, system headers which pretty much come standard with all compilers. They are, for the most part, OS specific implementations which I imagine is why they're not part of the C++ Standard.

2. Again, you make a good observation. Seeding the random generator outside of the class (in main) requires the class to trust that the client will have initialized the random number generator. This is generally more trust than a library writer would give to his end-users. There's a couple of ways to solve this.

a. Initialize the random number generator within the constructor, and mark it with a static variable. Although we've not covered static variables yet within classes, the overview of them is this: they are members of a class - not members of an object, so their values are preserved across all objects of a class. So for example...lets say we created a static variable called m_IsInitialized. We would set it to false initially. Then, the first time a constructor was called for the class we could set it to true, and initialize the random number generator. Subsequent calls to the constructor of the class could check to see if the value was true or false before initializing the random number generator...if its true, we don’t re-initialize.

The problem with the above is that the "random number generator" is still a shared resource. So lets say some other object initialized the random number generator...then we created our first "Character" - we're still going to initialize it again - but now only once!

b. Don’t call the random number generator explicitly. Classes are generally designed to represent one object type, and the methods of the class should be things that object does. So does a character assign his own attributes? No. Someone else does. So the second alternative would be to assign the attributes of the class externally. There are two ways to do this.

First - we can create a "Character Factory" which is a class that sits above the character class logically, and is responsible for creating characters, assigning it its values, and then returning a reference or pointer to the class back to the client. This requires creation of the object on the heap (dynamically) so we’ll learn more about that later.

Second - The simpler method is, as you pointed out, to create a class which is responsible for both initializing the random number generator - and creating the random numbers. Then we can create a global instance of this class which could be passed to a Character's constructor, and a reference or pointer saved internally. Now, whenever the "Character" needs to create a random number it calls upon the object to return it a random number, rather than using rand() explicitly.

Hope this info helps a bit...

Cheers!
Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
Chronicles of Elyria (An In-development MMORPG)
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints
Quote:
Original post by jwalsh
RinusMaximus,

Both good questions. Let me take a moment to answer them both in turn.

1. The .h extension is deprecated for header files which are part of the C++ Standard Library. The files which I indicated in the example are stdlib.h and time.h, neither of which are technically part of the C++ Standard Library. They are, however, system headers which pretty much come standard with all compilers. They are, for the most part, OS specific implementations which I imagine is why they're not part of the C++ Standard.








Um, I beg to differ. While the .h extension IS depracated for standard library header files, both stdlib.h and time.h are standard C library files C++ has incorparated them into the C++ standard. The rule is: take the C standard file, remove the .h, and add a c to the front. So the files become cstdlib and ctime, respectively. So they won't 'pretty much' come standard with all compilers, they Must be included to be considered a C++ compiler.

Proof at these sites:

http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.vacpp7a.doc/standlib/ref/stdcpplib.htm

http://en.wikipedia.org/wiki/C_Plus_Plus_standard_library

Perhaps the most comprehensive one:

http://cs.stmarys.ca/~porter/csc/ref/cpp_standlib.html

Edit: some modifications

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

Advertisement
Well, you're sorta right. You hit on it, but didnt get it.

According to the ISO Spec for the C++ Language the "C++ Standard Library contains 32 headers...
<algorithm>    <iomanip>    <list>    <ostream>    <streambuf><bitset>       <ios>        <locale>  <queue>      <string><complex>      <iosfwd>     <map>     <set>        <typeinfo><deque>        <iostream>   <memory>  <sstream>    <utility><exception>    <istream>    <new>     <stack>      <valarray><fstream>      <iterator>   <numeric> <stdexcept>  <vector><functional>   <limits>

The facilities of the Standard C Library are provided by 18 additional headers but do not fall under the domain of the C++ Standard Library. Specifically, the naming convention - adding the c at the beginning, and the rules about what must be in these files is actually governed by the "C Standard Library Specification."
<cassert>    <ciso646>    <csetjmp>    <cstdio>    <ctime><cctype>     <climits>    <csignal>    <cstdlib>   <cwchar><cerrno>     <clocale>    <cstdarg>    <cstring>   <cwctype><cfloat>     <cmath>      <cstddef>

As well...there is a difference between a hosted and freestanding library. For example, cstdlib is a freestanding library - implementation specific, and is not required to contain the same content as stdlib.h. In the case of Visual Studio, cstdlib includes an additional header file and then wraps the contents of stdlib.h into the standard namespace by including stdlib.h itself. In other words, you can use either stdlib.h or cstdlib...depending on whether you want to use the C++ Namespaces or not.

I stand by what I said: "The .h extension is deprecated for header files which are part of the C++ Standard Library. The files which I indicated in the example are stdlib.h and time.h, neither of which are technically part of the C++ Standard Library."

But you are correct in your statement that cstdlib and ctime should be present to be considered a C++ complient compiler.
Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
Chronicles of Elyria (An In-development MMORPG)
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints
Dang, nobodynews got BURNED. Oh... wait. :(

Haha, just kidding. Thanks for the heads up, now I get what you were saying better.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

No problem. Thanks for pointing out my mistake. Dont want to give people the wrong information.

Cheers!



Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
Chronicles of Elyria (An In-development MMORPG)
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints
Hi, just found this amazing forum, i am skimming through the weeks to catch up (i already read the book till chapter 12)

Just wanted to ask regarding file placement with the Dev-c++ compiler;

when i try to;

- put class declaration in file "Soldier.hpp"
- put class implementation in "ClassSoldier.cpp", and this file includes "Soldier.hpp" on top.
- include "ClassSoldier.cpp" in main on top.

1: is this the correct manner to divide the files? (i understood so from the book)
2: if yes, why do i get error "multiple definition of `Soldier::Soldier(unsigned short, unsigned short)'
first defined here

(same error 10 times, once for each member etc., then one [linker error])

[Linker error] undefined reference to `Soldier::Soldier()'
ld returned 1 exit status

and the error doesnt even show me a line number as usual, and when i click on the error it doesnt bring me to the line in question as usual.






This topic is closed to new replies.

Advertisement