How do I call functions?

I am a very beginner. I am self taught and learning as I go. My question is after I create the functions. How do I invoke them in main()? Below is my code, but it is only 40% done. If anyone can just explain the concept of calling the function. I thought and read it was className.memberfunction() so in my case class Road.getLength(), but it does not work.

Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Road
{
    public:
    void setWidth();
    void setLength();
    float getWidth();
    float getLength();
    float Asphalt();

    //private:
    float global_Width;//measured in feet
    float global_Length; // measured in miles


};

void Road::setWidth()
{

global_Width = 24;//feet wide
}
 void Road::setLength()
{
    global_Length =(1/5280);//miles long in feet
}
float Road::getWidth()
{
    return global_Width;
}
float Road::getLength()
{
    return global_Length;
}
float Road::Asphalt()
{


float Thickness;
Thickness = (Thickness /12) * global_Width * global_Length;
return Thickness;
}
int main()
{
     new Road;

     cout << "Enter Thickness in feet";
     cin >> Thickness;


     return 0;
}

You create an object of type Road and then call methods from the object:
1
2
Road rainbow; //this will call a default built-in constructor since there are none present in the Road class
int kappa = rainbow.getWidth(); //this calls getWidth() method which returns rainbow.global_Length 


If global_Length was a public variable, inside of main you could do this (I would not recommend this):
1
2
Road rainbow;
int kappa = rainbow.global_Length;


I usually think of methods as descriptors, actions, and states that help define the object and what it can do.

If this was not what you were looking for, then maybe static functions is what you wanted to learn about:
http://www.learncpp.com/cpp-tutorial/812-static-member-functions/
Last edited on
I'm not sure why you made an object on the heap(besides that isn't how you make a dynamic object, Road ptrroad = new Road;), it would be better to have it on the stack in this case. Anyways, moving on to your question.

When it gets to cin >> Thickness it's simply going to get confused on what your float variable Thickness is because it isn't in scope. Make it a private member of your class and see what you can figure out from there.
Last edited on
Thank you both.
i think you need some more tutorials on classes:
http://www.cplusplus.com/doc/tutorial/classes/

http://www.cplusplus.com/doc/tutorial/classes2/

please read both of them.

you might also need a tutorial on dynamic allocation:

http://www.cplusplus.com/doc/tutorial/dynamic/

hope that was useful.
Last edited on
Topic archived. No new replies allowed.