I would like to include an instance of "NewPing" in a class that I am making. In the getdistance method I need to call sonar.ping which I declare with NewPing sonar(PIN_TRIG, PIN_ECHO, MAX_DISTANCE); I'm not sure what to do from here though. I appreciate any tips!
You're going to need to create an instance of the NewPing class in your Robot class. In the getDistance() method, you need to exercise the NewPing instance, and make it return the distance value.
Sorry getDistance should not be private. But why would I want to init the NewPing object each time getDistance is called. Can't I init with the Robot constructor and then access it with getDistance?
The advantage is that your way won't work. What / where is your "sonar" variable? How do you define the variable without creating the object at the same time? Answer: use a pointer and new.
There is nothing at all wrong with new. It's excessive use of new / destroy or malloc() and free() that are frowned upon. Single allocation of an object at constructor time is perfectly fine.
The sonar variable is local to the function that you are defining it in. You need a way to break that variable out of that function so you can reference it in other functions.
I'm confused because in a function "NewPing sonar(pinTrig, pinEcho, MAX_DISTANCE);" works.
I suspect that you mean that in a sketch, that works. It works in a sketch, or in a function, because the instance is declared and initialized in a single statement.
In a class, the declaration goes in one file and the initialization goes in another. Therefore, it is not possible to declare and initialize in a single statement.
You could do the declaration and initialization in a single statement, as long as that single statement is executed every time you need the object/call a function that needs the object to do something. That hardly seems like the thing to do with your class.
Ok I used the class exactly as shown above and I get the following errors...
In file included from sketch_feb25a.ino:1:
D:\users\freak\My Documents\Arduino\progs\libraries\testclass/Robot.h:6: error: ISO C++ forbids declaration of 'NewPing' with no type
D:\users\freak\My Documents\Arduino\progs\libraries\testclass/Robot.h:6: error: expected ';' before '*' token