• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

C++ Help?

Status
Not open for further replies.
PistolGrip said:
Can you post an example? I am somewhat confused about your question.

Here is a nice guide
http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html
The compiler was giving me loads of weird errors like I'd never seen before. Essentially I had an object which held an array for a matrix math library. I was trying to build math operations on the matrices which would make it easier for the user of the matrix class. The code's on campus but it was silly errors. Essentially I am now saying matrixObject* += matrixObject2*. It's saved on campus anyway.
 

wolfmat

Confirmed Asshole
PistolGrip said:
More C++ Questions (and C/unix questions) from a Java developer:

* When you get exceptions, how do you guys easily trace where that exception comes from. Unlike Java I get hex locations to memory instead of source code lines. Is this just the code was compiled with non debugging info?
I'm guessing you're not referring to actual exceptions because that's a specific way of handling unexpected program flow.
If you're referring to errors, each error has its own set of output. For instance, if you have a segmentation fault, the memory address you're being referred to shows you what's in the vicinity of the relevant address.
So if you have "0x1d0ba6ff in main ()" after experiencing a segfault, that's where some piece of code tried to get to illegaly.
* Do any of you debug remotely? Are there free remote debuggers out there.
gdb supports remote debugging. http://davis.lbl.gov/Manuals/GDB/gdb_17.html

* how does dynamic loading of a library really work. when I load with dlopen does the Operating System then keep the code somewhere in memory and if another request is made, it uses the same code?
dlopen() gives you a handle with which you can access symbols. A good example is here: http://www.opengroup.org/onlinepubs/009695399/functions/dlsym.html

