Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

Virtual functions

Question:
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 type

class Temp_sensor : public sensor
{
public:
  Temperature get_data(void);
};

class IBP_Sensor : public sensor
{
public:
  IBP get_data(void);   // different return type
};                      // required

Answer:
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.

 

 

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