Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Apr 16, 1998



Application Security Testing: An Integral Part of DevOps

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
  get_data(void) = 0;  // this should have a      
};                      //return type

class Temp_sensor : public sensor
  Temperature get_data(void);

class IBP_Sensor : public sensor
  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.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date