REALLY confused with class

Hello. I am learning about classes and I understand a bit on how they work: like functions, except in a much nicer and cleaner way.

I am doing a programming exercise with multiple sub-problems and I have been watching videos and looking at other examples, but I just can't get my head around it. I am confused with how I am supposed to pass data from my main .cpp file onto my class and writing out the definitions on my class functions.

Here is what I have so far.

main.cpp
 
edit :D


I'm not sure if I am on the right track. I am confused with all the get/set functions and I don't even know if I did the definition of the function set properly :/
May I get some tips and pointers? Thanks.
Last edited on
You are on the right track.

The point of get/set functions is to retrieve values when your member variables are declared as private, just like yours are in this class you have written.

All of your declarations are written in your ".h" file, and all of the definitions are in the ".cpp" file. The ".h" file is like a "here, these are the functions, what they are called, and what arguments they take", and the ".cpp" file is like "OK, here is how the functions work."

You are correct that your get/set functions need to be public (otherwise we would never able to access them).

When you want to your class inside main, all we have to do is include the ".h" file, and the compiler will take care of making sure that the ".cpp" file's functions are connected.
If someone else wants to use your class, all they need to look at is the header ".h" file - they don't need to see the ".cpp" file (they still need the .cpp file, but they don't need to look at it). All they care about is how to use the functions and what arguments they take, but they don't really need to know how you made those functions do what they do.

Go ahead and write the .h and .cpp files like you have been, and your compiler will take care of the rest. You don't need to include the ".cpp" file into anything, just the ".h" file.
Thank you JayZom. It's a huge relief knowing I am going in the right direction so far lol

I am a bit confused when you say that other people will need to see my .h file. I understand they need to see my .h (class file), but what I am confused is which .cpp they would need to see? Is it the .cpp file with the function definition, or the .cpp file where I execute the program?

 
edit :D


My updated code.
Is the function manipulate correct? I am unsure if it's correct or not.

*second update
 
edit :D


Am I on the right track with my function definition set and manipulate?
I am bad with math. I am actually taking two math classes this spring semester so that will improve.
Last edited on
I just mean that if someone else was to use your class, they don't HAVE to see your .cpp file. All they need to look at is the .h file. They still need the .cpp if they want to actually use your class, but they never have to look at the .cpp file if all they want to do is use your class for something.

Your get/set functions look fine. I use set/get methods in ALL my classes, so they are really useful. Or mutator/accessor, whatever you decide to call them.

The program doesn't actually get executed from your class's .cpp file (that is a whole other thing and long long rant). Your compiler will turn all your code into an executable, so you don't have to worry about that. Just worry about making sure the code does what you want it to.

