Virtual functions

Virtual functions

If I have an abstract base class with a pure virtual function called get_data(), how do I declare the function in inherited classes to have different return types than get_data() in the base class? For example:

class sensor{public:  get_data(void) = 0;  // this should have a      };                      //return typeclass Temp_sensor : public sensor{public:  Temperature get_data(void);};class IBP_Sensor : public sensor{public:  IBP get_data(void);   // different return type};                      // required

In general, you cannot. Because code that calls a virtual function doesn’t need to know which class will service the call, it is important that all classes implement the function with the same arguments and return types. An important part of such a design is making sure your base class has the appropriate types.

The only other approach I can see is to have the function return a pointer or union or something that can contain different types of data depending on how it is used.

See also  Is Machine Learning Automating Creativity in Graphic Design?

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist