0

(Prob a duplicate)

I would really like to have function type() returning some value that can symbolize either class but it seems like it doesn't work that way.

#include <iostream>

class A {
public:
    char type() { return 'A'; }
};

class B : public A {
public:
    char type() { return 'B'; }
};

class C : public A {
public:
    char type() { return 'C'; }
};

auto main() -> int{
  A *b = new B;
  A *c = new C;

  std::cout << b->type() << "\n"; // leads to 'A' but expecting 'B'
  std::cout << c->type() << "\n"; // leads to 'A' but expecting 'C'


  return 0;
}
  • There's also `dynamic_cast` and `typeid` – KamilCuk Nov 30 '20 at 09:44
  • 1
    @KamilCuk Dynamic cast only work if there's at least one virtual method. – Arthur Tacca Nov 30 '20 at 09:51
  • You need `virtual`. Right now you never told the compiler that the `type()`s in each class should use virtual dispatch, so it rightly doesn't when you call `type()` through an `A*`. I would suggest to research more about virtual functions, oh and not ever to use `new` but instead `std::unique_ptr` or in this case just base references to subclasses. – underscore_d Nov 30 '20 at 09:52

1 Answers1

4

Using virtual functions.

#include <iostream>

class A
{
public:
//  vvvvvvv
    virtual char type() { return 'A'; }
};

class B : public A {
public:
//              vvvvvvvv
    char type() override { return 'B'; }
};

class C : public A {
public:
//              vvvvvvvv
    char type() override { return 'C'; }
};

auto main() -> int{
  A *b = new B;
  A *c = new C;

  std::cout << b->type() << "\n";
  std::cout << c->type() << "\n";


  return 0;
}

Output

Program returned: 0
Program stdout
B
C

Learn more

Why do we need virtual functions in C++?

Sprite
  • 3,222
  • 1
  • 12
  • 29