Your manipulate function looks fine, but I would put the 4/3 in an extra set of parenthesis just to be sure (I don't remember the precedence for operators at the moment) - I always put everything in extra parenthesis (I think it makes it easier to read), but if the output is correct then I wouldn't worry about it.

The .cpp file is where you define the function - that is where you actually write the code and tell HOW your function is going to do what it's supposed to. The .h files is just there to list declarations (it tells about your class, it's variables, and functions, but it doesn't tell HOW the functions work, only what they do).

I have only had a few cases where others needed to see my .h file, and no one has ever asked to see my .cpp files (except for my professors, of course, so that they can grade it). So, other than that, I wouldn't worry about that part too much. Maybe others can comment about how they share their code with coworkers.

In your .h file, you don't need to define your functions. That's what the .cpp file is for.

Of course, you CAN define all your functions in your .h file, but we usually don't, and I think your instructors (if you are in school - either way, props for taking on C++, which, according to most students, is one of the hardest languages to learn as a first programming language) wouldn't want you to do that. In the real world, we use .h and .cpp files (there are some exceptions, but we don't need to go into that).

Also, that's why you don't need to include your .cpp file when you want to use your class. Notice how you only have to write "#include "myClass.h""? That's because your other files don't care HOW the functions work, they just need to know what they do and what arguments they need to pass to the function, as well as what the function returns, if it returns anything - your compiler takes care of the rest.

Anyway, I could just keep ranting on about this.
I hope this helped.
I didn't really like classes when I first started programming, but now I don't do anything without using classes, it's the whole thing about object-oriented programming.
Just keep sticking with it, and you'll do great!
When I was looking up tutorials for set/get functions, I read mixed reviews about them.. I don't understand why but maybe that's just because I am a beginner xD

I actually updated that bit of code. I put it as 4/3.0 but I will put the parenthesis for better understanding. I would rather prefer writing out the definitions in a separate .cpp file. I think it looks neater; just a bit confusing for me a bit still. But I will continue doing class files throughout the holidays so I can get a better understanding of them.

I haven't tried out my code. I am stuck now on the print function. I don't know how to pass the values that my manipulator function calculated into my print function. It's confusing because the exercise says, "Write the definition of the member function manipulate that returns a decimal number as follows: If the value of description is 'rectangle,' it returns first * second; if the value of description is 'circle,' it returns the area of the circle with the radius first; (I am guessing pass the radius to the variable first?) If the value of
of description is 'sphere,' it returns the volume of the sphere with radius first; if the value of description is 'cylinder,' it returns the volume of the cylinder with radius first and height second; otherwise it returns the value -1."

and example would be if description = rectangle, first = 8.5 and second = 5, it returns:
rectangle: length = 8.50, width = 5.00, area = 42.50
Some help, anyone? :/
There's one way you could do it:

 
print(temporary.manipulate());


When you call this, "print" is called, but says "hey, wait, I have to call "manipulate" first, hold on "print" I'll be right back". So, "print" waits for "manipulate" to finish. When "manipulate" finishes, it returns its value, and "print" says "awesome! I can use that number!" Because you called "manipulate" INSIDE the call to "print", the value that "manipulate" returns gets sent to "print", and "print" should print out whatever that value is.

You'll have to change your definition of "print" to take a double value as a perimeter PARAMETER.
Or you could add an extra variable to your class that will store the result for manipulate. Since "manipulate" has to return something, I would change "print" so that it takes a "double" as an argument.
Last edited on
Chick3n13, this is pretty good. You're asking all the right questions and you fixed a bug that trips up 99% of beginners (4/3*3.14). A few suggestions:
- Specify a lot more digits of PI: 3.14159253589793.
- set() should just set the values:
1
2
3
4
5
void Temporary::set(string newDescription, double firstNum, double secondNum){
    description = newDescription;
    first = firstNum;
    second = secondNum;
}

Don't use the member variable names in the constructor - they hide the member variables. To see this consider:
1
2
3
4
5
Temporary::Temporary(string description, double first, double second){
    description = description;
    first = first;
    second = second;
}

This is asking the compiler to read programmer's mind and know that "description" on the left side is different from "description" on the right side. In C++ these are the same variable (the parameter) so the member variable "description" doesn't get changed.

Do it like this instead:
1
2
3
4
5
Temporary::Temporary(string desc, double f, double s){
    description = desc;
    first = f;
    second = s;
}

or better:
1
2
3
Temporary::Temporary(string desc, double f, double s){
    set(desc, f, s);
}

or even better:
1
2
3
4
5
Temporary::Temporary(const string &desc, double f, double s) :
    description(desc);
    first(f);
    second(s);
}


Why do you have both void get(string&, double&, double&); and the individual get() methods? The individual ones will do.

I don't use get() and set() methods unless there is a clear need for them. Using them "just because" adds certain complication for possible future benefit. In this case the ones you've defined don't provide any benefit. I'd get rid of them or change them to get/set logical values, which would provide some benefit:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
private:
    string description;
    double first;  // radius or width
    double second; // height
public:
    setRectangle(double width, double height)
    setCircle(double radius);
    setSphere(double radius);
    setCylinder(double radius, double height);

    string getDescription() const;
    double getRadius() const;
    double getWidth() const;
    double getHeight() const;

Damn JayZom, you explain in such a way I can really understand it :D Thanks!


Yea dhayden, yesterday when I was writing out the definition for the individual set/get, I thought to myself the same thing, "why would I have void get(string&, double&, double&); when I have the individual ones?" but it's part of the exercise so I just copied everything down. Even now it makes my eye twitch and don't understand why it needs both the individual sets and the longer one..

I really like your example of how you would organize your member functions dhayden

So this is what I have now (I'll just post changes from .h and .cpp definition)
void print(double);
That is from .h
is that what you meant JayZom? Or is it like this
double print(double);

 
edit :D

There is the .cpp function definition now..

I went with your first example for the constructor dhayden as that is the one that made the most sense to me!

*update*
1
2
3
void Temporary::print(Temporary.manipulate()); {
	//print values of the instance variables and the values returned by manipulate
}


I put that in but it is giving me an error.

*update 2*
1
2
3
void Temporary::print(){
	//print values of the instance variables and the values returned by manipulate
	cout << Temporary::manipulate();

Oh my glob!! I tried that with rectangle and it returned the perimeter :D I got SO HAPPY I am finally making progress :'D Thanks guys really freaking appreciate it!!! I won't close it down yet as I might have more questions
Last edited on
Yes, this is what I meant
 
void print(double);


Also, what you just did will also work
1
2
3
void Temporary::print(){
	//print values of the instance variables and the values returned by manipulate
	cout << Temporary::manipulate();


Both of those will do just fine.
Improved the code so it could be more "efficient." I don't like all the extra stuff but it got the job done! It outputs all the necessary information.

Thanks a lot JayZom.

I am curious though to how I could call the function manipulate with your
void print(double);
?

What would be the definition for that?

Again, thanks guys for the huge help! Happy holidays :D
Ah, I see what you mean.

Declare the function in your .h file
 
void print(double myDouble);


and then, in your .cpp file
1
2
3
4
void print(double myDouble)
{
    cout << myDouble << endl;
}


That's all you need to do for the definition.
When you call the function, do it like this: print(manipulate())

Since this is a class, and both "print" and "manipulate" are member functions of this class, you can solve this in a multitude of ways.

If you're working with an instance of your class (you created an object in main)
1
2
3
4
5
6
7
int main()
{

    Temporary myTemp;
    myTemp.print(myTemp.manipulate());
    return 0;
}


Or you could do it like you did before, that way also works perfectly:
1
2
3
4
void Temporary::print(){
	//print values of the instance variables and the values returned by manipulate
	cout << Temporary::manipulate(); 
}


I haven't actually sifted through all of your code, so you might have to adjust that to make it work with your definitions. But for the principles, that's fine. When you call "print" (the one with "double" in the parenthesis) all "print" wants is a double - it doesn't care where it came from. Since "manipulate" returns a double, "print" can take that double and do whatever it wants with it.

It's like you have a factory that's making, let's say, apple sauce. That factory needs apples, but if you're just making apple sauce, you can use apples from anywhere, they just have to be apples. If something gives you an apple, you can use it to make apple sauce.
Your function "print" is like that apple sauce factory. It needs a double, but it doesn't care where it came from. Your function "manipulate" is like a farmer that sells their apples - it provides apples to the factory.

Think about that. In your function definition and declaration, you don't have to tell "print" where the double is coming from, it just needs to know that it is a double. The apple seller doesn't have to tell the factory where the apple came from (OK, in the real world, yes, but this is the programming world, where factories don't question where apples come from). The apple seller just has to make sure it gives the factory an apple, just like "manipulate" just has to return a double so that "print" can use it.
Also, like dhayden said, you don't have to use get/set functions.

However, in an academic setting, it is probably a good idea, as your professors will most likely require you to use them. Exactly for what reason I'm not sure. Perhaps they are getting you prepared for interfaces, which is a whole new league of nasty. My professors explicitly define every single class I write in the course (which I don't really like), so I just write whatever functions they want me to. When I write my own code for fun, I don't write too many set/get functions, unless I'm making an interface, in which case you kind of HAVE to use them.
My professors explicitly define every single class I write in the course

From what I've read on this forum, most professor-defined classes are poorly designed. If something that your professor specified seems odd, it probably is.
The use of getters and setters usually turns into a philosophical debate. Programmers coming to C++ from Java usually expect to code a getter and setter for every private variable.

IMO, if you're going to code a getter and setter for every private member variable, you might as well make the member variable public (I'm not advocating that).

In the OO paradigm, what you want to look at are actions that are performed on an object. Using a battle between two opponents example, you don't want to call get_hit_points for each opponent, calculate the damage and then call set_hit_points for each opponent with the updated value. That violates encapsulation since the calling module must know how to apply damage. Instead, each opponent should have a take_damage () function. The take_damage() function evaluates the strength of the hit, health, any shields, etc and adjusts the hit points accordingly. That way only the opponent class needs to change if you decide to change how damage is applied. Externalizing hit_points through getters and setters means that changes to how damage is applied are scattered all over your code.
Yea, my professor required us to follow the code.. I didn't like they layout of my "final" code. I feel as if I could have done it a much cleaner way. Later when I get home I'll post it.

I am actually curious how you create GUIs?

My teacher comes from a Java background and used to teach Java, but he teaches c++ now because of the text.

What happens if the member variables were public?
What happens if the member variables were public?

If variables are public, you expose those variables so that any code in your program can modify them. Not a good practice.

Last edited on
What happens if the member variables were public?

As AbstractAnon points out, the variables become accessible to any code in your program (or any code in any future program that uses your class if it's in a library). This can cause trouble if the member is somehow "linked" to other variables in a logical way, or if only certain values are allowed etc. It also means that if you change the representation of the class in memory then client code will have to recompile. These are all good reasons for making variables private and using accessor methods.

The down side is that with accessor methods you can't create a reference or pointer to the member, and you can't use ++ or -- (or +=, -= etc) on it.

For the type of programming that I do, the drawbacks are frequently not worth the benefits. My classes are usually isolated to a program and thus recompiling is an easy option. Even when they are in a library, the code is used within the company so we can recompile.

So to me, you should use your head: create accessors when you need to, but not otherwise.
I said I would post my code (sorry for being late). I want to know how I could have done it in a much "cleaner" way.


function definitions
 
edit


I know that set function with all three variables should be gone. I just added it because the exercise required it. But I feel like my print() and manipulate() function could have been declared in a much nicer way.

If anyone could give me some tips I would appreciate it.
Last edited on
Yup, You're on the right track, given the assignment. Note that in the real world there are better ways to do this, but I suspect the prof will explain those next. In other words, he will say "there ought to be an easier way" and then show it to you.
Topic archived. No new replies allowed.