* what preferred tools do you use to debug, code in a unix environment. Currently I am using netbeans (with jVi plugin) along with its debugger which is fantastic and free. intelliJ for Java is untouchable though :(
gdb wrappers for IDEs are usually pretty good. I am hooked on Xcode right now, which ships with such a wrapper, and it's pretty cool.

* I hear there is a way to get a stack trace of a process while its running. How do you do this? Some people did this at work and were able to find a problem even though the process was still running and the trace did not affect the process. I think they were able to attach to the process and look the trace of a thread
That's really just debugging and looking at the stack. Check your debugger documentation. In gdb, the stack print command is bt.

Also, what were the toughest Interview questions you were ever given?
Why do you want to work here specifically?
Answer: I need the money, motherfucker.
 

krzy123

Member
While I like Visual C++ express, its a pain to use in any sort of cross compile scenarios. The main C++ compiler i use on now on windows when writing test routines is Dev-C++ (www.bloodshed.net), its easy and simple to use but keep in mind its old. I use it mostly to write test functions, or simple testing programs.

Here's another alternative if not mentioned: http://sourceforge.net/projects/codelite/

You could always go cygwin and gcc.
 

Chichikov

Member
PistolGrip said:
More C++ Questions (and C/unix questions) from a Java developer:
* When you get exceptions, how do you guys easily trace where that exception comes from. Unlike Java I get hex locations to memory instead of source code lines. Is this just the code was compiled with non debugging info?
If this is an exception that you throw (or control), you can do it in the exception class c-tor.
Though generally, I would advise against using structured error handling in C++.

PistolGrip said:
* Do any of you debug remotely? Are there free remote debuggers out there.
Visual Studio supports it, though I'm not sure if the free Express versions does.
If you're adventurous, windbg also supports it.
Not sure about a Linux solution though.

PistolGrip said:
* how does dynamic loading of a library really work. when I load with dlopen does the Operating System then keep the code somewhere in memory and if another request is made, it uses the same code?
Pretty much.
In simplistic terms, dlls have code segments, which are shared among all processes, and data segments which are loaded into each process' address space.
 

PistolGrip

sex vacation in Guam
Thank you all for the responses.

wmat said:
Why do you want to work here specifically?
Answer: I need the money, motherfucker.

ha!

That and the question: "Why do you want to leave your job" "giving myself a 20% raise fool!"

Visualante said:
The compiler was giving me loads of weird errors like I'd never seen before. Essentially I had an object which held an array for a matrix math library. I was trying to build math operations on the matrices which would make it easier for the user of the matrix class. The code's on campus but it was silly errors. Essentially I am now saying matrixObject* += matrixObject2*. It's saved on campus anyway.

hmm it should be something like this

matrixObject* += matrixObject2*.

Code:
//definition
MatrixWrapper & operator+=(const MatrixWrapper &rhs){
 ...
}

//call

MatrixWrapper  mObj , mObj2; 
mObj += mObj2

// or with pointers but make sure pointers point to something!
MatrixWrapper  mObj , mObj2;
MatrixWrapper  * mObj2Ptr  = & mObj2;
MatrixWrapper * mObjPtr = & mObj1;
//dereference the pointers because the operator belongs to the object not the pointer. 
(* mObjPtr) += (* mObj2Ptr);
 

jvalioli

Member
PistolGrip said:
Im sure a some major googling could answer these questions for me but I figure I join the conversation and support for a programming thread.

Also, what were the toughest Interview questions you were ever given?
So are we getting our Programming |OT| or is this it now?


Ducarmel said:
quick question are there any examples that uses greater than or less than in Switch statements or is that impossible.
C++? No, don't think so. You can do it some other languages (Perl, I think?).
 

Zoe

Member
Ducarmel said:
quick question are there any examples that uses greater than or less than in Switch statements or is that impossible.

Nope, you need a constant value.
 

Ducarmel

Member
Anybody have suggestions on how I can make this piece of code better and how I would use switch command in this it seems using switch would make this code a lot longer.

Code:
// Design and run a program that takes a numerical score and outputs a letter grade.
// Specific numerical scores and letter grades are listed below:
//            90-100 = 	Grade A
//            80-89 	= 	Grade B
//            70-79 	= 	Grade C
//            60-69 	= 	Grade D
//            0-59 	= 	Grade F

// In this program, create two void functions titled getScore and printGrade with an int argument.
// The function getScore should have a Reference parameter and printGrade should have a Value parameter.
// The function getScore will prompt the user for the numerical score, get the input from the user, and print the numerical score.
// The function printGrade will calculate the course grade and print the course grade.
// (Be careful and note that the assignment requires you to input the grade into getScore and not directly into the main function.)
// Do not forget to put in the proper prompts and appropriate output messages.
// (Note: This program is a natural for use of the switch command, but if?else structures will also work.)

#include <iostream>

using namespace std;
void getScore();
void printGrades();
int score;
int &grade = score;

void getScore (int&)
{
       cout << "Enter what score you got out of a hundred on the test?\n";
       cout << "And I will tell you the letter grade: ";
       cin >> score;
}

void printGrades(int)
{
       if (grade >= 0 , grade <= 59)
              {
                     cout << "You got a " << score << " that is an F.";
              }
       else if (grade >= 60 , grade <= 69)
              {
                     cout << "You got a " << score << " that is a D.";
              }
       else if (grade >= 70 , grade <= 79)
              {
                     cout << "You got a " << score << " that is a C.";
              }
       else if (grade >= 80 , grade <= 89)
              {
                     cout << "You got an " << score << " that is a B.";
              }
       else if (grade >= 90 , grade <= 100)
              {
                     cout << "You got a " << score << " that is an A.";
              }
}

int main()
{
       getScore(score);
       printGrades(grade);
       return 0;
}
 
Ducarmel said:
Anybody have suggestions on how I can make this piece of code better and how I would use switch command in this it seems using switch would make this code a lot longer.

Code:
// Design and run a program that takes a numerical score and outputs a letter grade.
// Specific numerical scores and letter grades are listed below:
//            90-100 = 	Grade A
//            80-89 	= 	Grade B
//            70-79 	= 	Grade C
//            60-69 	= 	Grade D
//            0-59 	= 	Grade F

// In this program, create two void functions titled getScore and printGrade with an int argument.
// The function getScore should have a Reference parameter and printGrade should have a Value parameter.
// The function getScore will prompt the user for the numerical score, get the input from the user, and print the numerical score.
// The function printGrade will calculate the course grade and print the course grade.
// (Be careful and note that the assignment requires you to input the grade into getScore and not directly into the main function.)
// Do not forget to put in the proper prompts and appropriate output messages.
// (Note: This program is a natural for use of the switch command, but if?else structures will also work.)

#include <iostream>

using namespace std;
void getScore();
void printGrades();
int score;
int &grade = score;

void getScore (int&)
{
       cout << "Enter what score you got out of a hundred on the test?\n";
       cout << "And I will tell you the letter grade: ";
       cin >> score;
}

void printGrades(int)
{
       if (grade >= 0 , grade <= 59)
              {
                     cout << "You got a " << score << " that is an F.";
              }
       else if (grade >= 60 , grade <= 69)
              {
                     cout << "You got a " << score << " that is a D.";
              }
       else if (grade >= 70 , grade <= 79)
              {
                     cout << "You got a " << score << " that is a C.";
              }
       else if (grade >= 80 , grade <= 89)
              {
                     cout << "You got an " << score << " that is a B.";
              }
       else if (grade >= 90 , grade <= 100)
              {
                     cout << "You got a " << score << " that is an A.";
              }
}

int main()
{
       getScore(score);
       printGrades(grade);
       return 0;
}
You can do this
Code:
switch (grade % 10)
case 9:
    //90-100
    break;
case 8:
    //80-90
    break;
...
 

Zoe

Member
Ducarmel said:
You can do that I thought a case only could have only one constant? I will try it out.

You have a unique constant for each case.

If you want to make the if..else block better, go from high to low. That way you only need to do calculate grade > 89, grade > 79, etc.
 

Zeppu

Member
CrayzeeCarl said:
You can do this
Code:
switch (grade % 10)
case 9:
    //90-100
    break;
case 8:
    //80-90
    break;
...

Um, no you need to do div not % since % is modulus. :)

