0

I know there's virtual functions, but no virtual variables. It wasn't added probably because it wasn't needed most of the time, but I've ran into a problem lately:

class A
{
public:
    int bar;
};

class B : public A
{
public:
    float foo;
};

class C : public A
{
public:
    double foo;
};

int main()
{
    std::vector<A*> v;
    v.push_back(new B());
    v.push_back(new C());

    std::cout << v[1]->bar << v[0]->foo; //error because it will not find 'foo' in A
}

Is there anyway that I can stop this error?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Henry
  • 53
  • 6
  • What type would you want `v[0].foo` to be? – Artyer Aug 17 '21 at 04:42
  • Where have read about virtual variables? – 273K Aug 17 '21 at 04:42
  • `because it will find 'foo' in A`, should it be `because it will not find 'foo' in A`? – 273K Aug 17 '21 at 04:44
  • 3
    C++ is a statically typed language. The type of each expression is known from the expression itself and the declarations of the operands. You apparently want `v[0].foo` to be either `float` or `double` depending on what was assigned to `v[0]`, but this is not how types work on C++. Besides, your code will not compile. You may want to read [this](https://stackoverflow.com/questions/274626/what-is-object-slicing). – n. m. could be an AI Aug 17 '21 at 04:54

1 Answers1

5

why dont you use virtual getter in both classes? like : virtual int getA() and virtual int getB()

it will be easier for you to access those variables then :)

  • 3
    A code example may help to make a good answer, I would suggest you add one so your answer would be better and more fleshed out. – mediocrevegetable1 Aug 17 '21 at 04:58
  • 2
    side note: Prefer to have functions that operate on the object to functions that get data from the object so the operation can be done elsewhere. If the work is done inside the object you probably don't need to know if the contained variable is an `int`, a `float`, a `foo` or wharever. – user4581301 Aug 17 '21 at 05:12