PDA

View Full Version : Proper way to implement a Class whose functions need to be used by different classes



dolevo
2nd December 2015, 10:01
Hi all,

Although I have been working with Qt for quite some time, I am lacking of some proper way of implementing some cases like below one.

There is an external library which does some image processing stuff using hardware. I created a class which uses this library and in this class I created some public functions that can be used from other classes if needed. Everything is fine and working ok. However, since this class needs to be used in different classes, I need to either pass some objects as parameters between different classes or I derive from that class. I know that this is not a good approach for this sort of case. Could anyone tell me the most proper way of handling this? How should I implement it so that I can reach those functions from everywhere?

Thanks.

Vikram.Saralaya
2nd December 2015, 10:32
A few points I would suggest:
1. The object oriented way of doing this is creating an instance of this class in a central place and pass this to all the classes that intend to use it.
2. Say the class you built is "Vehicle" which has a public member "GetVehicleNumber()". If you are building "Car" and "MotorBike" classes then ofcourse makes more sense to inherit from Vehicle rather than create an instance of vehicle or passing it around.
3. An alternative to point 1 is to use static class/methods and just include the header file and start using the public function (I don't like this or recommend this approach).

Regards
Vikram

yeye_olive
2nd December 2015, 10:34
In order to call a function, you need to provide the values it expects as input. Therefore, if your functions always operate on the same data, then you can spare the callers the need to supply an instance by turning them into (or wrapping them in) static methods. Otherwise there is no way around it: every caller must specify the instance on which the function should work.

jefftee
4th December 2015, 01:55
Another thing to consider is if you want to expose general functionality of your class that does not need to operate on a specific instance of an object, then you can make those static members that can be used w/o requiring an object, etc.