That, and strictly speaking you have a lot of duplicate code. You should try:

char getGrade(int) {
//whatev
return 'A'..'F'
}

void printScore(score, grade)
{

cout << "You got a " << score << " that is an " << grade << ".";
}

Edit: Sorry i skipped over th comments. Ignore.
 

Ducarmel

Member
Zoe said:
You have a unique constant for each case.

If you want to make the if..else block better, go from high to low. That way you only need to do calculate grade > 89, grade > 79, etc.

Ok so to clarify on switch

switch()

case 1:
break;

case 2:
break;

.....

case 99:
break;

case 100:
break;

I would have to write out all 100 cases correct? If so is there is a better shorter way.
 

Zeppu

Member
Ducarmel said:
Ok so to clarify on switch

switch()

case 1:
break;

case 2:
break;

.....

case 99:
break;

case 100:
break;

I would have to write out all 100 cases correct? If so is there is a better shorter way.

Like CrayzeeCarl said. Since your grades are 10 points apart:

Score div 10 (integer division) will give you a number from 0 to 10 (let's call this x)
Then

switch (x)
case 10:
case 9: A; break; // cater for 90-100
case 8: B; break;
case 7: C; break;
case 6: D; break;
default: F
 

wolfmat

Confirmed Asshole
You can also set an array up that has 10 fields, and in each field, there's the letter score. Then you return array[score/10]. That's called a lookup. Spares you the checks, but sacrifices memory.
 

Ducarmel

Member
OK thanks for clearing that up. Still a little over my head of what I know so far with C++, so I will play around with it.
 

wolfmat

Confirmed Asshole
Just to clarify, here's some pseudocode (lookups are an important concept, especially for optimization purposes!):
Code:
lettergrademap = array[11]
lettergrademap[0]  = F
lettergrademap[1]  = F
lettergrademap[2]  = F
lettergrademap[3]  = F
lettergrademap[4]  = F
lettergrademap[5]  = F
lettergrademap[6]  = D
lettergrademap[7]  = C
lettergrademap[8]  = B
lettergrademap[9]  = A
lettergrademap[10] = A
function letterforscore(score):
   return lettergrademap[score/10]
And sorry, that's of course 11 fields :p
 

Zeppu

Member
Oh, and don't forget to make sure the number input is within range. When grading assignments the first thing they try usually is to try and input a -1 or a 250 to see how good your program is.
 

poweld

Member
josephdebono said:
Oh, and don't forget to make sure the number input is within range. When grading assignments the first thing they try usually is to try and input a -1 or a 250 to see how good your program is.
I dunno, what about extra credit? Also, I once received a -5% on a Spanish essay back in high school.

Damn the standard valid ranges, I aim to exceed.
 

rpmurphy

Member
Question for C programming: Say that a chunk of memory is allocated from the heap, and a pointer to that memory is passed into a function. Can the function verify how much memory was allocated without triggering a seg fault or bus error, or how to handle a seg fault or bus error so that the process isn't killed but just have the function return like a null value?
 

BlueMagic

Member
rpmurphy said:
Question for C programming: Say that a chunk of memory is allocated from the heap, and a pointer to that memory is passed into a function. Can the function verify how much memory was allocated without triggering a seg fault or bus error, or how to handle a seg fault or bus error so that the process isn't killed but just have the function return like a null value?

I, also, have a question about this. How much of memory allocation and such can you handle in C++? I mean, does it work the same way, or is it better/worse?
 
rpmurphy said:
Question for C programming: Say that a chunk of memory is allocated from the heap, and a pointer to that memory is passed into a function. Can the function verify how much memory was allocated without triggering a seg fault or bus error, or how to handle a seg fault or bus error so that the process isn't killed but just have the function return like a null value?


I don't think so. There is the sizeof operator that will tell you the sizeof the object but if you have allocated an array of things you would need to know how many you allocated and pass that into the function as well.
 

Slavik81

Member
BlueMagic said:
I, also, have a question about this. How much of memory allocation and such can you handle in C++? I mean, does it work the same way, or is it better/worse?
New is pretty much the same as malloc, but it gives you typesafety, automatic calculation of the amount of memory to allocate, it can be overriden by the class to provide additional specialized functionality, and it calls the class's constructor.

Generally, it's more convenient and it provides some object-oriented control. Under the hood, the actual memory allocation is generally more or less the same as malloc.

In C++, unless you know what you're doing and why, always use new and never use malloc.
 

Xelinis

Junior Member
rpmurphy said:
Question for C programming: Say that a chunk of memory is allocated from the heap, and a pointer to that memory is passed into a function. Can the function verify how much memory was allocated without triggering a seg fault or bus error, or how to handle a seg fault or bus error so that the process isn't killed but just have the function return like a null value?


No. Here's an example of what I recommend you do.

typedef {
int *ptr;
int size;

} my_struct;

...

my_struct x;
x.size = the_size;
x.ptr = (int*)malloc( x.size * sizeof(int) );
my_function( &x );
 

rpmurphy

Member
Xelinis said:
No. Here's an example of what I recommend you do.

typedef {
int *ptr;
int size;

} my_struct;

...

my_struct x;
x.size = the_size;
x.ptr = (int*)malloc( x.size * sizeof(int) );
my_function( &x );
Yeah, that's the hunch I had. And using a special struct doesn't really fit what I'm trying to do. Thanks a bunch for the help guys.
 

Xelinis

Junior Member
"With C, you shoot yourself in the foot. With C++, you accidentally create a dozen instances of yourself and shoot them all in the foot. Providing emergency medical assistance is impossible since you can't tell which are bitwise copies and which are just pointing at others and saying, 'That's me, over there.'"
 
Slavik81 said:
In C++, unless you know what you're doing and why, always use new and never use malloc.
Wrong! Use stl containers and put that crap on the stack!

(if you must dynamically allocate, std::auto_ptr is your friend)

...I'm being snarky of course, but part of the pain for myself when I was starting -- and most C++ programmers, I'd wager -- is the notion that pointers were "the way" to do things. But this isn't C. They're a way, but not necessarily the best one.
 

Chichikov

Member
rpmurphy said:
Question for C programming: Say that a chunk of memory is allocated from the heap, and a pointer to that memory is passed into a function. Can the function verify how much memory was allocated without triggering a seg fault or bus error, or how to handle a seg fault or bus error so that the process isn't killed but just have the function return like a null value?
You can't do it with C or C++ language constructs, but some heap implementations support it.
If you're developing in windows you can use the HeapSize function.

Though generally speaking, you probably want to be explicit about the size, like Xelinis suggested or just by passing an extra parameter.
Using functions like this for anything other then debugging or generic memory management is not recommended.
 

Slavik81

Member
Elfforkusu said:
Wrong! Use stl containers and put that crap on the stack!

(if you must dynamically allocate, std::auto_ptr is your friend)

...I'm being snarky of course, but part of the pain for myself when I was starting -- and most C++ programmers, I'd wager -- is the notion that pointers were "the way" to do things. But this isn't C. They're a way, but certainly not the best one.
The somewhat depends. Since I use Qt, that advice isn't really all that applicable to me. It has alternative solutions.

But really, my point was just not to use malloc in C++ unless you have a good reason.
 

Chichikov

Member
Slavik81But said:
really, my point was just not to use malloc in C++ unless you have a good reason.
There is really very little reason to use malloc.
It only makes sense if you're writing an OS agnostic code that achieve its portability through CRT.
And let's face it, no one is doing this shit anymore.

If you need to allocate arbitrary memory on a heap, use heap functions, it gives you much more control.
 

Ducarmel

Member
Code:
//Define a class called Plot that has private members of length and width.
//Include a constructor and a public function that calculates the area
// and the length of the boundary of the field.
//Use public functions in a program that computes and displays the area
// and the length of the boundary of the plot where the length and width are 7 and 9 respectively.
//Hint: The length of the boundary is 2 * (length + width).

#include <iostream>
using namespace std;

class Plot
{
public:
       int l,w;
       Plot (int, int);
	int area(){return  2 * ( l + w );};
	int perimeter(){return (l * w);};
private:
	int length;
	int width;
};

 Plot::Plot (int length, int width)
{
    length = l;
    width = w;
}


int main()
{
       Plot rec(7,9);
       cout << "The area of 7 and 9 is: " << rec.area() << endl;
       cout << "The Perimeter of 7 and 9 is: " << rec.perimeter() << endl;
       return 0;
}

It works with out errors but its just nor returning the right answers.
 
you shouldn't need the l and w variables, just use length and width.


and you're math is wrong.

area = length*width
parameter = 2*(length+width);
 

Zeppu

Member
First off, I think the declaration of the constructor must be within the class itself (i.e. before }; ) brainfart.
Secondly, your constructor does nothing. It's assigning the input parameter to the value of l and w, but should be the other way round.
Thirdly, you do not need l and w, and you definitely do not need them to be public.
Finally, the area and perimeter calculations are flipped.

