How do I overload virtual function with the same name but different returning data

As title says, how do I overload virtual function with the same name but different returning data? Here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <string>

class Obj {
    
public:    
    
    virtual int getX() = 0;
    virtual float getX() = 0;//problem
    
};

class A : public Obj {
  
  int x = 0;
  float x_f = 0f;
  
  public:
  
  int getX() {   
      
      return x;
   }
    
   float getX() {   
      
      return x_f;
   }
    
};

int main()
{
    
    Obj* obj = new A;
    
    std::cout << obj->getX() << std::endl;
    
}
Last edited on
You can't.

What version of the function do you want to call on line 37? How can the compiler know?
Last edited on
What should I do then? What other programmers do?
Last edited on
It depends. What are you actually trying to do? What does x represent?
This code is only sample of problem in my bigger code. In bigger code I'm trying to write getPosition function which retrieves position of a object and you can either retrieve vector (with 2 values) or enum Position. But I can write only one type of getPosition.
Two options I can think of off the top of my head:

I assume your enum Positions map to coordinates. Can you return the coordinates of the enum position instead of the enum value itself?

How is the calling function supposed to know if it will receive a vector or an enum value? Based on this knowlege, the calling function can decide between which of 2 functions to call: getPositionXY() and getPostionEnum().
Thanks :)!
Topic archived. No new replies allowed.