0

The compiler keeps saying 'class A' has no member named 'foo'. I am trying to use a function from a derived class with a pointer. Here is my code:

 class A{
  .....
};

class B:public A{
     virtual void foo() = 0;
};

class C:public B{
....
public:
    void foo(){
        ....
    }
};

I have a table of A pointers named Table and when trying

Table[j]->foo()

I am getting the compiler error.

What should I do except cast?

Quentin
  • 62,093
  • 7
  • 131
  • 191
SaSJo
  • 61
  • 7

2 Answers2

2

You have a compilation error because function foo is not declared in class A.

You can declare it as pure virtual in A like this:

class A {
     virtual void foo() = 0;
};

In derived classes you don't have to declare foo as explicitly virtual. If only C is a concrete class, you don't have to declare foo in class B at all.

If your example if you know that in your array of pointers to A you have only instances of class C you can explicitly cast to pointer to C but it is a sign of poor design and I don't recommend it:

static_cast<C*>(Table[j])->foo()
Pustovalov Dmitry
  • 998
  • 1
  • 9
  • 25
0

If you have a pointer to a base and want to access a member of the derived type you have to cast so you have a pointer to the derived type, either that or as in your case add foo() as a virtual member to the base.

class A
{ ... };
class B : public A:{
{
public:
  virtual foo() { std::cout << "B::foo" << std::endl; }
};
class C : public B
{
public:
  void foo() { std::cout << "C::foo" << std::endl;
};
...
A * arr[8];
for(int i = 0; 8>i; ++i)
  arr[i] = new C;
((B*)arr[0])->foo(); // will print "C::foo\n"

But if you added virtual void foo() = 0; to A then you could just do arr[0]->foo() and it would still print C::foo

Ron
  • 14,674
  • 4
  • 34
  • 47
SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23
  • 2
    "Aaarrrrrggghhh" at that C-style cast. There's no reason not to use `static_cast` or `dynamic_cast` here. – Quentin Dec 24 '17 at 16:47