So

Code:
class Plot
{
public:
       Plot (int, int);
	int perimeter(){return  2 * ( l + w );};
	int area(){return (l * w);};
private:
	int l;
	int w;

};

 Plot::Plot (int length, int width)
{
    this.l = length;
    this.w = width;
}

I renamed private members to l and w to avoid confusing them with the parameters. Constructor sets l and w to the input values.

Finally, to add finesse to your application, I suggest you declare constants LENGTH and WIDTH and always refer to those values when you need to. That way, changing the values for the program only requires you change it in two places.

Code:
const int LENGTH = 7;
const int WIDTH = 9;

main() 
{
   Plot rec(LENGTH, WIDTH);
   cout << "The area of " << LENGTH << " and " << WIDTH << " is " rec.area() << endl;
}
 

AcciDante

Member
My programming class is over now (got an A!), and now I'm trying to finish going through the text book before I have to return it. I'm going over classes now, and it's going well, but I'm a little fuzzy on one thing. I know how to make separate specification and implementation files, but I'm not sure why/when you would define functions in the implementation file. Can someone briefly explain?
 

Zeppu

Member
AcciDante said:
My programming class is over now (got an A!), and now I'm trying to finish going through the text book before I have to return it. I'm going over classes now, and it's going well, but I'm a little fuzzy on one thing. I know how to make separate specification and implementation files, but I'm not sure why/when you would define functions in the implementation file. Can someone briefly explain?

Mostly for clarity of code. Strictly speaking you can declare everything in one file and everything will work exactly in the same fashion. However with larger-than-trivial projects it makes sense to have an .h and .cpp file for each and every class. Declare constants, structs, and functions in the .h file and everything regarding implementation in the .cpp file. Silly little functions such as getters and setters can be implemented within the .h file itself as well. You'll find out that it makes everything much easier to deal with, since you can just sift through the .h files to find whatever you need and then go to the respective .cpp file to edit particular functions.

Always isolate code as much as possible and keep in mind the concepts of cohesion and coupling even when it comes to files. (i.e. minimize the number of #includes).

Also, yay congrats on your A!

Edit: Hahaha! Holy shit I forgot the most important thing of the whole concept as explained below :lol :lol
 

wolfmat

Confirmed Asshole
Also, header files serve as interface-like contracts, so anyone including them has guaranteed functions with specific signatures, constants are guaranteed to be known and so forth.
 

AcciDante

Member
Thanks, dudes.

josephdebono said:
Always isolate code as much as possible and keep in mind the concepts of cohesion and coupling even when it comes to files. (i.e. minimize the number of #includes).

I don't think I've seen cohesion or coupling yet...
 
Also it allows people to use the functions defined in the .h without having to see the implementation so as was said above it allows for better encapsolation, but it also allows you to hid your source code.
 

Zeppu

Member
AcciDante said:
Thanks, dudes.



I don't think I've seen cohesion or coupling yet...

Put very simply, cohesion should be as high as possible which means that functions and functionality are grouped together because they make part of a single common task. I.e. don't put file opening code in a class which handles mathematical functions.
Coupling should be as low as possible which means that the amount of communication between functions should only contain what is required and what will be used. I.e. don't pass a Person object to a class which would only print out the person's name, just pass Person.name;
 

Chichikov

Member
josephdebono said:
Finally, to add finesse to your application, I suggest you declare constants LENGTH and WIDTH and always refer to those values when you need to. That way, changing the values for the program only requires you change it in two places.

Code:
const int LENGTH = 7;
const int WIDTH = 9;

main() 
{
   Plot rec(LENGTH, WIDTH);
   cout << "The area of " << LENGTH << " and " << WIDTH << " is " rec.area() << endl;
}
I think you're going a bit overboard with this.
It's true that it's a good rule of thumb to never use "naked" constants, but it seem to me like the assignment here is the class, not the code that drives it.

AcciDante said:
My programming class is over now (got an A!), and now I'm trying to finish going through the text book before I have to return it. I'm going over classes now, and it's going well, but I'm a little fuzzy on one thing. I know how to make separate specification and implementation files, but I'm not sure why/when you would define functions in the implementation file. Can someone briefly explain?
Ignoring templates (and ignoring some other stuff, so don't be anal):

C++ doesn't really have the language concept of a specification files.
Header files are nothing more that code that get added to your cpp file by your precompiler.
In theory, you can achieve everything you want without using a single h file in your project.

In practice, header files are used mostly for forward deceleration, and therefore you can replace your #include directive with a copy paste of the header file and it will work (again, in theory, in reality there will probably be some issues).

But to bring this discussion back to reality, people mostly put function deceleration in header files.
For convenience and code brevity, it's not a bad idea to put the implementation short or inline functions (like accessors) in the header file as well.

Not ignoring templates:
I'm already boring myself so I'll be short - templates need to be in a header file.
 
Status
Not open for further replies.
Top Bottom